camlib.py 265 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. #import traceback
  9. from io import StringIO
  10. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, dot, float32, \
  11. transpose
  12. from numpy.linalg import solve, norm
  13. import re
  14. import sys
  15. import traceback
  16. from decimal import Decimal
  17. import collections
  18. from rtree import index as rtindex
  19. # See: http://toblerity.org/shapely/manual.html
  20. from shapely.geometry import Polygon, LineString, Point, LinearRing, MultiLineString
  21. from shapely.geometry import MultiPoint, MultiPolygon
  22. from shapely.geometry import box as shply_box
  23. from shapely.ops import cascaded_union, unary_union
  24. import shapely.affinity as affinity
  25. from shapely.wkt import loads as sloads
  26. from shapely.wkt import dumps as sdumps
  27. from shapely.geometry.base import BaseGeometry
  28. from shapely.geometry import shape
  29. from collections import Iterable
  30. import numpy as np
  31. import rasterio
  32. from rasterio.features import shapes
  33. # TODO: Commented for FlatCAM packaging with cx_freeze
  34. from xml.dom.minidom import parseString as parse_xml_string
  35. from ParseSVG import *
  36. from ParseDXF import *
  37. import logging
  38. import os
  39. # import pprint
  40. import platform
  41. import FlatCAMApp
  42. import math
  43. if platform.architecture()[0] == '64bit':
  44. from ortools.constraint_solver import pywrapcp
  45. from ortools.constraint_solver import routing_enums_pb2
  46. log = logging.getLogger('base2')
  47. log.setLevel(logging.DEBUG)
  48. # log.setLevel(logging.WARNING)
  49. # log.setLevel(logging.INFO)
  50. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  51. handler = logging.StreamHandler()
  52. handler.setFormatter(formatter)
  53. log.addHandler(handler)
  54. class ParseError(Exception):
  55. pass
  56. class Geometry(object):
  57. """
  58. Base geometry class.
  59. """
  60. defaults = {
  61. "units": 'in',
  62. "geo_steps_per_circle": 64
  63. }
  64. def __init__(self, geo_steps_per_circle=None):
  65. # Units (in or mm)
  66. self.units = Geometry.defaults["units"]
  67. # Final geometry: MultiPolygon or list (of geometry constructs)
  68. self.solid_geometry = None
  69. # Attributes to be included in serialization
  70. self.ser_attrs = ["units", 'solid_geometry']
  71. # Flattened geometry (list of paths only)
  72. self.flat_geometry = []
  73. # Index
  74. self.index = None
  75. self.geo_steps_per_circle = geo_steps_per_circle
  76. if geo_steps_per_circle is None:
  77. geo_steps_per_circle = int(Geometry.defaults["geo_steps_per_circle"])
  78. self.geo_steps_per_circle = geo_steps_per_circle
  79. def make_index(self):
  80. self.flatten()
  81. self.index = FlatCAMRTree()
  82. for i, g in enumerate(self.flat_geometry):
  83. self.index.insert(i, g)
  84. def add_circle(self, origin, radius):
  85. """
  86. Adds a circle to the object.
  87. :param origin: Center of the circle.
  88. :param radius: Radius of the circle.
  89. :return: None
  90. """
  91. # TODO: Decide what solid_geometry is supposed to be and how we append to it.
  92. if self.solid_geometry is None:
  93. self.solid_geometry = []
  94. if type(self.solid_geometry) is list:
  95. self.solid_geometry.append(Point(origin).buffer(radius, int(int(self.geo_steps_per_circle) / 4)))
  96. return
  97. try:
  98. self.solid_geometry = self.solid_geometry.union(Point(origin).buffer(radius,
  99. int(int(self.geo_steps_per_circle) / 4)))
  100. except:
  101. #print "Failed to run union on polygons."
  102. log.error("Failed to run union on polygons.")
  103. return
  104. def add_polygon(self, points):
  105. """
  106. Adds a polygon to the object (by union)
  107. :param points: The vertices of the polygon.
  108. :return: None
  109. """
  110. if self.solid_geometry is None:
  111. self.solid_geometry = []
  112. if type(self.solid_geometry) is list:
  113. self.solid_geometry.append(Polygon(points))
  114. return
  115. try:
  116. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  117. except:
  118. #print "Failed to run union on polygons."
  119. log.error("Failed to run union on polygons.")
  120. return
  121. def add_polyline(self, points):
  122. """
  123. Adds a polyline to the object (by union)
  124. :param points: The vertices of the polyline.
  125. :return: None
  126. """
  127. if self.solid_geometry is None:
  128. self.solid_geometry = []
  129. if type(self.solid_geometry) is list:
  130. self.solid_geometry.append(LineString(points))
  131. return
  132. try:
  133. self.solid_geometry = self.solid_geometry.union(LineString(points))
  134. except:
  135. #print "Failed to run union on polygons."
  136. log.error("Failed to run union on polylines.")
  137. return
  138. def is_empty(self):
  139. if isinstance(self.solid_geometry, BaseGeometry):
  140. return self.solid_geometry.is_empty
  141. if isinstance(self.solid_geometry, list):
  142. return len(self.solid_geometry) == 0
  143. self.app.inform.emit("[ERROR_NOTCL] self.solid_geometry is neither BaseGeometry or list.")
  144. return
  145. def subtract_polygon(self, points):
  146. """
  147. Subtract polygon from the given object. This only operates on the paths in the original geometry, i.e. it converts polygons into paths.
  148. :param points: The vertices of the polygon.
  149. :return: none
  150. """
  151. if self.solid_geometry is None:
  152. self.solid_geometry = []
  153. #pathonly should be allways True, otherwise polygons are not subtracted
  154. flat_geometry = self.flatten(pathonly=True)
  155. log.debug("%d paths" % len(flat_geometry))
  156. polygon=Polygon(points)
  157. toolgeo=cascaded_union(polygon)
  158. diffs=[]
  159. for target in flat_geometry:
  160. if type(target) == LineString or type(target) == LinearRing:
  161. diffs.append(target.difference(toolgeo))
  162. else:
  163. log.warning("Not implemented.")
  164. self.solid_geometry=cascaded_union(diffs)
  165. def bounds(self):
  166. """
  167. Returns coordinates of rectangular bounds
  168. of geometry: (xmin, ymin, xmax, ymax).
  169. """
  170. # fixed issue of getting bounds only for one level lists of objects
  171. # now it can get bounds for nested lists of objects
  172. log.debug("Geometry->bounds()")
  173. if self.solid_geometry is None:
  174. log.debug("solid_geometry is None")
  175. return 0, 0, 0, 0
  176. def bounds_rec(obj):
  177. if type(obj) is list:
  178. minx = Inf
  179. miny = Inf
  180. maxx = -Inf
  181. maxy = -Inf
  182. for k in obj:
  183. if type(k) is dict:
  184. for key in k:
  185. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  186. minx = min(minx, minx_)
  187. miny = min(miny, miny_)
  188. maxx = max(maxx, maxx_)
  189. maxy = max(maxy, maxy_)
  190. else:
  191. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  192. minx = min(minx, minx_)
  193. miny = min(miny, miny_)
  194. maxx = max(maxx, maxx_)
  195. maxy = max(maxy, maxy_)
  196. return minx, miny, maxx, maxy
  197. else:
  198. # it's a Shapely object, return it's bounds
  199. return obj.bounds
  200. if self.multigeo is True:
  201. minx_list = []
  202. miny_list = []
  203. maxx_list = []
  204. maxy_list = []
  205. for tool in self.tools:
  206. minx, miny, maxx, maxy = bounds_rec(self.tools[tool]['solid_geometry'])
  207. minx_list.append(minx)
  208. miny_list.append(miny)
  209. maxx_list.append(maxx)
  210. maxy_list.append(maxy)
  211. return(min(minx_list), min(miny_list), max(maxx_list), max(maxy_list))
  212. else:
  213. bounds_coords = bounds_rec(self.solid_geometry)
  214. return bounds_coords
  215. # try:
  216. # # from here: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
  217. # def flatten(l, ltypes=(list, tuple)):
  218. # ltype = type(l)
  219. # l = list(l)
  220. # i = 0
  221. # while i < len(l):
  222. # while isinstance(l[i], ltypes):
  223. # if not l[i]:
  224. # l.pop(i)
  225. # i -= 1
  226. # break
  227. # else:
  228. # l[i:i + 1] = l[i]
  229. # i += 1
  230. # return ltype(l)
  231. #
  232. # log.debug("Geometry->bounds()")
  233. # if self.solid_geometry is None:
  234. # log.debug("solid_geometry is None")
  235. # return 0, 0, 0, 0
  236. #
  237. # if type(self.solid_geometry) is list:
  238. # # TODO: This can be done faster. See comment from Shapely mailing lists.
  239. # if len(self.solid_geometry) == 0:
  240. # log.debug('solid_geometry is empty []')
  241. # return 0, 0, 0, 0
  242. # return cascaded_union(flatten(self.solid_geometry)).bounds
  243. # else:
  244. # return self.solid_geometry.bounds
  245. # except Exception as e:
  246. # self.app.inform.emit("[ERROR_NOTCL] Error cause: %s" % str(e))
  247. # log.debug("Geometry->bounds()")
  248. # if self.solid_geometry is None:
  249. # log.debug("solid_geometry is None")
  250. # return 0, 0, 0, 0
  251. #
  252. # if type(self.solid_geometry) is list:
  253. # # TODO: This can be done faster. See comment from Shapely mailing lists.
  254. # if len(self.solid_geometry) == 0:
  255. # log.debug('solid_geometry is empty []')
  256. # return 0, 0, 0, 0
  257. # return cascaded_union(self.solid_geometry).bounds
  258. # else:
  259. # return self.solid_geometry.bounds
  260. def find_polygon(self, point, geoset=None):
  261. """
  262. Find an object that object.contains(Point(point)) in
  263. poly, which can can be iterable, contain iterable of, or
  264. be itself an implementer of .contains().
  265. :param poly: See description
  266. :return: Polygon containing point or None.
  267. """
  268. if geoset is None:
  269. geoset = self.solid_geometry
  270. try: # Iterable
  271. for sub_geo in geoset:
  272. p = self.find_polygon(point, geoset=sub_geo)
  273. if p is not None:
  274. return p
  275. except TypeError: # Non-iterable
  276. try: # Implements .contains()
  277. if isinstance(geoset, LinearRing):
  278. geoset = Polygon(geoset)
  279. if geoset.contains(Point(point)):
  280. return geoset
  281. except AttributeError: # Does not implement .contains()
  282. return None
  283. return None
  284. def get_interiors(self, geometry=None):
  285. interiors = []
  286. if geometry is None:
  287. geometry = self.solid_geometry
  288. ## If iterable, expand recursively.
  289. try:
  290. for geo in geometry:
  291. interiors.extend(self.get_interiors(geometry=geo))
  292. ## Not iterable, get the interiors if polygon.
  293. except TypeError:
  294. if type(geometry) == Polygon:
  295. interiors.extend(geometry.interiors)
  296. return interiors
  297. def get_exteriors(self, geometry=None):
  298. """
  299. Returns all exteriors of polygons in geometry. Uses
  300. ``self.solid_geometry`` if geometry is not provided.
  301. :param geometry: Shapely type or list or list of list of such.
  302. :return: List of paths constituting the exteriors
  303. of polygons in geometry.
  304. """
  305. exteriors = []
  306. if geometry is None:
  307. geometry = self.solid_geometry
  308. ## If iterable, expand recursively.
  309. try:
  310. for geo in geometry:
  311. exteriors.extend(self.get_exteriors(geometry=geo))
  312. ## Not iterable, get the exterior if polygon.
  313. except TypeError:
  314. if type(geometry) == Polygon:
  315. exteriors.append(geometry.exterior)
  316. return exteriors
  317. def flatten(self, geometry=None, reset=True, pathonly=False):
  318. """
  319. Creates a list of non-iterable linear geometry objects.
  320. Polygons are expanded into its exterior and interiors if specified.
  321. Results are placed in self.flat_geometry
  322. :param geometry: Shapely type or list or list of list of such.
  323. :param reset: Clears the contents of self.flat_geometry.
  324. :param pathonly: Expands polygons into linear elements.
  325. """
  326. if geometry is None:
  327. geometry = self.solid_geometry
  328. if reset:
  329. self.flat_geometry = []
  330. ## If iterable, expand recursively.
  331. try:
  332. for geo in geometry:
  333. if geo is not None:
  334. self.flatten(geometry=geo,
  335. reset=False,
  336. pathonly=pathonly)
  337. ## Not iterable, do the actual indexing and add.
  338. except TypeError:
  339. if pathonly and type(geometry) == Polygon:
  340. self.flat_geometry.append(geometry.exterior)
  341. self.flatten(geometry=geometry.interiors,
  342. reset=False,
  343. pathonly=True)
  344. else:
  345. self.flat_geometry.append(geometry)
  346. return self.flat_geometry
  347. # def make2Dstorage(self):
  348. #
  349. # self.flatten()
  350. #
  351. # def get_pts(o):
  352. # pts = []
  353. # if type(o) == Polygon:
  354. # g = o.exterior
  355. # pts += list(g.coords)
  356. # for i in o.interiors:
  357. # pts += list(i.coords)
  358. # else:
  359. # pts += list(o.coords)
  360. # return pts
  361. #
  362. # storage = FlatCAMRTreeStorage()
  363. # storage.get_points = get_pts
  364. # for shape in self.flat_geometry:
  365. # storage.insert(shape)
  366. # return storage
  367. # def flatten_to_paths(self, geometry=None, reset=True):
  368. # """
  369. # Creates a list of non-iterable linear geometry elements and
  370. # indexes them in rtree.
  371. #
  372. # :param geometry: Iterable geometry
  373. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  374. # :return: self.flat_geometry, self.flat_geometry_rtree
  375. # """
  376. #
  377. # if geometry is None:
  378. # geometry = self.solid_geometry
  379. #
  380. # if reset:
  381. # self.flat_geometry = []
  382. #
  383. # ## If iterable, expand recursively.
  384. # try:
  385. # for geo in geometry:
  386. # self.flatten_to_paths(geometry=geo, reset=False)
  387. #
  388. # ## Not iterable, do the actual indexing and add.
  389. # except TypeError:
  390. # if type(geometry) == Polygon:
  391. # g = geometry.exterior
  392. # self.flat_geometry.append(g)
  393. #
  394. # ## Add first and last points of the path to the index.
  395. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  396. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  397. #
  398. # for interior in geometry.interiors:
  399. # g = interior
  400. # self.flat_geometry.append(g)
  401. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  402. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  403. # else:
  404. # g = geometry
  405. # self.flat_geometry.append(g)
  406. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  407. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  408. #
  409. # return self.flat_geometry, self.flat_geometry_rtree
  410. def isolation_geometry(self, offset, iso_type=2, corner=None):
  411. """
  412. Creates contours around geometry at a given
  413. offset distance.
  414. :param offset: Offset distance.
  415. :type offset: float
  416. :param iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  417. :type integer
  418. :param corner: type of corner for the isolation: 0 = round; 1 = square; 2= beveled (line that connects the ends)
  419. :return: The buffered geometry.
  420. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  421. """
  422. # geo_iso = []
  423. # In case that the offset value is zero we don't use the buffer as the resulting geometry is actually the
  424. # original solid_geometry
  425. # if offset == 0:
  426. # geo_iso = self.solid_geometry
  427. # else:
  428. # flattened_geo = self.flatten_list(self.solid_geometry)
  429. # try:
  430. # for mp_geo in flattened_geo:
  431. # geo_iso.append(mp_geo.buffer(offset, int(int(self.geo_steps_per_circle) / 4)))
  432. # except TypeError:
  433. # geo_iso.append(self.solid_geometry.buffer(offset, int(int(self.geo_steps_per_circle) / 4)))
  434. # return geo_iso
  435. # commented this because of the bug with multiple passes cutting out of the copper
  436. # geo_iso = []
  437. # flattened_geo = self.flatten_list(self.solid_geometry)
  438. # try:
  439. # for mp_geo in flattened_geo:
  440. # geo_iso.append(mp_geo.buffer(offset, int(int(self.geo_steps_per_circle) / 4)))
  441. # except TypeError:
  442. # geo_iso.append(self.solid_geometry.buffer(offset, int(int(self.geo_steps_per_circle) / 4)))
  443. # the previously commented block is replaced with this block - regression - to solve the bug with multiple
  444. # isolation passes cutting from the copper features
  445. if offset == 0:
  446. geo_iso = self.solid_geometry
  447. else:
  448. if corner is None:
  449. geo_iso = self.solid_geometry.buffer(offset, int(int(self.geo_steps_per_circle) / 4))
  450. else:
  451. geo_iso = self.solid_geometry.buffer(offset, int(int(self.geo_steps_per_circle) / 4), join_style=corner)
  452. # end of replaced block
  453. if iso_type == 2:
  454. return geo_iso
  455. elif iso_type == 0:
  456. return self.get_exteriors(geo_iso)
  457. elif iso_type == 1:
  458. return self.get_interiors(geo_iso)
  459. else:
  460. log.debug("Geometry.isolation_geometry() --> Type of isolation not supported")
  461. return "fail"
  462. def flatten_list(self, list):
  463. for item in list:
  464. if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
  465. yield from self.flatten_list(item)
  466. else:
  467. yield item
  468. def import_svg(self, filename, object_type=None, flip=True, units='MM'):
  469. """
  470. Imports shapes from an SVG file into the object's geometry.
  471. :param filename: Path to the SVG file.
  472. :type filename: str
  473. :param flip: Flip the vertically.
  474. :type flip: bool
  475. :return: None
  476. """
  477. # Parse into list of shapely objects
  478. svg_tree = ET.parse(filename)
  479. svg_root = svg_tree.getroot()
  480. # Change origin to bottom left
  481. # h = float(svg_root.get('height'))
  482. # w = float(svg_root.get('width'))
  483. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  484. geos = getsvggeo(svg_root, object_type)
  485. if flip:
  486. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  487. # Add to object
  488. if self.solid_geometry is None:
  489. self.solid_geometry = []
  490. if type(self.solid_geometry) is list:
  491. # self.solid_geometry.append(cascaded_union(geos))
  492. if type(geos) is list:
  493. self.solid_geometry += geos
  494. else:
  495. self.solid_geometry.append(geos)
  496. else: # It's shapely geometry
  497. # self.solid_geometry = cascaded_union([self.solid_geometry,
  498. # cascaded_union(geos)])
  499. self.solid_geometry = [self.solid_geometry, geos]
  500. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  501. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  502. self.solid_geometry = cascaded_union(self.solid_geometry)
  503. geos_text = getsvgtext(svg_root, object_type, units=units)
  504. if geos_text is not None:
  505. geos_text_f = []
  506. if flip:
  507. # Change origin to bottom left
  508. for i in geos_text:
  509. _, minimy, _, maximy = i.bounds
  510. h2 = (maximy - minimy) * 0.5
  511. geos_text_f.append(translate(scale(i, 1.0, -1.0, origin=(0, 0)), yoff=(h + h2)))
  512. self.solid_geometry = [self.solid_geometry, geos_text_f]
  513. def import_dxf(self, filename, object_type=None, units='MM'):
  514. """
  515. Imports shapes from an DXF file into the object's geometry.
  516. :param filename: Path to the DXF file.
  517. :type filename: str
  518. :param units: Application units
  519. :type flip: str
  520. :return: None
  521. """
  522. # Parse into list of shapely objects
  523. dxf = ezdxf.readfile(filename)
  524. geos = getdxfgeo(dxf)
  525. # Add to object
  526. if self.solid_geometry is None:
  527. self.solid_geometry = []
  528. if type(self.solid_geometry) is list:
  529. if type(geos) is list:
  530. self.solid_geometry += geos
  531. else:
  532. self.solid_geometry.append(geos)
  533. else: # It's shapely geometry
  534. self.solid_geometry = [self.solid_geometry, geos]
  535. # flatten the self.solid_geometry list for import_dxf() to import DXF as Gerber
  536. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  537. if self.solid_geometry is not None:
  538. self.solid_geometry = cascaded_union(self.solid_geometry)
  539. else:
  540. return
  541. # commented until this function is ready
  542. # geos_text = getdxftext(dxf, object_type, units=units)
  543. # if geos_text is not None:
  544. # geos_text_f = []
  545. # self.solid_geometry = [self.solid_geometry, geos_text_f]
  546. def import_image(self, filename, flip=True, units='MM', dpi=96, mode='black', mask=[128, 128, 128, 128]):
  547. """
  548. Imports shapes from an IMAGE file into the object's geometry.
  549. :param filename: Path to the IMAGE file.
  550. :type filename: str
  551. :param flip: Flip the object vertically.
  552. :type flip: bool
  553. :return: None
  554. """
  555. scale_factor = 0.264583333
  556. if units.lower() == 'mm':
  557. scale_factor = 25.4 / dpi
  558. else:
  559. scale_factor = 1 / dpi
  560. geos = []
  561. unscaled_geos = []
  562. with rasterio.open(filename) as src:
  563. # if filename.lower().rpartition('.')[-1] == 'bmp':
  564. # red = green = blue = src.read(1)
  565. # print("BMP")
  566. # elif filename.lower().rpartition('.')[-1] == 'png':
  567. # red, green, blue, alpha = src.read()
  568. # elif filename.lower().rpartition('.')[-1] == 'jpg':
  569. # red, green, blue = src.read()
  570. red = green = blue = src.read(1)
  571. try:
  572. green = src.read(2)
  573. except:
  574. pass
  575. try:
  576. blue= src.read(3)
  577. except:
  578. pass
  579. if mode == 'black':
  580. mask_setting = red <= mask[0]
  581. total = red
  582. log.debug("Image import as monochrome.")
  583. else:
  584. mask_setting = (red <= mask[1]) + (green <= mask[2]) + (blue <= mask[3])
  585. total = np.zeros(red.shape, dtype=float32)
  586. for band in red, green, blue:
  587. total += band
  588. total /= 3
  589. log.debug("Image import as colored. Thresholds are: R = %s , G = %s, B = %s" %
  590. (str(mask[1]), str(mask[2]), str(mask[3])))
  591. for geom, val in shapes(total, mask=mask_setting):
  592. unscaled_geos.append(shape(geom))
  593. for g in unscaled_geos:
  594. geos.append(scale(g, scale_factor, scale_factor, origin=(0, 0)))
  595. if flip:
  596. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0))) for g in geos]
  597. # Add to object
  598. if self.solid_geometry is None:
  599. self.solid_geometry = []
  600. if type(self.solid_geometry) is list:
  601. # self.solid_geometry.append(cascaded_union(geos))
  602. if type(geos) is list:
  603. self.solid_geometry += geos
  604. else:
  605. self.solid_geometry.append(geos)
  606. else: # It's shapely geometry
  607. self.solid_geometry = [self.solid_geometry, geos]
  608. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  609. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  610. self.solid_geometry = cascaded_union(self.solid_geometry)
  611. # self.solid_geometry = MultiPolygon(self.solid_geometry)
  612. # self.solid_geometry = self.solid_geometry.buffer(0.00000001)
  613. # self.solid_geometry = self.solid_geometry.buffer(-0.00000001)
  614. def size(self):
  615. """
  616. Returns (width, height) of rectangular
  617. bounds of geometry.
  618. """
  619. if self.solid_geometry is None:
  620. log.warning("Solid_geometry not computed yet.")
  621. return 0
  622. bounds = self.bounds()
  623. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  624. def get_empty_area(self, boundary=None):
  625. """
  626. Returns the complement of self.solid_geometry within
  627. the given boundary polygon. If not specified, it defaults to
  628. the rectangular bounding box of self.solid_geometry.
  629. """
  630. if boundary is None:
  631. boundary = self.solid_geometry.envelope
  632. return boundary.difference(self.solid_geometry)
  633. @staticmethod
  634. def clear_polygon(polygon, tooldia, steps_per_circle, overlap=0.15, connect=True,
  635. contour=True):
  636. """
  637. Creates geometry inside a polygon for a tool to cover
  638. the whole area.
  639. This algorithm shrinks the edges of the polygon and takes
  640. the resulting edges as toolpaths.
  641. :param polygon: Polygon to clear.
  642. :param tooldia: Diameter of the tool.
  643. :param overlap: Overlap of toolpasses.
  644. :param connect: Draw lines between disjoint segments to
  645. minimize tool lifts.
  646. :param contour: Paint around the edges. Inconsequential in
  647. this painting method.
  648. :return:
  649. """
  650. # log.debug("camlib.clear_polygon()")
  651. assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
  652. "Expected a Polygon or MultiPolygon, got %s" % type(polygon)
  653. ## The toolpaths
  654. # Index first and last points in paths
  655. def get_pts(o):
  656. return [o.coords[0], o.coords[-1]]
  657. geoms = FlatCAMRTreeStorage()
  658. geoms.get_points = get_pts
  659. # Can only result in a Polygon or MultiPolygon
  660. # NOTE: The resulting polygon can be "empty".
  661. current = polygon.buffer((-tooldia / 1.999999), int(int(steps_per_circle) / 4))
  662. if current.area == 0:
  663. # Otherwise, trying to to insert current.exterior == None
  664. # into the FlatCAMStorage will fail.
  665. # print("Area is None")
  666. return None
  667. # current can be a MultiPolygon
  668. try:
  669. for p in current:
  670. geoms.insert(p.exterior)
  671. for i in p.interiors:
  672. geoms.insert(i)
  673. # Not a Multipolygon. Must be a Polygon
  674. except TypeError:
  675. geoms.insert(current.exterior)
  676. for i in current.interiors:
  677. geoms.insert(i)
  678. while True:
  679. # Can only result in a Polygon or MultiPolygon
  680. current = current.buffer(-tooldia * (1 - overlap), int(int(steps_per_circle) / 4))
  681. if current.area > 0:
  682. # current can be a MultiPolygon
  683. try:
  684. for p in current:
  685. geoms.insert(p.exterior)
  686. for i in p.interiors:
  687. geoms.insert(i)
  688. # Not a Multipolygon. Must be a Polygon
  689. except TypeError:
  690. geoms.insert(current.exterior)
  691. for i in current.interiors:
  692. geoms.insert(i)
  693. else:
  694. log.debug("camlib.Geometry.clear_polygon() --> Current Area is zero")
  695. break
  696. # Optimization: Reduce lifts
  697. if connect:
  698. # log.debug("Reducing tool lifts...")
  699. geoms = Geometry.paint_connect(geoms, polygon, tooldia, int(steps_per_circle))
  700. return geoms
  701. @staticmethod
  702. def clear_polygon2(polygon_to_clear, tooldia, steps_per_circle, seedpoint=None, overlap=0.15,
  703. connect=True, contour=True):
  704. """
  705. Creates geometry inside a polygon for a tool to cover
  706. the whole area.
  707. This algorithm starts with a seed point inside the polygon
  708. and draws circles around it. Arcs inside the polygons are
  709. valid cuts. Finalizes by cutting around the inside edge of
  710. the polygon.
  711. :param polygon_to_clear: Shapely.geometry.Polygon
  712. :param tooldia: Diameter of the tool
  713. :param seedpoint: Shapely.geometry.Point or None
  714. :param overlap: Tool fraction overlap bewteen passes
  715. :param connect: Connect disjoint segment to minumize tool lifts
  716. :param contour: Cut countour inside the polygon.
  717. :return: List of toolpaths covering polygon.
  718. :rtype: FlatCAMRTreeStorage | None
  719. """
  720. # log.debug("camlib.clear_polygon2()")
  721. # Current buffer radius
  722. radius = tooldia / 2 * (1 - overlap)
  723. ## The toolpaths
  724. # Index first and last points in paths
  725. def get_pts(o):
  726. return [o.coords[0], o.coords[-1]]
  727. geoms = FlatCAMRTreeStorage()
  728. geoms.get_points = get_pts
  729. # Path margin
  730. path_margin = polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4))
  731. if path_margin.is_empty or path_margin is None:
  732. return
  733. # Estimate good seedpoint if not provided.
  734. if seedpoint is None:
  735. seedpoint = path_margin.representative_point()
  736. # Grow from seed until outside the box. The polygons will
  737. # never have an interior, so take the exterior LinearRing.
  738. while 1:
  739. path = Point(seedpoint).buffer(radius, int(steps_per_circle / 4)).exterior
  740. path = path.intersection(path_margin)
  741. # Touches polygon?
  742. if path.is_empty:
  743. break
  744. else:
  745. #geoms.append(path)
  746. #geoms.insert(path)
  747. # path can be a collection of paths.
  748. try:
  749. for p in path:
  750. geoms.insert(p)
  751. except TypeError:
  752. geoms.insert(path)
  753. radius += tooldia * (1 - overlap)
  754. # Clean inside edges (contours) of the original polygon
  755. if contour:
  756. outer_edges = [x.exterior for x in autolist(polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4)))]
  757. inner_edges = []
  758. for x in autolist(polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4))): # Over resulting polygons
  759. for y in x.interiors: # Over interiors of each polygon
  760. inner_edges.append(y)
  761. #geoms += outer_edges + inner_edges
  762. for g in outer_edges + inner_edges:
  763. geoms.insert(g)
  764. # Optimization connect touching paths
  765. # log.debug("Connecting paths...")
  766. # geoms = Geometry.path_connect(geoms)
  767. # Optimization: Reduce lifts
  768. if connect:
  769. # log.debug("Reducing tool lifts...")
  770. geoms = Geometry.paint_connect(geoms, polygon_to_clear, tooldia, steps_per_circle)
  771. return geoms
  772. @staticmethod
  773. def clear_polygon3(polygon, tooldia, steps_per_circle, overlap=0.15, connect=True,
  774. contour=True):
  775. """
  776. Creates geometry inside a polygon for a tool to cover
  777. the whole area.
  778. This algorithm draws horizontal lines inside the polygon.
  779. :param polygon: The polygon being painted.
  780. :type polygon: shapely.geometry.Polygon
  781. :param tooldia: Tool diameter.
  782. :param overlap: Tool path overlap percentage.
  783. :param connect: Connect lines to avoid tool lifts.
  784. :param contour: Paint around the edges.
  785. :return:
  786. """
  787. # log.debug("camlib.clear_polygon3()")
  788. ## The toolpaths
  789. # Index first and last points in paths
  790. def get_pts(o):
  791. return [o.coords[0], o.coords[-1]]
  792. geoms = FlatCAMRTreeStorage()
  793. geoms.get_points = get_pts
  794. lines = []
  795. # Bounding box
  796. left, bot, right, top = polygon.bounds
  797. # First line
  798. y = top - tooldia / 1.99999999
  799. while y > bot + tooldia / 1.999999999:
  800. line = LineString([(left, y), (right, y)])
  801. lines.append(line)
  802. y -= tooldia * (1 - overlap)
  803. # Last line
  804. y = bot + tooldia / 2
  805. line = LineString([(left, y), (right, y)])
  806. lines.append(line)
  807. # Combine
  808. linesgeo = unary_union(lines)
  809. # Trim to the polygon
  810. margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  811. lines_trimmed = linesgeo.intersection(margin_poly)
  812. # Add lines to storage
  813. try:
  814. for line in lines_trimmed:
  815. geoms.insert(line)
  816. except TypeError:
  817. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  818. geoms.insert(lines_trimmed)
  819. # Add margin (contour) to storage
  820. if contour:
  821. geoms.insert(margin_poly.exterior)
  822. for ints in margin_poly.interiors:
  823. geoms.insert(ints)
  824. # Optimization: Reduce lifts
  825. if connect:
  826. # log.debug("Reducing tool lifts...")
  827. geoms = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  828. return geoms
  829. def scale(self, xfactor, yfactor, point=None):
  830. """
  831. Scales all of the object's geometry by a given factor. Override
  832. this method.
  833. :param factor: Number by which to scale.
  834. :type factor: float
  835. :return: None
  836. :rtype: None
  837. """
  838. return
  839. def offset(self, vect):
  840. """
  841. Offset the geometry by the given vector. Override this method.
  842. :param vect: (x, y) vector by which to offset the object.
  843. :type vect: tuple
  844. :return: None
  845. """
  846. return
  847. @staticmethod
  848. def paint_connect(storage, boundary, tooldia, steps_per_circle, max_walk=None):
  849. """
  850. Connects paths that results in a connection segment that is
  851. within the paint area. This avoids unnecessary tool lifting.
  852. :param storage: Geometry to be optimized.
  853. :type storage: FlatCAMRTreeStorage
  854. :param boundary: Polygon defining the limits of the paintable area.
  855. :type boundary: Polygon
  856. :param tooldia: Tool diameter.
  857. :rtype tooldia: float
  858. :param max_walk: Maximum allowable distance without lifting tool.
  859. :type max_walk: float or None
  860. :return: Optimized geometry.
  861. :rtype: FlatCAMRTreeStorage
  862. """
  863. # If max_walk is not specified, the maximum allowed is
  864. # 10 times the tool diameter
  865. max_walk = max_walk or 10 * tooldia
  866. # Assuming geolist is a flat list of flat elements
  867. ## Index first and last points in paths
  868. def get_pts(o):
  869. return [o.coords[0], o.coords[-1]]
  870. # storage = FlatCAMRTreeStorage()
  871. # storage.get_points = get_pts
  872. #
  873. # for shape in geolist:
  874. # if shape is not None: # TODO: This shouldn't have happened.
  875. # # Make LlinearRings into linestrings otherwise
  876. # # When chaining the coordinates path is messed up.
  877. # storage.insert(LineString(shape))
  878. # #storage.insert(shape)
  879. ## Iterate over geometry paths getting the nearest each time.
  880. #optimized_paths = []
  881. optimized_paths = FlatCAMRTreeStorage()
  882. optimized_paths.get_points = get_pts
  883. path_count = 0
  884. current_pt = (0, 0)
  885. pt, geo = storage.nearest(current_pt)
  886. storage.remove(geo)
  887. geo = LineString(geo)
  888. current_pt = geo.coords[-1]
  889. try:
  890. while True:
  891. path_count += 1
  892. #log.debug("Path %d" % path_count)
  893. pt, candidate = storage.nearest(current_pt)
  894. storage.remove(candidate)
  895. candidate = LineString(candidate)
  896. # If last point in geometry is the nearest
  897. # then reverse coordinates.
  898. # but prefer the first one if last == first
  899. if pt != candidate.coords[0] and pt == candidate.coords[-1]:
  900. candidate.coords = list(candidate.coords)[::-1]
  901. # Straight line from current_pt to pt.
  902. # Is the toolpath inside the geometry?
  903. walk_path = LineString([current_pt, pt])
  904. walk_cut = walk_path.buffer(tooldia / 2, int(steps_per_circle / 4))
  905. if walk_cut.within(boundary) and walk_path.length < max_walk:
  906. #log.debug("Walk to path #%d is inside. Joining." % path_count)
  907. # Completely inside. Append...
  908. geo.coords = list(geo.coords) + list(candidate.coords)
  909. # try:
  910. # last = optimized_paths[-1]
  911. # last.coords = list(last.coords) + list(geo.coords)
  912. # except IndexError:
  913. # optimized_paths.append(geo)
  914. else:
  915. # Have to lift tool. End path.
  916. #log.debug("Path #%d not within boundary. Next." % path_count)
  917. #optimized_paths.append(geo)
  918. optimized_paths.insert(geo)
  919. geo = candidate
  920. current_pt = geo.coords[-1]
  921. # Next
  922. #pt, geo = storage.nearest(current_pt)
  923. except StopIteration: # Nothing left in storage.
  924. #pass
  925. optimized_paths.insert(geo)
  926. return optimized_paths
  927. @staticmethod
  928. def path_connect(storage, origin=(0, 0)):
  929. """
  930. Simplifies paths in the FlatCAMRTreeStorage storage by
  931. connecting paths that touch on their enpoints.
  932. :param storage: Storage containing the initial paths.
  933. :rtype storage: FlatCAMRTreeStorage
  934. :return: Simplified storage.
  935. :rtype: FlatCAMRTreeStorage
  936. """
  937. log.debug("path_connect()")
  938. ## Index first and last points in paths
  939. def get_pts(o):
  940. return [o.coords[0], o.coords[-1]]
  941. #
  942. # storage = FlatCAMRTreeStorage()
  943. # storage.get_points = get_pts
  944. #
  945. # for shape in pathlist:
  946. # if shape is not None: # TODO: This shouldn't have happened.
  947. # storage.insert(shape)
  948. path_count = 0
  949. pt, geo = storage.nearest(origin)
  950. storage.remove(geo)
  951. #optimized_geometry = [geo]
  952. optimized_geometry = FlatCAMRTreeStorage()
  953. optimized_geometry.get_points = get_pts
  954. #optimized_geometry.insert(geo)
  955. try:
  956. while True:
  957. path_count += 1
  958. #print "geo is", geo
  959. _, left = storage.nearest(geo.coords[0])
  960. #print "left is", left
  961. # If left touches geo, remove left from original
  962. # storage and append to geo.
  963. if type(left) == LineString:
  964. if left.coords[0] == geo.coords[0]:
  965. storage.remove(left)
  966. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  967. continue
  968. if left.coords[-1] == geo.coords[0]:
  969. storage.remove(left)
  970. geo.coords = list(left.coords) + list(geo.coords)
  971. continue
  972. if left.coords[0] == geo.coords[-1]:
  973. storage.remove(left)
  974. geo.coords = list(geo.coords) + list(left.coords)
  975. continue
  976. if left.coords[-1] == geo.coords[-1]:
  977. storage.remove(left)
  978. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  979. continue
  980. _, right = storage.nearest(geo.coords[-1])
  981. #print "right is", right
  982. # If right touches geo, remove left from original
  983. # storage and append to geo.
  984. if type(right) == LineString:
  985. if right.coords[0] == geo.coords[-1]:
  986. storage.remove(right)
  987. geo.coords = list(geo.coords) + list(right.coords)
  988. continue
  989. if right.coords[-1] == geo.coords[-1]:
  990. storage.remove(right)
  991. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  992. continue
  993. if right.coords[0] == geo.coords[0]:
  994. storage.remove(right)
  995. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  996. continue
  997. if right.coords[-1] == geo.coords[0]:
  998. storage.remove(right)
  999. geo.coords = list(left.coords) + list(geo.coords)
  1000. continue
  1001. # right is either a LinearRing or it does not connect
  1002. # to geo (nothing left to connect to geo), so we continue
  1003. # with right as geo.
  1004. storage.remove(right)
  1005. if type(right) == LinearRing:
  1006. optimized_geometry.insert(right)
  1007. else:
  1008. # Cannot exteng geo any further. Put it away.
  1009. optimized_geometry.insert(geo)
  1010. # Continue with right.
  1011. geo = right
  1012. except StopIteration: # Nothing found in storage.
  1013. optimized_geometry.insert(geo)
  1014. #print path_count
  1015. log.debug("path_count = %d" % path_count)
  1016. return optimized_geometry
  1017. def convert_units(self, units):
  1018. """
  1019. Converts the units of the object to ``units`` by scaling all
  1020. the geometry appropriately. This call ``scale()``. Don't call
  1021. it again in descendents.
  1022. :param units: "IN" or "MM"
  1023. :type units: str
  1024. :return: Scaling factor resulting from unit change.
  1025. :rtype: float
  1026. """
  1027. log.debug("Geometry.convert_units()")
  1028. if units.upper() == self.units.upper():
  1029. return 1.0
  1030. if units.upper() == "MM":
  1031. factor = 25.4
  1032. elif units.upper() == "IN":
  1033. factor = 1 / 25.4
  1034. else:
  1035. log.error("Unsupported units: %s" % str(units))
  1036. return 1.0
  1037. self.units = units
  1038. self.scale(factor)
  1039. return factor
  1040. def to_dict(self):
  1041. """
  1042. Returns a respresentation of the object as a dictionary.
  1043. Attributes to include are listed in ``self.ser_attrs``.
  1044. :return: A dictionary-encoded copy of the object.
  1045. :rtype: dict
  1046. """
  1047. d = {}
  1048. for attr in self.ser_attrs:
  1049. d[attr] = getattr(self, attr)
  1050. return d
  1051. def from_dict(self, d):
  1052. """
  1053. Sets object's attributes from a dictionary.
  1054. Attributes to include are listed in ``self.ser_attrs``.
  1055. This method will look only for only and all the
  1056. attributes in ``self.ser_attrs``. They must all
  1057. be present. Use only for deserializing saved
  1058. objects.
  1059. :param d: Dictionary of attributes to set in the object.
  1060. :type d: dict
  1061. :return: None
  1062. """
  1063. for attr in self.ser_attrs:
  1064. setattr(self, attr, d[attr])
  1065. def union(self):
  1066. """
  1067. Runs a cascaded union on the list of objects in
  1068. solid_geometry.
  1069. :return: None
  1070. """
  1071. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  1072. def export_svg(self, scale_factor=0.00):
  1073. """
  1074. Exports the Geometry Object as a SVG Element
  1075. :return: SVG Element
  1076. """
  1077. # Make sure we see a Shapely Geometry class and not a list
  1078. if str(type(self)) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  1079. flat_geo = []
  1080. if self.multigeo:
  1081. for tool in self.tools:
  1082. flat_geo += self.flatten(self.tools[tool]['solid_geometry'])
  1083. geom = cascaded_union(flat_geo)
  1084. else:
  1085. geom = cascaded_union(self.flatten())
  1086. else:
  1087. geom = cascaded_union(self.flatten())
  1088. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  1089. # If 0 or less which is invalid then default to 0.05
  1090. # This value appears to work for zooming, and getting the output svg line width
  1091. # to match that viewed on screen with FlatCam
  1092. # MS: I choose a factor of 0.01 so the scale is right for PCB UV film
  1093. if scale_factor <= 0:
  1094. scale_factor = 0.01
  1095. # Convert to a SVG
  1096. svg_elem = geom.svg(scale_factor=scale_factor)
  1097. return svg_elem
  1098. def mirror(self, axis, point):
  1099. """
  1100. Mirrors the object around a specified axis passign through
  1101. the given point.
  1102. :param axis: "X" or "Y" indicates around which axis to mirror.
  1103. :type axis: str
  1104. :param point: [x, y] point belonging to the mirror axis.
  1105. :type point: list
  1106. :return: None
  1107. """
  1108. px, py = point
  1109. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1110. def mirror_geom(obj):
  1111. if type(obj) is list:
  1112. new_obj = []
  1113. for g in obj:
  1114. new_obj.append(mirror_geom(g))
  1115. return new_obj
  1116. else:
  1117. return affinity.scale(obj, xscale, yscale, origin=(px,py))
  1118. try:
  1119. if self.multigeo is True:
  1120. for tool in self.tools:
  1121. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  1122. else:
  1123. self.solid_geometry = mirror_geom(self.solid_geometry)
  1124. self.app.inform.emit('[success]Object was mirrored ...')
  1125. except AttributeError:
  1126. self.app.inform.emit("[ERROR_NOTCL] Failed to mirror. No object selected")
  1127. def rotate(self, angle, point):
  1128. """
  1129. Rotate an object by an angle (in degrees) around the provided coordinates.
  1130. Parameters
  1131. ----------
  1132. The angle of rotation are specified in degrees (default). Positive angles are
  1133. counter-clockwise and negative are clockwise rotations.
  1134. The point of origin can be a keyword 'center' for the bounding box
  1135. center (default), 'centroid' for the geometry's centroid, a Point object
  1136. or a coordinate tuple (x0, y0).
  1137. See shapely manual for more information:
  1138. http://toblerity.org/shapely/manual.html#affine-transformations
  1139. """
  1140. px, py = point
  1141. def rotate_geom(obj):
  1142. if type(obj) is list:
  1143. new_obj = []
  1144. for g in obj:
  1145. new_obj.append(rotate_geom(g))
  1146. return new_obj
  1147. else:
  1148. return affinity.rotate(obj, angle, origin=(px, py))
  1149. try:
  1150. if self.multigeo is True:
  1151. for tool in self.tools:
  1152. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  1153. else:
  1154. self.solid_geometry = rotate_geom(self.solid_geometry)
  1155. self.app.inform.emit('[success]Object was rotated ...')
  1156. except AttributeError:
  1157. self.app.inform.emit("[ERROR_NOTCL] Failed to rotate. No object selected")
  1158. def skew(self, angle_x, angle_y, point):
  1159. """
  1160. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1161. Parameters
  1162. ----------
  1163. angle_x, angle_y : float, float
  1164. The shear angle(s) for the x and y axes respectively. These can be
  1165. specified in either degrees (default) or radians by setting
  1166. use_radians=True.
  1167. point: tuple of coordinates (x,y)
  1168. See shapely manual for more information:
  1169. http://toblerity.org/shapely/manual.html#affine-transformations
  1170. """
  1171. px, py = point
  1172. def skew_geom(obj):
  1173. if type(obj) is list:
  1174. new_obj = []
  1175. for g in obj:
  1176. new_obj.append(skew_geom(g))
  1177. return new_obj
  1178. else:
  1179. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1180. try:
  1181. if self.multigeo is True:
  1182. for tool in self.tools:
  1183. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1184. else:
  1185. self.solid_geometry = skew_geom(self.solid_geometry)
  1186. self.app.inform.emit('[success]Object was skewed ...')
  1187. except AttributeError:
  1188. self.app.inform.emit("[ERROR_NOTCL] Failed to skew. No object selected")
  1189. # if type(self.solid_geometry) == list:
  1190. # self.solid_geometry = [affinity.skew(g, angle_x, angle_y, origin=(px, py))
  1191. # for g in self.solid_geometry]
  1192. # else:
  1193. # self.solid_geometry = affinity.skew(self.solid_geometry, angle_x, angle_y,
  1194. # origin=(px, py))
  1195. class ApertureMacro:
  1196. """
  1197. Syntax of aperture macros.
  1198. <AM command>: AM<Aperture macro name>*<Macro content>
  1199. <Macro content>: {{<Variable definition>*}{<Primitive>*}}
  1200. <Variable definition>: $K=<Arithmetic expression>
  1201. <Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
  1202. <Modifier>: $M|< Arithmetic expression>
  1203. <Comment>: 0 <Text>
  1204. """
  1205. ## Regular expressions
  1206. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  1207. am2_re = re.compile(r'(.*)%$')
  1208. amcomm_re = re.compile(r'^0(.*)')
  1209. amprim_re = re.compile(r'^[1-9].*')
  1210. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  1211. def __init__(self, name=None):
  1212. self.name = name
  1213. self.raw = ""
  1214. ## These below are recomputed for every aperture
  1215. ## definition, in other words, are temporary variables.
  1216. self.primitives = []
  1217. self.locvars = {}
  1218. self.geometry = None
  1219. def to_dict(self):
  1220. """
  1221. Returns the object in a serializable form. Only the name and
  1222. raw are required.
  1223. :return: Dictionary representing the object. JSON ready.
  1224. :rtype: dict
  1225. """
  1226. return {
  1227. 'name': self.name,
  1228. 'raw': self.raw
  1229. }
  1230. def from_dict(self, d):
  1231. """
  1232. Populates the object from a serial representation created
  1233. with ``self.to_dict()``.
  1234. :param d: Serial representation of an ApertureMacro object.
  1235. :return: None
  1236. """
  1237. for attr in ['name', 'raw']:
  1238. setattr(self, attr, d[attr])
  1239. def parse_content(self):
  1240. """
  1241. Creates numerical lists for all primitives in the aperture
  1242. macro (in ``self.raw``) by replacing all variables by their
  1243. values iteratively and evaluating expressions. Results
  1244. are stored in ``self.primitives``.
  1245. :return: None
  1246. """
  1247. # Cleanup
  1248. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  1249. self.primitives = []
  1250. # Separate parts
  1251. parts = self.raw.split('*')
  1252. #### Every part in the macro ####
  1253. for part in parts:
  1254. ### Comments. Ignored.
  1255. match = ApertureMacro.amcomm_re.search(part)
  1256. if match:
  1257. continue
  1258. ### Variables
  1259. # These are variables defined locally inside the macro. They can be
  1260. # numerical constant or defind in terms of previously define
  1261. # variables, which can be defined locally or in an aperture
  1262. # definition. All replacements ocurr here.
  1263. match = ApertureMacro.amvar_re.search(part)
  1264. if match:
  1265. var = match.group(1)
  1266. val = match.group(2)
  1267. # Replace variables in value
  1268. for v in self.locvars:
  1269. # replaced the following line with the next to fix Mentor custom apertures not parsed OK
  1270. # val = re.sub((r'\$'+str(v)+r'(?![0-9a-zA-Z])'), str(self.locvars[v]), val)
  1271. val = val.replace('$' + str(v), str(self.locvars[v]))
  1272. # Make all others 0
  1273. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  1274. # Change x with *
  1275. val = re.sub(r'[xX]', "*", val)
  1276. # Eval() and store.
  1277. self.locvars[var] = eval(val)
  1278. continue
  1279. ### Primitives
  1280. # Each is an array. The first identifies the primitive, while the
  1281. # rest depend on the primitive. All are strings representing a
  1282. # number and may contain variable definition. The values of these
  1283. # variables are defined in an aperture definition.
  1284. match = ApertureMacro.amprim_re.search(part)
  1285. if match:
  1286. ## Replace all variables
  1287. for v in self.locvars:
  1288. # replaced the following line with the next to fix Mentor custom apertures not parsed OK
  1289. # part = re.sub(r'\$' + str(v) + r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  1290. part = part.replace('$' + str(v), str(self.locvars[v]))
  1291. # Make all others 0
  1292. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  1293. # Change x with *
  1294. part = re.sub(r'[xX]', "*", part)
  1295. ## Store
  1296. elements = part.split(",")
  1297. self.primitives.append([eval(x) for x in elements])
  1298. continue
  1299. log.warning("Unknown syntax of aperture macro part: %s" % str(part))
  1300. def append(self, data):
  1301. """
  1302. Appends a string to the raw macro.
  1303. :param data: Part of the macro.
  1304. :type data: str
  1305. :return: None
  1306. """
  1307. self.raw += data
  1308. @staticmethod
  1309. def default2zero(n, mods):
  1310. """
  1311. Pads the ``mods`` list with zeros resulting in an
  1312. list of length n.
  1313. :param n: Length of the resulting list.
  1314. :type n: int
  1315. :param mods: List to be padded.
  1316. :type mods: list
  1317. :return: Zero-padded list.
  1318. :rtype: list
  1319. """
  1320. x = [0.0] * n
  1321. na = len(mods)
  1322. x[0:na] = mods
  1323. return x
  1324. @staticmethod
  1325. def make_circle(mods):
  1326. """
  1327. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  1328. :return:
  1329. """
  1330. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  1331. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  1332. @staticmethod
  1333. def make_vectorline(mods):
  1334. """
  1335. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  1336. rotation angle around origin in degrees)
  1337. :return:
  1338. """
  1339. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  1340. line = LineString([(xs, ys), (xe, ye)])
  1341. box = line.buffer(width/2, cap_style=2)
  1342. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  1343. return {"pol": int(pol), "geometry": box_rotated}
  1344. @staticmethod
  1345. def make_centerline(mods):
  1346. """
  1347. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  1348. rotation angle around origin in degrees)
  1349. :return:
  1350. """
  1351. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  1352. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  1353. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  1354. return {"pol": int(pol), "geometry": box_rotated}
  1355. @staticmethod
  1356. def make_lowerleftline(mods):
  1357. """
  1358. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  1359. rotation angle around origin in degrees)
  1360. :return:
  1361. """
  1362. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  1363. box = shply_box(x, y, x+width, y+height)
  1364. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  1365. return {"pol": int(pol), "geometry": box_rotated}
  1366. @staticmethod
  1367. def make_outline(mods):
  1368. """
  1369. :param mods:
  1370. :return:
  1371. """
  1372. pol = mods[0]
  1373. n = mods[1]
  1374. points = [(0, 0)]*(n+1)
  1375. for i in range(n+1):
  1376. points[i] = mods[2*i + 2:2*i + 4]
  1377. angle = mods[2*n + 4]
  1378. poly = Polygon(points)
  1379. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  1380. return {"pol": int(pol), "geometry": poly_rotated}
  1381. @staticmethod
  1382. def make_polygon(mods):
  1383. """
  1384. Note: Specs indicate that rotation is only allowed if the center
  1385. (x, y) == (0, 0). I will tolerate breaking this rule.
  1386. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  1387. diameter of circumscribed circle >=0, rotation angle around origin)
  1388. :return:
  1389. """
  1390. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  1391. points = [(0, 0)]*nverts
  1392. for i in range(nverts):
  1393. points[i] = (x + 0.5 * dia * cos(2*pi * i/nverts),
  1394. y + 0.5 * dia * sin(2*pi * i/nverts))
  1395. poly = Polygon(points)
  1396. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  1397. return {"pol": int(pol), "geometry": poly_rotated}
  1398. @staticmethod
  1399. def make_moire(mods):
  1400. """
  1401. Note: Specs indicate that rotation is only allowed if the center
  1402. (x, y) == (0, 0). I will tolerate breaking this rule.
  1403. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  1404. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  1405. angle around origin in degrees)
  1406. :return:
  1407. """
  1408. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  1409. r = dia/2 - thickness/2
  1410. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  1411. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  1412. i = 1 # Number of rings created so far
  1413. ## If the ring does not have an interior it means that it is
  1414. ## a disk. Then stop.
  1415. while len(ring.interiors) > 0 and i < nrings:
  1416. r -= thickness + gap
  1417. if r <= 0:
  1418. break
  1419. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  1420. result = cascaded_union([result, ring])
  1421. i += 1
  1422. ## Crosshair
  1423. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  1424. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  1425. result = cascaded_union([result, hor, ver])
  1426. return {"pol": 1, "geometry": result}
  1427. @staticmethod
  1428. def make_thermal(mods):
  1429. """
  1430. Note: Specs indicate that rotation is only allowed if the center
  1431. (x, y) == (0, 0). I will tolerate breaking this rule.
  1432. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  1433. gap-thickness, rotation angle around origin]
  1434. :return:
  1435. """
  1436. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  1437. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  1438. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  1439. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  1440. thermal = ring.difference(hline.union(vline))
  1441. return {"pol": 1, "geometry": thermal}
  1442. def make_geometry(self, modifiers):
  1443. """
  1444. Runs the macro for the given modifiers and generates
  1445. the corresponding geometry.
  1446. :param modifiers: Modifiers (parameters) for this macro
  1447. :type modifiers: list
  1448. :return: Shapely geometry
  1449. :rtype: shapely.geometry.polygon
  1450. """
  1451. ## Primitive makers
  1452. makers = {
  1453. "1": ApertureMacro.make_circle,
  1454. "2": ApertureMacro.make_vectorline,
  1455. "20": ApertureMacro.make_vectorline,
  1456. "21": ApertureMacro.make_centerline,
  1457. "22": ApertureMacro.make_lowerleftline,
  1458. "4": ApertureMacro.make_outline,
  1459. "5": ApertureMacro.make_polygon,
  1460. "6": ApertureMacro.make_moire,
  1461. "7": ApertureMacro.make_thermal
  1462. }
  1463. ## Store modifiers as local variables
  1464. modifiers = modifiers or []
  1465. modifiers = [float(m) for m in modifiers]
  1466. self.locvars = {}
  1467. for i in range(0, len(modifiers)):
  1468. self.locvars[str(i + 1)] = modifiers[i]
  1469. ## Parse
  1470. self.primitives = [] # Cleanup
  1471. self.geometry = Polygon()
  1472. self.parse_content()
  1473. ## Make the geometry
  1474. for primitive in self.primitives:
  1475. # Make the primitive
  1476. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  1477. # Add it (according to polarity)
  1478. # if self.geometry is None and prim_geo['pol'] == 1:
  1479. # self.geometry = prim_geo['geometry']
  1480. # continue
  1481. if prim_geo['pol'] == 1:
  1482. self.geometry = self.geometry.union(prim_geo['geometry'])
  1483. continue
  1484. if prim_geo['pol'] == 0:
  1485. self.geometry = self.geometry.difference(prim_geo['geometry'])
  1486. continue
  1487. return self.geometry
  1488. class Gerber (Geometry):
  1489. """
  1490. **ATTRIBUTES**
  1491. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  1492. The values are dictionaries key/value pairs which describe the aperture. The
  1493. type key is always present and the rest depend on the key:
  1494. +-----------+-----------------------------------+
  1495. | Key | Value |
  1496. +===========+===================================+
  1497. | type | (str) "C", "R", "O", "P", or "AP" |
  1498. +-----------+-----------------------------------+
  1499. | others | Depend on ``type`` |
  1500. +-----------+-----------------------------------+
  1501. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  1502. that can be instanciated with different parameters in an aperture
  1503. definition. See ``apertures`` above. The key is the name of the macro,
  1504. and the macro itself, the value, is a ``Aperture_Macro`` object.
  1505. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  1506. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  1507. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  1508. *buffering* (or thickening) the ``paths`` with the aperture. These are
  1509. generated from ``paths`` in ``buffer_paths()``.
  1510. **USAGE**::
  1511. g = Gerber()
  1512. g.parse_file(filename)
  1513. g.create_geometry()
  1514. do_something(s.solid_geometry)
  1515. """
  1516. defaults = {
  1517. "steps_per_circle": 56,
  1518. "use_buffer_for_union": True
  1519. }
  1520. def __init__(self, steps_per_circle=None):
  1521. """
  1522. The constructor takes no parameters. Use ``gerber.parse_files()``
  1523. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  1524. :return: Gerber object
  1525. :rtype: Gerber
  1526. """
  1527. # How to discretize a circle.
  1528. if steps_per_circle is None:
  1529. steps_per_circle = int(Gerber.defaults['steps_per_circle'])
  1530. self.steps_per_circle = int(steps_per_circle)
  1531. # Initialize parent
  1532. Geometry.__init__(self, geo_steps_per_circle=int(steps_per_circle))
  1533. self.solid_geometry = Polygon()
  1534. # Number format
  1535. self.int_digits = 3
  1536. """Number of integer digits in Gerber numbers. Used during parsing."""
  1537. self.frac_digits = 4
  1538. """Number of fraction digits in Gerber numbers. Used during parsing."""
  1539. self.gerber_zeros = 'L'
  1540. """Zeros in Gerber numbers. If 'L' then remove leading zeros, if 'T' remove trailing zeros. Used during parsing.
  1541. """
  1542. ## Gerber elements ##
  1543. # Apertures {'id':{'type':chr,
  1544. # ['size':float], ['width':float],
  1545. # ['height':float]}, ...}
  1546. self.apertures = {}
  1547. # Aperture Macros
  1548. self.aperture_macros = {}
  1549. # Attributes to be included in serialization
  1550. # Always append to it because it carries contents
  1551. # from Geometry.
  1552. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures',
  1553. 'aperture_macros', 'solid_geometry']
  1554. #### Parser patterns ####
  1555. # FS - Format Specification
  1556. # The format of X and Y must be the same!
  1557. # L-omit leading zeros, T-omit trailing zeros
  1558. # A-absolute notation, I-incremental notation
  1559. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  1560. self.fmt_re_alt = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*MO(IN|MM)\*%$')
  1561. self.fmt_re_orcad = re.compile(r'(G\d+)*\**%FS([LT])([AI]).*X(\d)(\d)Y\d\d\*%$')
  1562. # Mode (IN/MM)
  1563. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  1564. # Comment G04|G4
  1565. self.comm_re = re.compile(r'^G0?4(.*)$')
  1566. # AD - Aperture definition
  1567. # Aperture Macro names: Name = [a-zA-Z_.$]{[a-zA-Z_.0-9]+}
  1568. # NOTE: Adding "-" to support output from Upverter.
  1569. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z_$\.][a-zA-Z0-9_$\.\-]*)(?:,(.*))?\*%$')
  1570. # AM - Aperture Macro
  1571. # Beginning of macro (Ends with *%):
  1572. #self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  1573. # Tool change
  1574. # May begin with G54 but that is deprecated
  1575. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  1576. # G01... - Linear interpolation plus flashes with coordinates
  1577. # Operation code (D0x) missing is deprecated... oh well I will support it.
  1578. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  1579. # Operation code alone, usually just D03 (Flash)
  1580. self.opcode_re = re.compile(r'^D0?([123])\*$')
  1581. # G02/3... - Circular interpolation with coordinates
  1582. # 2-clockwise, 3-counterclockwise
  1583. # Operation code (D0x) missing is deprecated... oh well I will support it.
  1584. # Optional start with G02 or G03, optional end with D01 or D02 with
  1585. # optional coordinates but at least one in any order.
  1586. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))' +
  1587. '?(?=.*I([\+-]?\d+))?(?=.*J([\+-]?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  1588. # G01/2/3 Occurring without coordinates
  1589. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  1590. # Single G74 or multi G75 quadrant for circular interpolation
  1591. self.quad_re = re.compile(r'^G7([45]).*\*$')
  1592. # Region mode on
  1593. # In region mode, D01 starts a region
  1594. # and D02 ends it. A new region can be started again
  1595. # with D01. All contours must be closed before
  1596. # D02 or G37.
  1597. self.regionon_re = re.compile(r'^G36\*$')
  1598. # Region mode off
  1599. # Will end a region and come off region mode.
  1600. # All contours must be closed before D02 or G37.
  1601. self.regionoff_re = re.compile(r'^G37\*$')
  1602. # End of file
  1603. self.eof_re = re.compile(r'^M02\*')
  1604. # IP - Image polarity
  1605. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  1606. # LP - Level polarity
  1607. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  1608. # Units (OBSOLETE)
  1609. self.units_re = re.compile(r'^G7([01])\*$')
  1610. # Absolute/Relative G90/1 (OBSOLETE)
  1611. self.absrel_re = re.compile(r'^G9([01])\*$')
  1612. # Aperture macros
  1613. self.am1_re = re.compile(r'^%AM([^\*]+)\*([^%]+)?(%)?$')
  1614. self.am2_re = re.compile(r'(.*)%$')
  1615. self.use_buffer_for_union = self.defaults["use_buffer_for_union"]
  1616. def aperture_parse(self, apertureId, apertureType, apParameters):
  1617. """
  1618. Parse gerber aperture definition into dictionary of apertures.
  1619. The following kinds and their attributes are supported:
  1620. * *Circular (C)*: size (float)
  1621. * *Rectangle (R)*: width (float), height (float)
  1622. * *Obround (O)*: width (float), height (float).
  1623. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  1624. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  1625. :param apertureId: Id of the aperture being defined.
  1626. :param apertureType: Type of the aperture.
  1627. :param apParameters: Parameters of the aperture.
  1628. :type apertureId: str
  1629. :type apertureType: str
  1630. :type apParameters: str
  1631. :return: Identifier of the aperture.
  1632. :rtype: str
  1633. """
  1634. # Found some Gerber with a leading zero in the aperture id and the
  1635. # referenced it without the zero, so this is a hack to handle that.
  1636. apid = str(int(apertureId))
  1637. try: # Could be empty for aperture macros
  1638. paramList = apParameters.split('X')
  1639. except:
  1640. paramList = None
  1641. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  1642. self.apertures[apid] = {"type": "C",
  1643. "size": float(paramList[0])}
  1644. return apid
  1645. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  1646. self.apertures[apid] = {"type": "R",
  1647. "width": float(paramList[0]),
  1648. "height": float(paramList[1]),
  1649. "size": sqrt(float(paramList[0])**2 + float(paramList[1])**2)} # Hack
  1650. return apid
  1651. if apertureType == "O": # Obround
  1652. self.apertures[apid] = {"type": "O",
  1653. "width": float(paramList[0]),
  1654. "height": float(paramList[1]),
  1655. "size": sqrt(float(paramList[0])**2 + float(paramList[1])**2)} # Hack
  1656. return apid
  1657. if apertureType == "P": # Polygon (regular)
  1658. self.apertures[apid] = {"type": "P",
  1659. "diam": float(paramList[0]),
  1660. "nVertices": int(paramList[1]),
  1661. "size": float(paramList[0])} # Hack
  1662. if len(paramList) >= 3:
  1663. self.apertures[apid]["rotation"] = float(paramList[2])
  1664. return apid
  1665. if apertureType in self.aperture_macros:
  1666. self.apertures[apid] = {"type": "AM",
  1667. "macro": self.aperture_macros[apertureType],
  1668. "modifiers": paramList}
  1669. return apid
  1670. log.warning("Aperture not implemented: %s" % str(apertureType))
  1671. return None
  1672. def parse_file(self, filename, follow=False):
  1673. """
  1674. Calls Gerber.parse_lines() with generator of lines
  1675. read from the given file. Will split the lines if multiple
  1676. statements are found in a single original line.
  1677. The following line is split into two::
  1678. G54D11*G36*
  1679. First is ``G54D11*`` and seconds is ``G36*``.
  1680. :param filename: Gerber file to parse.
  1681. :type filename: str
  1682. :param follow: If true, will not create polygons, just lines
  1683. following the gerber path.
  1684. :type follow: bool
  1685. :return: None
  1686. """
  1687. with open(filename, 'r') as gfile:
  1688. def line_generator():
  1689. for line in gfile:
  1690. line = line.strip(' \r\n')
  1691. while len(line) > 0:
  1692. # If ends with '%' leave as is.
  1693. if line[-1] == '%':
  1694. yield line
  1695. break
  1696. # Split after '*' if any.
  1697. starpos = line.find('*')
  1698. if starpos > -1:
  1699. cleanline = line[:starpos + 1]
  1700. yield cleanline
  1701. line = line[starpos + 1:]
  1702. # Otherwise leave as is.
  1703. else:
  1704. # yield cleanline
  1705. yield line
  1706. break
  1707. self.parse_lines(line_generator(), follow=follow)
  1708. #@profile
  1709. def parse_lines(self, glines, follow=False):
  1710. """
  1711. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  1712. ``self.flashes``, ``self.regions`` and ``self.units``.
  1713. :param glines: Gerber code as list of strings, each element being
  1714. one line of the source file.
  1715. :type glines: list
  1716. :param follow: If true, will not create polygons, just lines
  1717. following the gerber path.
  1718. :type follow: bool
  1719. :return: None
  1720. :rtype: None
  1721. """
  1722. # Coordinates of the current path, each is [x, y]
  1723. path = []
  1724. # this is for temporary storage of geometry until it is added to poly_buffer
  1725. geo = None
  1726. # Polygons are stored here until there is a change in polarity.
  1727. # Only then they are combined via cascaded_union and added or
  1728. # subtracted from solid_geometry. This is ~100 times faster than
  1729. # applying a union for every new polygon.
  1730. poly_buffer = []
  1731. last_path_aperture = None
  1732. current_aperture = None
  1733. # 1,2 or 3 from "G01", "G02" or "G03"
  1734. current_interpolation_mode = None
  1735. # 1 or 2 from "D01" or "D02"
  1736. # Note this is to support deprecated Gerber not putting
  1737. # an operation code at the end of every coordinate line.
  1738. current_operation_code = None
  1739. # Current coordinates
  1740. current_x = None
  1741. current_y = None
  1742. previous_x = None
  1743. previous_y = None
  1744. current_d = None
  1745. # Absolute or Relative/Incremental coordinates
  1746. # Not implemented
  1747. absolute = True
  1748. # How to interpret circular interpolation: SINGLE or MULTI
  1749. quadrant_mode = None
  1750. # Indicates we are parsing an aperture macro
  1751. current_macro = None
  1752. # Indicates the current polarity: D-Dark, C-Clear
  1753. current_polarity = 'D'
  1754. # If a region is being defined
  1755. making_region = False
  1756. #### Parsing starts here ####
  1757. line_num = 0
  1758. gline = ""
  1759. try:
  1760. for gline in glines:
  1761. line_num += 1
  1762. ### Cleanup
  1763. gline = gline.strip(' \r\n')
  1764. # log.debug("Line=%3s %s" % (line_num, gline))
  1765. #### Ignored lines
  1766. ## Comments
  1767. match = self.comm_re.search(gline)
  1768. if match:
  1769. continue
  1770. ### Polarity change
  1771. # Example: %LPD*% or %LPC*%
  1772. # If polarity changes, creates geometry from current
  1773. # buffer, then adds or subtracts accordingly.
  1774. match = self.lpol_re.search(gline)
  1775. if match:
  1776. if len(path) > 1 and current_polarity != match.group(1):
  1777. # --- Buffered ----
  1778. width = self.apertures[last_path_aperture]["size"]
  1779. if follow:
  1780. geo = LineString(path)
  1781. else:
  1782. geo = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  1783. if not geo.is_empty:
  1784. poly_buffer.append(geo)
  1785. path = [path[-1]]
  1786. # --- Apply buffer ---
  1787. # If added for testing of bug #83
  1788. # TODO: Remove when bug fixed
  1789. if len(poly_buffer) > 0:
  1790. if current_polarity == 'D':
  1791. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1792. else:
  1793. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1794. poly_buffer = []
  1795. current_polarity = match.group(1)
  1796. continue
  1797. ### Number format
  1798. # Example: %FSLAX24Y24*%
  1799. # TODO: This is ignoring most of the format. Implement the rest.
  1800. match = self.fmt_re.search(gline)
  1801. if match:
  1802. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(2)]
  1803. self.gerber_zeros = match.group(1)
  1804. self.int_digits = int(match.group(3))
  1805. self.frac_digits = int(match.group(4))
  1806. log.debug("Gerber format found. (%s) " % str(gline))
  1807. log.debug(
  1808. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros)" %
  1809. self.gerber_zeros)
  1810. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  1811. continue
  1812. ### Mode (IN/MM)
  1813. # Example: %MOIN*%
  1814. match = self.mode_re.search(gline)
  1815. if match:
  1816. gerber_units = match.group(1)
  1817. log.debug("Gerber units found = %s" % gerber_units)
  1818. # Changed for issue #80
  1819. self.convert_units(match.group(1))
  1820. continue
  1821. ### Combined Number format and Mode --- Allegro does this
  1822. match = self.fmt_re_alt.search(gline)
  1823. if match:
  1824. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(2)]
  1825. self.gerber_zeros = match.group(1)
  1826. self.int_digits = int(match.group(3))
  1827. self.frac_digits = int(match.group(4))
  1828. log.debug("Gerber format found. (%s) " % str(gline))
  1829. log.debug(
  1830. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros)" %
  1831. self.gerber_zeros)
  1832. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  1833. gerber_units = match.group(1)
  1834. log.debug("Gerber units found = %s" % gerber_units)
  1835. # Changed for issue #80
  1836. self.convert_units(match.group(5))
  1837. continue
  1838. ### Search for OrCAD way for having Number format
  1839. match = self.fmt_re_orcad.search(gline)
  1840. if match:
  1841. if match.group(1) is not None:
  1842. if match.group(1) == 'G74':
  1843. quadrant_mode = 'SINGLE'
  1844. elif match.group(1) == 'G75':
  1845. quadrant_mode = 'MULTI'
  1846. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(3)]
  1847. self.gerber_zeros = match.group(2)
  1848. self.int_digits = int(match.group(4))
  1849. self.frac_digits = int(match.group(5))
  1850. log.debug("Gerber format found. (%s) " % str(gline))
  1851. log.debug(
  1852. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros)" %
  1853. self.gerber_zeros)
  1854. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  1855. gerber_units = match.group(1)
  1856. log.debug("Gerber units found = %s" % gerber_units)
  1857. # Changed for issue #80
  1858. self.convert_units(match.group(5))
  1859. continue
  1860. ### Units (G70/1) OBSOLETE
  1861. match = self.units_re.search(gline)
  1862. if match:
  1863. obs_gerber_units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  1864. log.warning("Gerber obsolete units found = %s" % obs_gerber_units)
  1865. # Changed for issue #80
  1866. self.convert_units({'0': 'IN', '1': 'MM'}[match.group(1)])
  1867. continue
  1868. ### Absolute/relative coordinates G90/1 OBSOLETE
  1869. match = self.absrel_re.search(gline)
  1870. if match:
  1871. absolute = {'0': "Absolute", '1': "Relative"}[match.group(1)]
  1872. log.warning("Gerber obsolete coordinates type found = %s (Absolute or Relative) " % absolute)
  1873. continue
  1874. ### Aperture Macros
  1875. # Having this at the beginning will slow things down
  1876. # but macros can have complicated statements than could
  1877. # be caught by other patterns.
  1878. if current_macro is None: # No macro started yet
  1879. match = self.am1_re.search(gline)
  1880. # Start macro if match, else not an AM, carry on.
  1881. if match:
  1882. log.debug("Starting macro. Line %d: %s" % (line_num, gline))
  1883. current_macro = match.group(1)
  1884. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  1885. if match.group(2): # Append
  1886. self.aperture_macros[current_macro].append(match.group(2))
  1887. if match.group(3): # Finish macro
  1888. #self.aperture_macros[current_macro].parse_content()
  1889. current_macro = None
  1890. log.debug("Macro complete in 1 line.")
  1891. continue
  1892. else: # Continue macro
  1893. log.debug("Continuing macro. Line %d." % line_num)
  1894. match = self.am2_re.search(gline)
  1895. if match: # Finish macro
  1896. log.debug("End of macro. Line %d." % line_num)
  1897. self.aperture_macros[current_macro].append(match.group(1))
  1898. #self.aperture_macros[current_macro].parse_content()
  1899. current_macro = None
  1900. else: # Append
  1901. self.aperture_macros[current_macro].append(gline)
  1902. continue
  1903. ### Aperture definitions %ADD...
  1904. match = self.ad_re.search(gline)
  1905. if match:
  1906. log.info("Found aperture definition. Line %d: %s" % (line_num, gline))
  1907. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  1908. continue
  1909. ### Operation code alone
  1910. # Operation code alone, usually just D03 (Flash)
  1911. # self.opcode_re = re.compile(r'^D0?([123])\*$')
  1912. match = self.opcode_re.search(gline)
  1913. if match:
  1914. current_operation_code = int(match.group(1))
  1915. current_d = current_operation_code
  1916. if current_operation_code == 3:
  1917. ## --- Buffered ---
  1918. try:
  1919. log.debug("Bare op-code %d." % current_operation_code)
  1920. # flash = Gerber.create_flash_geometry(Point(path[-1]),
  1921. # self.apertures[current_aperture])
  1922. if follow:
  1923. continue
  1924. flash = Gerber.create_flash_geometry(
  1925. Point(current_x, current_y), self.apertures[current_aperture],
  1926. int(self.steps_per_circle))
  1927. if not flash.is_empty:
  1928. poly_buffer.append(flash)
  1929. except IndexError:
  1930. log.warning("Line %d: %s -> Nothing there to flash!" % (line_num, gline))
  1931. continue
  1932. ### Tool/aperture change
  1933. # Example: D12*
  1934. match = self.tool_re.search(gline)
  1935. if match:
  1936. current_aperture = match.group(1)
  1937. log.debug("Line %d: Aperture change to (%s)" % (line_num, match.group(1)))
  1938. # If the aperture value is zero then make it something quite small but with a non-zero value
  1939. # so it can be processed by FlatCAM.
  1940. # But first test to see if the aperture type is "aperture macro". In that case
  1941. # we should not test for "size" key as it does not exist in this case.
  1942. if self.apertures[current_aperture]["type"] is not "AM":
  1943. if self.apertures[current_aperture]["size"] == 0:
  1944. self.apertures[current_aperture]["size"] = 1e-12
  1945. log.debug(self.apertures[current_aperture])
  1946. # Take care of the current path with the previous tool
  1947. if len(path) > 1:
  1948. if self.apertures[last_path_aperture]["type"] == 'R':
  1949. # do nothing because 'R' type moving aperture is none at once
  1950. pass
  1951. else:
  1952. # --- Buffered ----
  1953. width = self.apertures[last_path_aperture]["size"]
  1954. if follow:
  1955. geo = LineString(path)
  1956. else:
  1957. geo = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  1958. if not geo.is_empty:
  1959. poly_buffer.append(geo)
  1960. path = [path[-1]]
  1961. continue
  1962. ### G36* - Begin region
  1963. if self.regionon_re.search(gline):
  1964. if len(path) > 1:
  1965. # Take care of what is left in the path
  1966. ## --- Buffered ---
  1967. width = self.apertures[last_path_aperture]["size"]
  1968. if follow:
  1969. geo = LineString(path)
  1970. else:
  1971. geo = LineString(path).buffer(width/1.999, int(self.steps_per_circle / 4))
  1972. if not geo.is_empty:
  1973. poly_buffer.append(geo)
  1974. path = [path[-1]]
  1975. making_region = True
  1976. continue
  1977. ### G37* - End region
  1978. if self.regionoff_re.search(gline):
  1979. making_region = False
  1980. # if D02 happened before G37 we now have a path with 1 element only so we have to add the current
  1981. # geo to the poly_buffer otherwise we loose it
  1982. if current_operation_code == 2:
  1983. if geo:
  1984. if not geo.is_empty:
  1985. poly_buffer.append(geo)
  1986. continue
  1987. # Only one path defines region?
  1988. # This can happen if D02 happened before G37 and
  1989. # is not and error.
  1990. if len(path) < 3:
  1991. # print "ERROR: Path contains less than 3 points:"
  1992. # print path
  1993. # print "Line (%d): " % line_num, gline
  1994. # path = []
  1995. #path = [[current_x, current_y]]
  1996. continue
  1997. # For regions we may ignore an aperture that is None
  1998. # self.regions.append({"polygon": Polygon(path),
  1999. # "aperture": last_path_aperture})
  2000. # --- Buffered ---
  2001. if follow:
  2002. region = Polygon()
  2003. else:
  2004. region = Polygon(path)
  2005. if not region.is_valid:
  2006. if not follow:
  2007. region = region.buffer(0, int(self.steps_per_circle / 4))
  2008. if not region.is_empty:
  2009. poly_buffer.append(region)
  2010. path = [[current_x, current_y]] # Start new path
  2011. continue
  2012. ### G01/2/3* - Interpolation mode change
  2013. # Can occur along with coordinates and operation code but
  2014. # sometimes by itself (handled here).
  2015. # Example: G01*
  2016. match = self.interp_re.search(gline)
  2017. if match:
  2018. current_interpolation_mode = int(match.group(1))
  2019. continue
  2020. ### G01 - Linear interpolation plus flashes
  2021. # Operation code (D0x) missing is deprecated... oh well I will support it.
  2022. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  2023. match = self.lin_re.search(gline)
  2024. if match:
  2025. # Dxx alone?
  2026. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  2027. # try:
  2028. # current_operation_code = int(match.group(4))
  2029. # except:
  2030. # pass # A line with just * will match too.
  2031. # continue
  2032. # NOTE: Letting it continue allows it to react to the
  2033. # operation code.
  2034. # Parse coordinates
  2035. if match.group(2) is not None:
  2036. linear_x = parse_gerber_number(match.group(2),
  2037. self.int_digits, self.frac_digits, self.gerber_zeros)
  2038. current_x = linear_x
  2039. else:
  2040. linear_x = current_x
  2041. if match.group(3) is not None:
  2042. linear_y = parse_gerber_number(match.group(3),
  2043. self.int_digits, self.frac_digits, self.gerber_zeros)
  2044. current_y = linear_y
  2045. else:
  2046. linear_y = current_y
  2047. # Parse operation code
  2048. if match.group(4) is not None:
  2049. current_operation_code = int(match.group(4))
  2050. # Pen down: add segment
  2051. if current_operation_code == 1:
  2052. # if linear_x or linear_y are None, ignore those
  2053. if linear_x is not None and linear_y is not None:
  2054. # only add the point if it's a new one otherwise skip it (harder to process)
  2055. if path[-1] != [linear_x, linear_y]:
  2056. path.append([linear_x, linear_y])
  2057. if follow == 0 and making_region is False:
  2058. # if the aperture is rectangle then add a rectangular shape having as parameters the
  2059. # coordinates of the start and end point and also the width and height
  2060. # of the 'R' aperture
  2061. try:
  2062. if self.apertures[current_aperture]["type"] == 'R':
  2063. width = self.apertures[current_aperture]['width']
  2064. height = self.apertures[current_aperture]['height']
  2065. minx = min(path[0][0], path[1][0]) - width / 2
  2066. maxx = max(path[0][0], path[1][0]) + width / 2
  2067. miny = min(path[0][1], path[1][1]) - height / 2
  2068. maxy = max(path[0][1], path[1][1]) + height / 2
  2069. log.debug("Coords: %s - %s - %s - %s" % (minx, miny, maxx, maxy))
  2070. poly_buffer.append(shply_box(minx, miny, maxx, maxy))
  2071. except:
  2072. pass
  2073. last_path_aperture = current_aperture
  2074. else:
  2075. self.app.inform.emit("[WARNING] Coordinates missing, line ignored: %s" % str(gline))
  2076. self.app.inform.emit("[WARNING_NOTCL] GERBER file might be CORRUPT. Check the file !!!")
  2077. elif current_operation_code == 2:
  2078. if len(path) > 1:
  2079. geo = None
  2080. ## --- BUFFERED ---
  2081. if making_region:
  2082. if follow:
  2083. geo = Polygon()
  2084. else:
  2085. elem = [linear_x, linear_y]
  2086. if elem != path[-1]:
  2087. path.append([linear_x, linear_y])
  2088. try:
  2089. geo = Polygon(path)
  2090. except ValueError:
  2091. log.warning("Problem %s %s" % (gline, line_num))
  2092. self.app.inform.emit("[ERROR] Region does not have enough points. "
  2093. "File will be processed but there are parser errors. "
  2094. "Line number: %s" % str(line_num))
  2095. else:
  2096. if last_path_aperture is None:
  2097. log.warning("No aperture defined for curent path. (%d)" % line_num)
  2098. width = self.apertures[last_path_aperture]["size"] # TODO: WARNING this should fail!
  2099. #log.debug("Line %d: Setting aperture to %s before buffering." % (line_num, last_path_aperture))
  2100. if follow:
  2101. geo = LineString(path)
  2102. else:
  2103. geo = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  2104. try:
  2105. if self.apertures[last_path_aperture]["type"] != 'R':
  2106. if not geo.is_empty:
  2107. poly_buffer.append(geo)
  2108. except:
  2109. poly_buffer.append(geo)
  2110. # if linear_x or linear_y are None, ignore those
  2111. if linear_x is not None and linear_y is not None:
  2112. path = [[linear_x, linear_y]] # Start new path
  2113. else:
  2114. self.app.inform.emit("[WARNING] Coordinates missing, line ignored: %s" % str(gline))
  2115. self.app.inform.emit("[WARNING_NOTCL] GERBER file might be CORRUPT. Check the file !!!")
  2116. # Flash
  2117. # Not allowed in region mode.
  2118. elif current_operation_code == 3:
  2119. # Create path draw so far.
  2120. if len(path) > 1:
  2121. # --- Buffered ----
  2122. width = self.apertures[last_path_aperture]["size"]
  2123. if follow:
  2124. geo = LineString(path)
  2125. else:
  2126. geo = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  2127. if not geo.is_empty:
  2128. try:
  2129. if self.apertures[current_aperture]["type"] != 'R':
  2130. poly_buffer.append(geo)
  2131. else:
  2132. pass
  2133. except:
  2134. poly_buffer.append(geo)
  2135. # Reset path starting point
  2136. path = [[linear_x, linear_y]]
  2137. # --- BUFFERED ---
  2138. # Draw the flash
  2139. if follow:
  2140. continue
  2141. flash = Gerber.create_flash_geometry(
  2142. Point(
  2143. [linear_x, linear_y]),
  2144. self.apertures[current_aperture],
  2145. int(self.steps_per_circle)
  2146. )
  2147. if not flash.is_empty:
  2148. poly_buffer.append(flash)
  2149. # maybe those lines are not exactly needed but it is easier to read the program as those coordinates
  2150. # are used in case that circular interpolation is encountered within the Gerber file
  2151. current_x = linear_x
  2152. current_y = linear_y
  2153. # log.debug("Line_number=%3s X=%s Y=%s (%s)" % (line_num, linear_x, linear_y, gline))
  2154. continue
  2155. ### G74/75* - Single or multiple quadrant arcs
  2156. match = self.quad_re.search(gline)
  2157. if match:
  2158. if match.group(1) == '4':
  2159. quadrant_mode = 'SINGLE'
  2160. else:
  2161. quadrant_mode = 'MULTI'
  2162. continue
  2163. ### G02/3 - Circular interpolation
  2164. # 2-clockwise, 3-counterclockwise
  2165. # Ex. format: G03 X0 Y50 I-50 J0 where the X, Y coords are the coords of the End Point
  2166. match = self.circ_re.search(gline)
  2167. if match:
  2168. arcdir = [None, None, "cw", "ccw"]
  2169. mode, circular_x, circular_y, i, j, d = match.groups()
  2170. try:
  2171. circular_x = parse_gerber_number(circular_x,
  2172. self.int_digits, self.frac_digits, self.gerber_zeros)
  2173. except:
  2174. circular_x = current_x
  2175. try:
  2176. circular_y = parse_gerber_number(circular_y,
  2177. self.int_digits, self.frac_digits, self.gerber_zeros)
  2178. except:
  2179. circular_y = current_y
  2180. # According to Gerber specification i and j are not modal, which means that when i or j are missing,
  2181. # they are to be interpreted as being zero
  2182. try:
  2183. i = parse_gerber_number(i, self.int_digits, self.frac_digits, self.gerber_zeros)
  2184. except:
  2185. i = 0
  2186. try:
  2187. j = parse_gerber_number(j, self.int_digits, self.frac_digits, self.gerber_zeros)
  2188. except:
  2189. j = 0
  2190. if quadrant_mode is None:
  2191. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  2192. log.error(gline)
  2193. continue
  2194. if mode is None and current_interpolation_mode not in [2, 3]:
  2195. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  2196. log.error(gline)
  2197. continue
  2198. elif mode is not None:
  2199. current_interpolation_mode = int(mode)
  2200. # Set operation code if provided
  2201. try:
  2202. current_operation_code = int(d)
  2203. current_d = current_operation_code
  2204. except:
  2205. current_operation_code = current_d
  2206. # Nothing created! Pen Up.
  2207. if current_operation_code == 2:
  2208. log.warning("Arc with D2. (%d)" % line_num)
  2209. if len(path) > 1:
  2210. if last_path_aperture is None:
  2211. log.warning("No aperture defined for curent path. (%d)" % line_num)
  2212. # --- BUFFERED ---
  2213. width = self.apertures[last_path_aperture]["size"]
  2214. if follow:
  2215. buffered = LineString(path)
  2216. else:
  2217. buffered = LineString(path).buffer(width / 1.999, int(self.steps_per_circle))
  2218. if not buffered.is_empty:
  2219. poly_buffer.append(buffered)
  2220. current_x = circular_x
  2221. current_y = circular_y
  2222. path = [[current_x, current_y]] # Start new path
  2223. continue
  2224. # Flash should not happen here
  2225. if current_operation_code == 3:
  2226. log.error("Trying to flash within arc. (%d)" % line_num)
  2227. continue
  2228. if quadrant_mode == 'MULTI':
  2229. center = [i + current_x, j + current_y]
  2230. radius = sqrt(i ** 2 + j ** 2)
  2231. start = arctan2(-j, -i) # Start angle
  2232. # Numerical errors might prevent start == stop therefore
  2233. # we check ahead of time. This should result in a
  2234. # 360 degree arc.
  2235. if current_x == circular_x and current_y == circular_y:
  2236. stop = start
  2237. else:
  2238. stop = arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  2239. this_arc = arc(center, radius, start, stop,
  2240. arcdir[current_interpolation_mode],
  2241. int(self.steps_per_circle))
  2242. # The last point in the computed arc can have
  2243. # numerical errors. The exact final point is the
  2244. # specified (x, y). Replace.
  2245. this_arc[-1] = (circular_x, circular_y)
  2246. # Last point in path is current point
  2247. # current_x = this_arc[-1][0]
  2248. # current_y = this_arc[-1][1]
  2249. current_x, current_y = circular_x, circular_y
  2250. # Append
  2251. path += this_arc
  2252. last_path_aperture = current_aperture
  2253. continue
  2254. if quadrant_mode == 'SINGLE':
  2255. center_candidates = [
  2256. [i + current_x, j + current_y],
  2257. [-i + current_x, j + current_y],
  2258. [i + current_x, -j + current_y],
  2259. [-i + current_x, -j + current_y]
  2260. ]
  2261. valid = False
  2262. log.debug("I: %f J: %f" % (i, j))
  2263. for center in center_candidates:
  2264. radius = sqrt(i ** 2 + j ** 2)
  2265. # Make sure radius to start is the same as radius to end.
  2266. radius2 = sqrt((center[0] - circular_x) ** 2 + (center[1] - circular_y) ** 2)
  2267. if radius2 < radius * 0.95 or radius2 > radius * 1.05:
  2268. continue # Not a valid center.
  2269. # Correct i and j and continue as with multi-quadrant.
  2270. i = center[0] - current_x
  2271. j = center[1] - current_y
  2272. start = arctan2(-j, -i) # Start angle
  2273. stop = arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  2274. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  2275. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  2276. (current_x, current_y, center[0], center[1], circular_x, circular_y))
  2277. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  2278. (start * 180 / pi, stop * 180 / pi, arcdir[current_interpolation_mode],
  2279. angle * 180 / pi, pi / 2 * 180 / pi, angle <= (pi + 1e-6) / 2))
  2280. if angle <= (pi + 1e-6) / 2:
  2281. log.debug("########## ACCEPTING ARC ############")
  2282. this_arc = arc(center, radius, start, stop,
  2283. arcdir[current_interpolation_mode],
  2284. int(self.steps_per_circle))
  2285. # Replace with exact values
  2286. this_arc[-1] = (circular_x, circular_y)
  2287. # current_x = this_arc[-1][0]
  2288. # current_y = this_arc[-1][1]
  2289. current_x, current_y = circular_x, circular_y
  2290. path += this_arc
  2291. last_path_aperture = current_aperture
  2292. valid = True
  2293. break
  2294. if valid:
  2295. continue
  2296. else:
  2297. log.warning("Invalid arc in line %d." % line_num)
  2298. ## EOF
  2299. match = self.eof_re.search(gline)
  2300. if match:
  2301. continue
  2302. ### Line did not match any pattern. Warn user.
  2303. log.warning("Line ignored (%d): %s" % (line_num, gline))
  2304. if len(path) > 1:
  2305. # In case that G01 (moving) aperture is rectangular, there is no need to still create
  2306. # another geo since we already created a shapely box using the start and end coordinates found in
  2307. # path variable. We do it only for other apertures than 'R' type
  2308. if self.apertures[last_path_aperture]["type"] == 'R':
  2309. pass
  2310. else:
  2311. # EOF, create shapely LineString if something still in path
  2312. ## --- Buffered ---
  2313. width = self.apertures[last_path_aperture]["size"]
  2314. if follow:
  2315. geo = LineString(path)
  2316. else:
  2317. geo = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  2318. if not geo.is_empty:
  2319. poly_buffer.append(geo)
  2320. # --- Apply buffer ---
  2321. if follow:
  2322. self.solid_geometry = poly_buffer
  2323. return
  2324. log.warning("Joining %d polygons." % len(poly_buffer))
  2325. if len(poly_buffer) == 0:
  2326. log.error("Object is not Gerber file or empty. Aborting Object creation.")
  2327. return
  2328. if self.use_buffer_for_union:
  2329. log.debug("Union by buffer...")
  2330. new_poly = MultiPolygon(poly_buffer)
  2331. new_poly = new_poly.buffer(0.00000001)
  2332. new_poly = new_poly.buffer(-0.00000001)
  2333. log.warning("Union(buffer) done.")
  2334. else:
  2335. log.debug("Union by union()...")
  2336. new_poly = cascaded_union(poly_buffer)
  2337. new_poly = new_poly.buffer(0, int(self.steps_per_circle / 4))
  2338. log.warning("Union done.")
  2339. if current_polarity == 'D':
  2340. self.solid_geometry = self.solid_geometry.union(new_poly)
  2341. else:
  2342. self.solid_geometry = self.solid_geometry.difference(new_poly)
  2343. except Exception as err:
  2344. ex_type, ex, tb = sys.exc_info()
  2345. traceback.print_tb(tb)
  2346. #print traceback.format_exc()
  2347. log.error("Gerber PARSING FAILED. Line %d: %s" % (line_num, gline))
  2348. loc = 'Gerber Line #%d Gerber Line Content: %s\n' % (line_num, gline) + repr(err)
  2349. self.app.inform.emit("[ERROR]Gerber Parser ERROR.\n%s:" % loc)
  2350. @staticmethod
  2351. def create_flash_geometry(location, aperture, steps_per_circle=None):
  2352. # log.debug('Flashing @%s, Aperture: %s' % (location, aperture))
  2353. if steps_per_circle is None:
  2354. steps_per_circle = 64
  2355. if type(location) == list:
  2356. location = Point(location)
  2357. if aperture['type'] == 'C': # Circles
  2358. return location.buffer(aperture['size'] / 2, int(steps_per_circle / 4))
  2359. if aperture['type'] == 'R': # Rectangles
  2360. loc = location.coords[0]
  2361. width = aperture['width']
  2362. height = aperture['height']
  2363. minx = loc[0] - width / 2
  2364. maxx = loc[0] + width / 2
  2365. miny = loc[1] - height / 2
  2366. maxy = loc[1] + height / 2
  2367. return shply_box(minx, miny, maxx, maxy)
  2368. if aperture['type'] == 'O': # Obround
  2369. loc = location.coords[0]
  2370. width = aperture['width']
  2371. height = aperture['height']
  2372. if width > height:
  2373. p1 = Point(loc[0] + 0.5 * (width - height), loc[1])
  2374. p2 = Point(loc[0] - 0.5 * (width - height), loc[1])
  2375. c1 = p1.buffer(height * 0.5, int(steps_per_circle / 4))
  2376. c2 = p2.buffer(height * 0.5, int(steps_per_circle / 4))
  2377. else:
  2378. p1 = Point(loc[0], loc[1] + 0.5 * (height - width))
  2379. p2 = Point(loc[0], loc[1] - 0.5 * (height - width))
  2380. c1 = p1.buffer(width * 0.5, int(steps_per_circle / 4))
  2381. c2 = p2.buffer(width * 0.5, int(steps_per_circle / 4))
  2382. return cascaded_union([c1, c2]).convex_hull
  2383. if aperture['type'] == 'P': # Regular polygon
  2384. loc = location.coords[0]
  2385. diam = aperture['diam']
  2386. n_vertices = aperture['nVertices']
  2387. points = []
  2388. for i in range(0, n_vertices):
  2389. x = loc[0] + 0.5 * diam * (cos(2 * pi * i / n_vertices))
  2390. y = loc[1] + 0.5 * diam * (sin(2 * pi * i / n_vertices))
  2391. points.append((x, y))
  2392. ply = Polygon(points)
  2393. if 'rotation' in aperture:
  2394. ply = affinity.rotate(ply, aperture['rotation'])
  2395. return ply
  2396. if aperture['type'] == 'AM': # Aperture Macro
  2397. loc = location.coords[0]
  2398. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  2399. if flash_geo.is_empty:
  2400. log.warning("Empty geometry for Aperture Macro: %s" % str(aperture['macro'].name))
  2401. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  2402. log.warning("Unknown aperture type: %s" % aperture['type'])
  2403. return None
  2404. def create_geometry(self):
  2405. """
  2406. Geometry from a Gerber file is made up entirely of polygons.
  2407. Every stroke (linear or circular) has an aperture which gives
  2408. it thickness. Additionally, aperture strokes have non-zero area,
  2409. and regions naturally do as well.
  2410. :rtype : None
  2411. :return: None
  2412. """
  2413. # self.buffer_paths()
  2414. #
  2415. # self.fix_regions()
  2416. #
  2417. # self.do_flashes()
  2418. #
  2419. # self.solid_geometry = cascaded_union(self.buffered_paths +
  2420. # [poly['polygon'] for poly in self.regions] +
  2421. # self.flash_geometry)
  2422. def get_bounding_box(self, margin=0.0, rounded=False):
  2423. """
  2424. Creates and returns a rectangular polygon bounding at a distance of
  2425. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  2426. can optionally have rounded corners of radius equal to margin.
  2427. :param margin: Distance to enlarge the rectangular bounding
  2428. box in both positive and negative, x and y axes.
  2429. :type margin: float
  2430. :param rounded: Wether or not to have rounded corners.
  2431. :type rounded: bool
  2432. :return: The bounding box.
  2433. :rtype: Shapely.Polygon
  2434. """
  2435. bbox = self.solid_geometry.envelope.buffer(margin)
  2436. if not rounded:
  2437. bbox = bbox.envelope
  2438. return bbox
  2439. def bounds(self):
  2440. """
  2441. Returns coordinates of rectangular bounds
  2442. of Gerber geometry: (xmin, ymin, xmax, ymax).
  2443. """
  2444. # fixed issue of getting bounds only for one level lists of objects
  2445. # now it can get bounds for nested lists of objects
  2446. log.debug("Gerber->bounds()")
  2447. if self.solid_geometry is None:
  2448. log.debug("solid_geometry is None")
  2449. return 0, 0, 0, 0
  2450. def bounds_rec(obj):
  2451. if type(obj) is list and type(obj) is not MultiPolygon:
  2452. minx = Inf
  2453. miny = Inf
  2454. maxx = -Inf
  2455. maxy = -Inf
  2456. for k in obj:
  2457. if type(k) is dict:
  2458. for key in k:
  2459. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  2460. minx = min(minx, minx_)
  2461. miny = min(miny, miny_)
  2462. maxx = max(maxx, maxx_)
  2463. maxy = max(maxy, maxy_)
  2464. else:
  2465. try:
  2466. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2467. except Exception as e:
  2468. log.debug("camlib.Geometry.bounds() --> %s" % str(e))
  2469. return
  2470. minx = min(minx, minx_)
  2471. miny = min(miny, miny_)
  2472. maxx = max(maxx, maxx_)
  2473. maxy = max(maxy, maxy_)
  2474. return minx, miny, maxx, maxy
  2475. else:
  2476. # it's a Shapely object, return it's bounds
  2477. return obj.bounds
  2478. bounds_coords = bounds_rec(self.solid_geometry)
  2479. return bounds_coords
  2480. def scale(self, xfactor, yfactor=None, point=None):
  2481. """
  2482. Scales the objects' geometry on the XY plane by a given factor.
  2483. These are:
  2484. * ``buffered_paths``
  2485. * ``flash_geometry``
  2486. * ``solid_geometry``
  2487. * ``regions``
  2488. NOTE:
  2489. Does not modify the data used to create these elements. If these
  2490. are recreated, the scaling will be lost. This behavior was modified
  2491. because of the complexity reached in this class.
  2492. :param factor: Number by which to scale.
  2493. :type factor: float
  2494. :rtype : None
  2495. """
  2496. try:
  2497. xfactor = float(xfactor)
  2498. except:
  2499. self.app.inform.emit("[ERROR_NOTCL] Scale factor has to be a number: integer or float.")
  2500. return
  2501. if yfactor is None:
  2502. yfactor = xfactor
  2503. else:
  2504. try:
  2505. yfactor = float(yfactor)
  2506. except:
  2507. self.app.inform.emit("[ERROR_NOTCL] Scale factor has to be a number: integer or float.")
  2508. return
  2509. if point is None:
  2510. px = 0
  2511. py = 0
  2512. else:
  2513. px, py = point
  2514. def scale_geom(obj):
  2515. if type(obj) is list:
  2516. new_obj = []
  2517. for g in obj:
  2518. new_obj.append(scale_geom(g))
  2519. return new_obj
  2520. else:
  2521. return affinity.scale(obj, xfactor,
  2522. yfactor, origin=(px, py))
  2523. self.solid_geometry = scale_geom(self.solid_geometry)
  2524. self.app.inform.emit("[success]Gerber Scale done.")
  2525. ## solid_geometry ???
  2526. # It's a cascaded union of objects.
  2527. # self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  2528. # factor, origin=(0, 0))
  2529. # # Now buffered_paths, flash_geometry and solid_geometry
  2530. # self.create_geometry()
  2531. def offset(self, vect):
  2532. """
  2533. Offsets the objects' geometry on the XY plane by a given vector.
  2534. These are:
  2535. * ``buffered_paths``
  2536. * ``flash_geometry``
  2537. * ``solid_geometry``
  2538. * ``regions``
  2539. NOTE:
  2540. Does not modify the data used to create these elements. If these
  2541. are recreated, the scaling will be lost. This behavior was modified
  2542. because of the complexity reached in this class.
  2543. :param vect: (x, y) offset vector.
  2544. :type vect: tuple
  2545. :return: None
  2546. """
  2547. try:
  2548. dx, dy = vect
  2549. except TypeError:
  2550. self.app.inform.emit("[ERROR_NOTCL]An (x,y) pair of values are needed. "
  2551. "Probable you entered only one value in the Offset field.")
  2552. return
  2553. def offset_geom(obj):
  2554. if type(obj) is list:
  2555. new_obj = []
  2556. for g in obj:
  2557. new_obj.append(offset_geom(g))
  2558. return new_obj
  2559. else:
  2560. return affinity.translate(obj, xoff=dx, yoff=dy)
  2561. ## Solid geometry
  2562. # self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  2563. self.solid_geometry = offset_geom(self.solid_geometry)
  2564. self.app.inform.emit("[success]Gerber Offset done.")
  2565. def mirror(self, axis, point):
  2566. """
  2567. Mirrors the object around a specified axis passing through
  2568. the given point. What is affected:
  2569. * ``buffered_paths``
  2570. * ``flash_geometry``
  2571. * ``solid_geometry``
  2572. * ``regions``
  2573. NOTE:
  2574. Does not modify the data used to create these elements. If these
  2575. are recreated, the scaling will be lost. This behavior was modified
  2576. because of the complexity reached in this class.
  2577. :param axis: "X" or "Y" indicates around which axis to mirror.
  2578. :type axis: str
  2579. :param point: [x, y] point belonging to the mirror axis.
  2580. :type point: list
  2581. :return: None
  2582. """
  2583. px, py = point
  2584. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  2585. def mirror_geom(obj):
  2586. if type(obj) is list:
  2587. new_obj = []
  2588. for g in obj:
  2589. new_obj.append(mirror_geom(g))
  2590. return new_obj
  2591. else:
  2592. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  2593. self.solid_geometry = mirror_geom(self.solid_geometry)
  2594. # It's a cascaded union of objects.
  2595. # self.solid_geometry = affinity.scale(self.solid_geometry,
  2596. # xscale, yscale, origin=(px, py))
  2597. def skew(self, angle_x, angle_y, point):
  2598. """
  2599. Shear/Skew the geometries of an object by angles along x and y dimensions.
  2600. Parameters
  2601. ----------
  2602. xs, ys : float, float
  2603. The shear angle(s) for the x and y axes respectively. These can be
  2604. specified in either degrees (default) or radians by setting
  2605. use_radians=True.
  2606. See shapely manual for more information:
  2607. http://toblerity.org/shapely/manual.html#affine-transformations
  2608. """
  2609. px, py = point
  2610. def skew_geom(obj):
  2611. if type(obj) is list:
  2612. new_obj = []
  2613. for g in obj:
  2614. new_obj.append(skew_geom(g))
  2615. return new_obj
  2616. else:
  2617. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  2618. self.solid_geometry = skew_geom(self.solid_geometry)
  2619. # self.solid_geometry = affinity.skew(self.solid_geometry, angle_x, angle_y, origin=(px, py))
  2620. def rotate(self, angle, point):
  2621. """
  2622. Rotate an object by a given angle around given coords (point)
  2623. :param angle:
  2624. :param point:
  2625. :return:
  2626. """
  2627. px, py = point
  2628. def rotate_geom(obj):
  2629. if type(obj) is list:
  2630. new_obj = []
  2631. for g in obj:
  2632. new_obj.append(rotate_geom(g))
  2633. return new_obj
  2634. else:
  2635. return affinity.rotate(obj, angle, origin=(px, py))
  2636. self.solid_geometry = rotate_geom(self.solid_geometry)
  2637. # self.solid_geometry = affinity.rotate(self.solid_geometry, angle, origin=(px, py))
  2638. class Excellon(Geometry):
  2639. """
  2640. *ATTRIBUTES*
  2641. * ``tools`` (dict): The key is the tool name and the value is
  2642. a dictionary specifying the tool:
  2643. ================ ====================================
  2644. Key Value
  2645. ================ ====================================
  2646. C Diameter of the tool
  2647. Others Not supported (Ignored).
  2648. ================ ====================================
  2649. * ``drills`` (list): Each is a dictionary:
  2650. ================ ====================================
  2651. Key Value
  2652. ================ ====================================
  2653. point (Shapely.Point) Where to drill
  2654. tool (str) A key in ``tools``
  2655. ================ ====================================
  2656. * ``slots`` (list): Each is a dictionary
  2657. ================ ====================================
  2658. Key Value
  2659. ================ ====================================
  2660. start (Shapely.Point) Start point of the slot
  2661. stop (Shapely.Point) Stop point of the slot
  2662. tool (str) A key in ``tools``
  2663. ================ ====================================
  2664. """
  2665. defaults = {
  2666. "zeros": "L",
  2667. "excellon_format_upper_mm": '3',
  2668. "excellon_format_lower_mm": '3',
  2669. "excellon_format_upper_in": '2',
  2670. "excellon_format_lower_in": '4',
  2671. "excellon_units": 'INCH',
  2672. "geo_steps_per_circle": '64'
  2673. }
  2674. def __init__(self, zeros=None, excellon_format_upper_mm=None, excellon_format_lower_mm=None,
  2675. excellon_format_upper_in=None, excellon_format_lower_in=None, excellon_units=None,
  2676. geo_steps_per_circle=None):
  2677. """
  2678. The constructor takes no parameters.
  2679. :return: Excellon object.
  2680. :rtype: Excellon
  2681. """
  2682. if geo_steps_per_circle is None:
  2683. geo_steps_per_circle = int(Excellon.defaults['geo_steps_per_circle'])
  2684. self.geo_steps_per_circle = int(geo_steps_per_circle)
  2685. Geometry.__init__(self, geo_steps_per_circle=int(geo_steps_per_circle))
  2686. # dictionary to store tools, see above for description
  2687. self.tools = {}
  2688. # list to store the drills, see above for description
  2689. self.drills = []
  2690. # self.slots (list) to store the slots; each is a dictionary
  2691. self.slots = []
  2692. # it serve to flag if a start routing or a stop routing was encountered
  2693. # if a stop is encounter and this flag is still 0 (so there is no stop for a previous start) issue error
  2694. self.routing_flag = 1
  2695. self.match_routing_start = None
  2696. self.match_routing_stop = None
  2697. self.num_tools = [] # List for keeping the tools sorted
  2698. self.index_per_tool = {} # Dictionary to store the indexed points for each tool
  2699. ## IN|MM -> Units are inherited from Geometry
  2700. #self.units = units
  2701. # Trailing "T" or leading "L" (default)
  2702. #self.zeros = "T"
  2703. self.zeros = zeros or self.defaults["zeros"]
  2704. self.zeros_found = self.zeros
  2705. self.units_found = self.units
  2706. # Excellon format
  2707. self.excellon_format_upper_in = excellon_format_upper_in or self.defaults["excellon_format_upper_in"]
  2708. self.excellon_format_lower_in = excellon_format_lower_in or self.defaults["excellon_format_lower_in"]
  2709. self.excellon_format_upper_mm = excellon_format_upper_mm or self.defaults["excellon_format_upper_mm"]
  2710. self.excellon_format_lower_mm = excellon_format_lower_mm or self.defaults["excellon_format_lower_mm"]
  2711. self.excellon_units = excellon_units or self.defaults["excellon_units"]
  2712. # Attributes to be included in serialization
  2713. # Always append to it because it carries contents
  2714. # from Geometry.
  2715. self.ser_attrs += ['tools', 'drills', 'zeros', 'excellon_format_upper_mm', 'excellon_format_lower_mm',
  2716. 'excellon_format_upper_in', 'excellon_format_lower_in', 'excellon_units', 'slots']
  2717. #### Patterns ####
  2718. # Regex basics:
  2719. # ^ - beginning
  2720. # $ - end
  2721. # *: 0 or more, +: 1 or more, ?: 0 or 1
  2722. # M48 - Beginning of Part Program Header
  2723. self.hbegin_re = re.compile(r'^M48$')
  2724. # ;HEADER - Beginning of Allegro Program Header
  2725. self.allegro_hbegin_re = re.compile(r'\;\s*(HEADER)')
  2726. # M95 or % - End of Part Program Header
  2727. # NOTE: % has different meaning in the body
  2728. self.hend_re = re.compile(r'^(?:M95|%)$')
  2729. # FMAT Excellon format
  2730. # Ignored in the parser
  2731. #self.fmat_re = re.compile(r'^FMAT,([12])$')
  2732. # Number format and units
  2733. # INCH uses 6 digits
  2734. # METRIC uses 5/6
  2735. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  2736. # Tool definition/parameters (?= is look-ahead
  2737. # NOTE: This might be an overkill!
  2738. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  2739. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  2740. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  2741. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  2742. self.toolset_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))?' +
  2743. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  2744. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  2745. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  2746. self.detect_gcode_re = re.compile(r'^G2([01])$')
  2747. # Tool select
  2748. # Can have additional data after tool number but
  2749. # is ignored if present in the header.
  2750. # Warning: This will match toolset_re too.
  2751. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  2752. self.toolsel_re = re.compile(r'^T(\d+)')
  2753. # Headerless toolset
  2754. self.toolset_hl_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))')
  2755. # Comment
  2756. self.comm_re = re.compile(r'^;(.*)$')
  2757. # Absolute/Incremental G90/G91
  2758. self.absinc_re = re.compile(r'^G9([01])$')
  2759. # Modes of operation
  2760. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  2761. self.modes_re = re.compile(r'^G0([012345])')
  2762. # Measuring mode
  2763. # 1-metric, 2-inch
  2764. self.meas_re = re.compile(r'^M7([12])$')
  2765. # Coordinates
  2766. # self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  2767. # self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  2768. coordsperiod_re_string = r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]'
  2769. self.coordsperiod_re = re.compile(coordsperiod_re_string)
  2770. coordsnoperiod_re_string = r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]'
  2771. self.coordsnoperiod_re = re.compile(coordsnoperiod_re_string)
  2772. # Slots parsing
  2773. slots_re_string = r'^([^G]+)G85(.*)$'
  2774. self.slots_re = re.compile(slots_re_string)
  2775. # R - Repeat hole (# times, X offset, Y offset)
  2776. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  2777. # Various stop/pause commands
  2778. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  2779. # Allegro Excellon format support
  2780. self.tool_units_re = re.compile(r'(\;\s*Holesize \d+.\s*\=\s*(\d+.\d+).*(MILS|MM))')
  2781. # Parse coordinates
  2782. self.leadingzeros_re = re.compile(r'^[-\+]?(0*)(\d*)')
  2783. # Repeating command
  2784. self.repeat_re = re.compile(r'R(\d+)')
  2785. def parse_file(self, filename):
  2786. """
  2787. Reads the specified file as array of lines as
  2788. passes it to ``parse_lines()``.
  2789. :param filename: The file to be read and parsed.
  2790. :type filename: str
  2791. :return: None
  2792. """
  2793. efile = open(filename, 'r')
  2794. estr = efile.readlines()
  2795. efile.close()
  2796. try:
  2797. self.parse_lines(estr)
  2798. except:
  2799. return "fail"
  2800. def parse_lines(self, elines):
  2801. """
  2802. Main Excellon parser.
  2803. :param elines: List of strings, each being a line of Excellon code.
  2804. :type elines: list
  2805. :return: None
  2806. """
  2807. # State variables
  2808. current_tool = ""
  2809. in_header = False
  2810. headerless = False
  2811. current_x = None
  2812. current_y = None
  2813. slot_current_x = None
  2814. slot_current_y = None
  2815. name_tool = 0
  2816. allegro_warning = False
  2817. line_units_found = False
  2818. repeating_x = 0
  2819. repeating_y = 0
  2820. repeat = 0
  2821. line_units = ''
  2822. #### Parsing starts here ####
  2823. line_num = 0 # Line number
  2824. eline = ""
  2825. try:
  2826. for eline in elines:
  2827. line_num += 1
  2828. # log.debug("%3d %s" % (line_num, str(eline)))
  2829. # Cleanup lines
  2830. eline = eline.strip(' \r\n')
  2831. # Excellon files and Gcode share some extensions therefore if we detect G20 or G21 it's GCODe
  2832. # and we need to exit from here
  2833. if self.detect_gcode_re.search(eline):
  2834. log.warning("This is GCODE mark: %s" % eline)
  2835. self.app.inform.emit('[ERROR_NOTCL] This is GCODE mark: %s' % eline)
  2836. return
  2837. # Header Begin (M48) #
  2838. if self.hbegin_re.search(eline):
  2839. in_header = True
  2840. log.warning("Found start of the header: %s" % eline)
  2841. continue
  2842. # Allegro Header Begin (;HEADER) #
  2843. if self.allegro_hbegin_re.search(eline):
  2844. in_header = True
  2845. allegro_warning = True
  2846. log.warning("Found ALLEGRO start of the header: %s" % eline)
  2847. continue
  2848. # Header End #
  2849. # Since there might be comments in the header that include char % or M95
  2850. # we ignore the lines starting with ';' which show they are comments
  2851. if self.comm_re.search(eline):
  2852. match = self.tool_units_re.search(eline)
  2853. if match:
  2854. if line_units_found is False:
  2855. line_units_found = True
  2856. line_units = match.group(3)
  2857. self.convert_units({"MILS": "IN", "MM": "MM"}[line_units])
  2858. log.warning("Type of Allegro UNITS found inline: %s" % line_units)
  2859. if match.group(2):
  2860. name_tool += 1
  2861. if line_units == 'MILS':
  2862. spec = {"C": (float(match.group(2)) / 1000)}
  2863. self.tools[str(name_tool)] = spec
  2864. log.debug(" Tool definition: %s %s" % (name_tool, spec))
  2865. else:
  2866. spec = {"C": float(match.group(2))}
  2867. self.tools[str(name_tool)] = spec
  2868. log.debug(" Tool definition: %s %s" % (name_tool, spec))
  2869. continue
  2870. else:
  2871. log.warning("Line ignored, it's a comment: %s" % eline)
  2872. else:
  2873. if self.hend_re.search(eline):
  2874. if in_header is False:
  2875. log.warning("Found end of the header but there is no header: %s" % eline)
  2876. log.warning("The only useful data in header are tools, units and format.")
  2877. log.warning("Therefore we will create units and format based on defaults.")
  2878. headerless = True
  2879. try:
  2880. self.convert_units({"INCH": "IN", "METRIC": "MM"}[self.excellon_units])
  2881. print("Units converted .............................. %s" % self.excellon_units)
  2882. except Exception as e:
  2883. log.warning("Units could not be converted: %s" % str(e))
  2884. in_header = False
  2885. # for Allegro type of Excellons we reset name_tool variable so we can reuse it for toolchange
  2886. if allegro_warning is True:
  2887. name_tool = 0
  2888. log.warning("Found end of the header: %s" % eline)
  2889. continue
  2890. ## Alternative units format M71/M72
  2891. # Supposed to be just in the body (yes, the body)
  2892. # but some put it in the header (PADS for example).
  2893. # Will detect anywhere. Occurrence will change the
  2894. # object's units.
  2895. match = self.meas_re.match(eline)
  2896. if match:
  2897. #self.units = {"1": "MM", "2": "IN"}[match.group(1)]
  2898. # Modified for issue #80
  2899. self.convert_units({"1": "MM", "2": "IN"}[match.group(1)])
  2900. log.debug(" Units: %s" % self.units)
  2901. if self.units == 'MM':
  2902. log.warning("Excellon format preset is: %s" % self.excellon_format_upper_mm + \
  2903. ':' + str(self.excellon_format_lower_mm))
  2904. else:
  2905. log.warning("Excellon format preset is: %s" % self.excellon_format_upper_in + \
  2906. ':' + str(self.excellon_format_lower_in))
  2907. continue
  2908. #### Body ####
  2909. if not in_header:
  2910. ## Tool change ##
  2911. match = self.toolsel_re.search(eline)
  2912. if match:
  2913. current_tool = str(int(match.group(1)))
  2914. log.debug("Tool change: %s" % current_tool)
  2915. if headerless is True:
  2916. match = self.toolset_hl_re.search(eline)
  2917. if match:
  2918. name = str(int(match.group(1)))
  2919. spec = {
  2920. "C": float(match.group(2)),
  2921. }
  2922. self.tools[name] = spec
  2923. log.debug(" Tool definition out of header: %s %s" % (name, spec))
  2924. continue
  2925. ## Allegro Type Tool change ##
  2926. if allegro_warning is True:
  2927. match = self.absinc_re.search(eline)
  2928. match1 = self.stop_re.search(eline)
  2929. if match or match1:
  2930. name_tool += 1
  2931. current_tool = str(name_tool)
  2932. log.debug(" Tool change for Allegro type of Excellon: %s" % current_tool)
  2933. continue
  2934. ## Slots parsing for drilled slots (contain G85)
  2935. # a Excellon drilled slot line may look like this:
  2936. # X01125Y0022244G85Y0027756
  2937. match = self.slots_re.search(eline)
  2938. if match:
  2939. # signal that there are milling slots operations
  2940. self.defaults['excellon_drills'] = False
  2941. # the slot start coordinates group is to the left of G85 command (group(1) )
  2942. # the slot stop coordinates group is to the right of G85 command (group(2) )
  2943. start_coords_match = match.group(1)
  2944. stop_coords_match = match.group(2)
  2945. # Slot coordinates without period ##
  2946. # get the coordinates for slot start and for slot stop into variables
  2947. start_coords_noperiod = self.coordsnoperiod_re.search(start_coords_match)
  2948. stop_coords_noperiod = self.coordsnoperiod_re.search(stop_coords_match)
  2949. if start_coords_noperiod:
  2950. try:
  2951. slot_start_x = self.parse_number(start_coords_noperiod.group(1))
  2952. slot_current_x = slot_start_x
  2953. except TypeError:
  2954. slot_start_x = slot_current_x
  2955. except:
  2956. return
  2957. try:
  2958. slot_start_y = self.parse_number(start_coords_noperiod.group(2))
  2959. slot_current_y = slot_start_y
  2960. except TypeError:
  2961. slot_start_y = slot_current_y
  2962. except:
  2963. return
  2964. try:
  2965. slot_stop_x = self.parse_number(stop_coords_noperiod.group(1))
  2966. slot_current_x = slot_stop_x
  2967. except TypeError:
  2968. slot_stop_x = slot_current_x
  2969. except:
  2970. return
  2971. try:
  2972. slot_stop_y = self.parse_number(stop_coords_noperiod.group(2))
  2973. slot_current_y = slot_stop_y
  2974. except TypeError:
  2975. slot_stop_y = slot_current_y
  2976. except:
  2977. return
  2978. if (slot_start_x is None or slot_start_y is None or
  2979. slot_stop_x is None or slot_stop_y is None):
  2980. log.error("Slots are missing some or all coordinates.")
  2981. continue
  2982. # we have a slot
  2983. log.debug('Parsed a slot with coordinates: ' + str([slot_start_x,
  2984. slot_start_y, slot_stop_x,
  2985. slot_stop_y]))
  2986. # store current tool diameter as slot diameter
  2987. slot_dia = 0.05
  2988. try:
  2989. slot_dia = float(self.tools[current_tool]['C'])
  2990. except:
  2991. pass
  2992. log.debug(
  2993. 'Milling/Drilling slot with tool %s, diam=%f' % (
  2994. current_tool,
  2995. slot_dia
  2996. )
  2997. )
  2998. self.slots.append(
  2999. {
  3000. 'start': Point(slot_start_x, slot_start_y),
  3001. 'stop': Point(slot_stop_x, slot_stop_y),
  3002. 'tool': current_tool
  3003. }
  3004. )
  3005. continue
  3006. # Slot coordinates with period: Use literally. ##
  3007. # get the coordinates for slot start and for slot stop into variables
  3008. start_coords_period = self.coordsperiod_re.search(start_coords_match)
  3009. stop_coords_period = self.coordsperiod_re.search(stop_coords_match)
  3010. if start_coords_period:
  3011. try:
  3012. slot_start_x = float(start_coords_period.group(1))
  3013. slot_current_x = slot_start_x
  3014. except TypeError:
  3015. slot_start_x = slot_current_x
  3016. except:
  3017. return
  3018. try:
  3019. slot_start_y = float(start_coords_period.group(2))
  3020. slot_current_y = slot_start_y
  3021. except TypeError:
  3022. slot_start_y = slot_current_y
  3023. except:
  3024. return
  3025. try:
  3026. slot_stop_x = float(stop_coords_period.group(1))
  3027. slot_current_x = slot_stop_x
  3028. except TypeError:
  3029. slot_stop_x = slot_current_x
  3030. except:
  3031. return
  3032. try:
  3033. slot_stop_y = float(stop_coords_period.group(2))
  3034. slot_current_y = slot_stop_y
  3035. except TypeError:
  3036. slot_stop_y = slot_current_y
  3037. except:
  3038. return
  3039. if (slot_start_x is None or slot_start_y is None or
  3040. slot_stop_x is None or slot_stop_y is None):
  3041. log.error("Slots are missing some or all coordinates.")
  3042. continue
  3043. # we have a slot
  3044. log.debug('Parsed a slot with coordinates: ' + str([slot_start_x,
  3045. slot_start_y, slot_stop_x, slot_stop_y]))
  3046. # store current tool diameter as slot diameter
  3047. slot_dia = 0.05
  3048. try:
  3049. slot_dia = float(self.tools[current_tool]['C'])
  3050. except:
  3051. pass
  3052. log.debug(
  3053. 'Milling/Drilling slot with tool %s, diam=%f' % (
  3054. current_tool,
  3055. slot_dia
  3056. )
  3057. )
  3058. self.slots.append(
  3059. {
  3060. 'start': Point(slot_start_x, slot_start_y),
  3061. 'stop': Point(slot_stop_x, slot_stop_y),
  3062. 'tool': current_tool
  3063. }
  3064. )
  3065. continue
  3066. ## Coordinates without period ##
  3067. match = self.coordsnoperiod_re.search(eline)
  3068. if match:
  3069. matchr = self.repeat_re.search(eline)
  3070. if matchr:
  3071. repeat = int(matchr.group(1))
  3072. try:
  3073. x = self.parse_number(match.group(1))
  3074. repeating_x = current_x
  3075. current_x = x
  3076. except TypeError:
  3077. x = current_x
  3078. repeating_x = 0
  3079. except:
  3080. return
  3081. try:
  3082. y = self.parse_number(match.group(2))
  3083. repeating_y = current_y
  3084. current_y = y
  3085. except TypeError:
  3086. y = current_y
  3087. repeating_y = 0
  3088. except:
  3089. return
  3090. if x is None or y is None:
  3091. log.error("Missing coordinates")
  3092. continue
  3093. ## Excellon Routing parse
  3094. if len(re.findall("G00", eline)) > 0:
  3095. self.match_routing_start = 'G00'
  3096. # signal that there are milling slots operations
  3097. self.defaults['excellon_drills'] = False
  3098. self.routing_flag = 0
  3099. slot_start_x = x
  3100. slot_start_y = y
  3101. continue
  3102. if self.routing_flag == 0:
  3103. if len(re.findall("G01", eline)) > 0:
  3104. self.match_routing_stop = 'G01'
  3105. # signal that there are milling slots operations
  3106. self.defaults['excellon_drills'] = False
  3107. self.routing_flag = 1
  3108. slot_stop_x = x
  3109. slot_stop_y = y
  3110. self.slots.append(
  3111. {
  3112. 'start': Point(slot_start_x, slot_start_y),
  3113. 'stop': Point(slot_stop_x, slot_stop_y),
  3114. 'tool': current_tool
  3115. }
  3116. )
  3117. continue
  3118. if self.match_routing_start is None and self.match_routing_stop is None:
  3119. if repeat == 0:
  3120. # signal that there are drill operations
  3121. self.defaults['excellon_drills'] = True
  3122. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  3123. else:
  3124. coordx = x
  3125. coordy = y
  3126. while repeat > 0:
  3127. if repeating_x:
  3128. coordx = (repeat * x) + repeating_x
  3129. if repeating_y:
  3130. coordy = (repeat * y) + repeating_y
  3131. self.drills.append({'point': Point((coordx, coordy)), 'tool': current_tool})
  3132. repeat -= 1
  3133. repeating_x = repeating_y = 0
  3134. log.debug("{:15} {:8} {:8}".format(eline, x, y))
  3135. continue
  3136. ## Coordinates with period: Use literally. ##
  3137. match = self.coordsperiod_re.search(eline)
  3138. if match:
  3139. matchr = self.repeat_re.search(eline)
  3140. if matchr:
  3141. repeat = int(matchr.group(1))
  3142. if match:
  3143. # signal that there are drill operations
  3144. self.defaults['excellon_drills'] = True
  3145. try:
  3146. x = float(match.group(1))
  3147. repeating_x = current_x
  3148. current_x = x
  3149. except TypeError:
  3150. x = current_x
  3151. repeating_x = 0
  3152. try:
  3153. y = float(match.group(2))
  3154. repeating_y = current_y
  3155. current_y = y
  3156. except TypeError:
  3157. y = current_y
  3158. repeating_y = 0
  3159. if x is None or y is None:
  3160. log.error("Missing coordinates")
  3161. continue
  3162. ## Excellon Routing parse
  3163. if len(re.findall("G00", eline)) > 0:
  3164. self.match_routing_start = 'G00'
  3165. # signal that there are milling slots operations
  3166. self.defaults['excellon_drills'] = False
  3167. self.routing_flag = 0
  3168. slot_start_x = x
  3169. slot_start_y = y
  3170. continue
  3171. if self.routing_flag == 0:
  3172. if len(re.findall("G01", eline)) > 0:
  3173. self.match_routing_stop = 'G01'
  3174. # signal that there are milling slots operations
  3175. self.defaults['excellon_drills'] = False
  3176. self.routing_flag = 1
  3177. slot_stop_x = x
  3178. slot_stop_y = y
  3179. self.slots.append(
  3180. {
  3181. 'start': Point(slot_start_x, slot_start_y),
  3182. 'stop': Point(slot_stop_x, slot_stop_y),
  3183. 'tool': current_tool
  3184. }
  3185. )
  3186. continue
  3187. if self.match_routing_start is None and self.match_routing_stop is None:
  3188. # signal that there are drill operations
  3189. if repeat == 0:
  3190. # signal that there are drill operations
  3191. self.defaults['excellon_drills'] = True
  3192. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  3193. else:
  3194. coordx = x
  3195. coordy = y
  3196. while repeat > 0:
  3197. if repeating_x:
  3198. coordx = (repeat * x) + repeating_x
  3199. if repeating_y:
  3200. coordy = (repeat * y) + repeating_y
  3201. self.drills.append({'point': Point((coordx, coordy)), 'tool': current_tool})
  3202. repeat -= 1
  3203. repeating_x = repeating_y = 0
  3204. log.debug("{:15} {:8} {:8}".format(eline, x, y))
  3205. continue
  3206. #### Header ####
  3207. if in_header:
  3208. ## Tool definitions ##
  3209. match = self.toolset_re.search(eline)
  3210. if match:
  3211. name = str(int(match.group(1)))
  3212. spec = {
  3213. "C": float(match.group(2)),
  3214. # "F": float(match.group(3)),
  3215. # "S": float(match.group(4)),
  3216. # "B": float(match.group(5)),
  3217. # "H": float(match.group(6)),
  3218. # "Z": float(match.group(7))
  3219. }
  3220. self.tools[name] = spec
  3221. log.debug(" Tool definition: %s %s" % (name, spec))
  3222. continue
  3223. ## Units and number format ##
  3224. match = self.units_re.match(eline)
  3225. if match:
  3226. self.units_found = match.group(1)
  3227. self.zeros = match.group(2) # "T" or "L". Might be empty
  3228. # self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  3229. # Modified for issue #80
  3230. self.convert_units({"INCH": "IN", "METRIC": "MM"}[self.units_found])
  3231. # log.warning(" Units/Format: %s %s" % (self.units, self.zeros))
  3232. log.warning("Units: %s" % self.units)
  3233. if self.units == 'MM':
  3234. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_mm) +
  3235. ':' + str(self.excellon_format_lower_mm))
  3236. else:
  3237. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_in) +
  3238. ':' + str(self.excellon_format_lower_in))
  3239. log.warning("Type of zeros found inline: %s" % self.zeros)
  3240. continue
  3241. # Search for units type again it might be alone on the line
  3242. if "INCH" in eline:
  3243. line_units = "INCH"
  3244. # Modified for issue #80
  3245. self.convert_units({"INCH": "IN", "METRIC": "MM"}[line_units])
  3246. log.warning("Type of UNITS found inline: %s" % line_units)
  3247. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_in) +
  3248. ':' + str(self.excellon_format_lower_in))
  3249. # TODO: not working
  3250. #FlatCAMApp.App.inform.emit("Detected INLINE: %s" % str(eline))
  3251. continue
  3252. elif "METRIC" in eline:
  3253. line_units = "METRIC"
  3254. # Modified for issue #80
  3255. self.convert_units({"INCH": "IN", "METRIC": "MM"}[line_units])
  3256. log.warning("Type of UNITS found inline: %s" % line_units)
  3257. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_mm) +
  3258. ':' + str(self.excellon_format_lower_mm))
  3259. # TODO: not working
  3260. #FlatCAMApp.App.inform.emit("Detected INLINE: %s" % str(eline))
  3261. continue
  3262. # Search for zeros type again because it might be alone on the line
  3263. match = re.search(r'[LT]Z',eline)
  3264. if match:
  3265. self.zeros = match.group()
  3266. log.warning("Type of zeros found: %s" % self.zeros)
  3267. continue
  3268. ## Units and number format outside header##
  3269. match = self.units_re.match(eline)
  3270. if match:
  3271. self.units_found = match.group(1)
  3272. self.zeros = match.group(2) # "T" or "L". Might be empty
  3273. # self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  3274. # Modified for issue #80
  3275. self.convert_units({"INCH": "IN", "METRIC": "MM"}[self.units_found])
  3276. # log.warning(" Units/Format: %s %s" % (self.units, self.zeros))
  3277. log.warning("Units: %s" % self.units)
  3278. if self.units == 'MM':
  3279. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_mm) +
  3280. ':' + str(self.excellon_format_lower_mm))
  3281. else:
  3282. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_in) +
  3283. ':' + str(self.excellon_format_lower_in))
  3284. log.warning("Type of zeros found outside header, inline: %s" % self.zeros)
  3285. log.warning("UNITS found outside header")
  3286. continue
  3287. log.warning("Line ignored: %s" % eline)
  3288. # make sure that since we are in headerless mode, we convert the tools only after the file parsing
  3289. # is finished since the tools definitions are spread in the Excellon body. We use as units the value
  3290. # from self.defaults['excellon_units']
  3291. log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
  3292. except Exception as e:
  3293. log.error("Excellon PARSING FAILED. Line %d: %s" % (line_num, eline))
  3294. msg = "[ERROR_NOTCL] An internal error has ocurred. See shell.\n"
  3295. msg += '[ERROR] Excellon Parser error.\nParsing Failed. Line %d: %s\n' % (line_num, eline)
  3296. msg += traceback.format_exc()
  3297. self.app.inform.emit(msg)
  3298. return "fail"
  3299. def parse_number(self, number_str):
  3300. """
  3301. Parses coordinate numbers without period.
  3302. :param number_str: String representing the numerical value.
  3303. :type number_str: str
  3304. :return: Floating point representation of the number
  3305. :rtype: float
  3306. """
  3307. match = self.leadingzeros_re.search(number_str)
  3308. nr_length = len(match.group(1)) + len(match.group(2))
  3309. try:
  3310. if self.zeros == "L" or self.zeros == "LZ":
  3311. # With leading zeros, when you type in a coordinate,
  3312. # the leading zeros must always be included. Trailing zeros
  3313. # are unneeded and may be left off. The CNC-7 will automatically add them.
  3314. # r'^[-\+]?(0*)(\d*)'
  3315. # 6 digits are divided by 10^4
  3316. # If less than size digits, they are automatically added,
  3317. # 5 digits then are divided by 10^3 and so on.
  3318. if self.units.lower() == "in":
  3319. result = float(number_str) / (10 ** (float(nr_length) - float(self.excellon_format_upper_in)))
  3320. else:
  3321. result = float(number_str) / (10 ** (float(nr_length) - float(self.excellon_format_upper_mm)))
  3322. return result
  3323. else: # Trailing
  3324. # You must show all zeros to the right of the number and can omit
  3325. # all zeros to the left of the number. The CNC-7 will count the number
  3326. # of digits you typed and automatically fill in the missing zeros.
  3327. ## flatCAM expects 6digits
  3328. # flatCAM expects the number of digits entered into the defaults
  3329. if self.units.lower() == "in": # Inches is 00.0000
  3330. result = float(number_str) / (10 ** (float(self.excellon_format_lower_in)))
  3331. else: # Metric is 000.000
  3332. result = float(number_str) / (10 ** (float(self.excellon_format_lower_mm)))
  3333. return result
  3334. except Exception as e:
  3335. log.error("Aborted. Operation could not be completed due of %s" % str(e))
  3336. return
  3337. def create_geometry(self):
  3338. """
  3339. Creates circles of the tool diameter at every point
  3340. specified in ``self.drills``. Also creates geometries (polygons)
  3341. for the slots as specified in ``self.slots``
  3342. All the resulting geometry is stored into self.solid_geometry list.
  3343. The list self.solid_geometry has 2 elements: first is a dict with the drills geometry,
  3344. and second element is another similar dict that contain the slots geometry.
  3345. Each dict has as keys the tool diameters and as values lists with Shapely objects, the geometries
  3346. ================ ====================================
  3347. Key Value
  3348. ================ ====================================
  3349. tool_diameter list of (Shapely.Point) Where to drill
  3350. ================ ====================================
  3351. :return: None
  3352. """
  3353. self.solid_geometry = []
  3354. try:
  3355. for drill in self.drills:
  3356. # poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  3357. if drill['tool'] is '':
  3358. self.app.inform.emit("[WARNING] Excellon.create_geometry() -> a drill location was skipped "
  3359. "due of not having a tool associated.\n"
  3360. "Check the resulting GCode.")
  3361. log.debug("Excellon.create_geometry() -> a drill location was skipped "
  3362. "due of not having a tool associated")
  3363. continue
  3364. tooldia = self.tools[drill['tool']]['C']
  3365. poly = drill['point'].buffer(tooldia / 2.0, int(int(self.geo_steps_per_circle) / 4))
  3366. self.solid_geometry.append(poly)
  3367. for slot in self.slots:
  3368. slot_tooldia = self.tools[slot['tool']]['C']
  3369. start = slot['start']
  3370. stop = slot['stop']
  3371. lines_string = LineString([start, stop])
  3372. poly = lines_string.buffer(slot_tooldia / 2.0, int(int(self.geo_steps_per_circle) / 4))
  3373. self.solid_geometry.append(poly)
  3374. except Exception as e:
  3375. log.debug("Excellon geometry creation failed due of ERROR: %s" % str(e))
  3376. return "fail"
  3377. # drill_geometry = {}
  3378. # slot_geometry = {}
  3379. #
  3380. # def insertIntoDataStruct(dia, drill_geo, aDict):
  3381. # if not dia in aDict:
  3382. # aDict[dia] = [drill_geo]
  3383. # else:
  3384. # aDict[dia].append(drill_geo)
  3385. #
  3386. # for tool in self.tools:
  3387. # tooldia = self.tools[tool]['C']
  3388. # for drill in self.drills:
  3389. # if drill['tool'] == tool:
  3390. # poly = drill['point'].buffer(tooldia / 2.0)
  3391. # insertIntoDataStruct(tooldia, poly, drill_geometry)
  3392. #
  3393. # for tool in self.tools:
  3394. # slot_tooldia = self.tools[tool]['C']
  3395. # for slot in self.slots:
  3396. # if slot['tool'] == tool:
  3397. # start = slot['start']
  3398. # stop = slot['stop']
  3399. # lines_string = LineString([start, stop])
  3400. # poly = lines_string.buffer(slot_tooldia/2.0, self.geo_steps_per_circle)
  3401. # insertIntoDataStruct(slot_tooldia, poly, drill_geometry)
  3402. #
  3403. # self.solid_geometry = [drill_geometry, slot_geometry]
  3404. def bounds(self):
  3405. """
  3406. Returns coordinates of rectangular bounds
  3407. of Gerber geometry: (xmin, ymin, xmax, ymax).
  3408. """
  3409. # fixed issue of getting bounds only for one level lists of objects
  3410. # now it can get bounds for nested lists of objects
  3411. log.debug("Excellon() -> bounds()")
  3412. if self.solid_geometry is None:
  3413. log.debug("solid_geometry is None")
  3414. return 0, 0, 0, 0
  3415. def bounds_rec(obj):
  3416. if type(obj) is list:
  3417. minx = Inf
  3418. miny = Inf
  3419. maxx = -Inf
  3420. maxy = -Inf
  3421. for k in obj:
  3422. if type(k) is dict:
  3423. for key in k:
  3424. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  3425. minx = min(minx, minx_)
  3426. miny = min(miny, miny_)
  3427. maxx = max(maxx, maxx_)
  3428. maxy = max(maxy, maxy_)
  3429. else:
  3430. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3431. minx = min(minx, minx_)
  3432. miny = min(miny, miny_)
  3433. maxx = max(maxx, maxx_)
  3434. maxy = max(maxy, maxy_)
  3435. return minx, miny, maxx, maxy
  3436. else:
  3437. # it's a Shapely object, return it's bounds
  3438. return obj.bounds
  3439. bounds_coords = bounds_rec(self.solid_geometry)
  3440. return bounds_coords
  3441. def convert_units(self, units):
  3442. """
  3443. This function first convert to the the units found in the Excellon file but it converts tools that
  3444. are not there yet so it has no effect other than it signal that the units are the ones in the file.
  3445. On object creation, in new_object(), true conversion is done because this is done at the end of the
  3446. Excellon file parsing, the tools are inside and self.tools is really converted from the units found
  3447. inside the file to the FlatCAM units.
  3448. Kind of convolute way to make the conversion and it is based on the assumption that the Excellon file
  3449. will have detected the units before the tools are parsed and stored in self.tools
  3450. :param units:
  3451. :type str: IN or MM
  3452. :return:
  3453. """
  3454. factor = Geometry.convert_units(self, units)
  3455. # Tools
  3456. for tname in self.tools:
  3457. self.tools[tname]["C"] *= factor
  3458. self.create_geometry()
  3459. return factor
  3460. def scale(self, xfactor, yfactor=None, point=None):
  3461. """
  3462. Scales geometry on the XY plane in the object by a given factor.
  3463. Tool sizes, feedrates an Z-plane dimensions are untouched.
  3464. :param factor: Number by which to scale the object.
  3465. :type factor: float
  3466. :return: None
  3467. :rtype: NOne
  3468. """
  3469. if yfactor is None:
  3470. yfactor = xfactor
  3471. if point is None:
  3472. px = 0
  3473. py = 0
  3474. else:
  3475. px, py = point
  3476. # Drills
  3477. for drill in self.drills:
  3478. drill['point'] = affinity.scale(drill['point'], xfactor, yfactor, origin=(px, py))
  3479. # Slots
  3480. for slot in self.slots:
  3481. slot['stop'] = affinity.scale(slot['stop'], xfactor, yfactor, origin=(px, py))
  3482. slot['start'] = affinity.scale(slot['start'], xfactor, yfactor, origin=(px, py))
  3483. self.create_geometry()
  3484. def offset(self, vect):
  3485. """
  3486. Offsets geometry on the XY plane in the object by a given vector.
  3487. :param vect: (x, y) offset vector.
  3488. :type vect: tuple
  3489. :return: None
  3490. """
  3491. dx, dy = vect
  3492. # Drills
  3493. for drill in self.drills:
  3494. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  3495. # Slots
  3496. for slot in self.slots:
  3497. slot['stop'] = affinity.translate(slot['stop'], xoff=dx, yoff=dy)
  3498. slot['start'] = affinity.translate(slot['start'],xoff=dx, yoff=dy)
  3499. # Recreate geometry
  3500. self.create_geometry()
  3501. def mirror(self, axis, point):
  3502. """
  3503. :param axis: "X" or "Y" indicates around which axis to mirror.
  3504. :type axis: str
  3505. :param point: [x, y] point belonging to the mirror axis.
  3506. :type point: list
  3507. :return: None
  3508. """
  3509. px, py = point
  3510. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  3511. # Modify data
  3512. # Drills
  3513. for drill in self.drills:
  3514. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  3515. # Slots
  3516. for slot in self.slots:
  3517. slot['stop'] = affinity.scale(slot['stop'], xscale, yscale, origin=(px, py))
  3518. slot['start'] = affinity.scale(slot['start'], xscale, yscale, origin=(px, py))
  3519. # Recreate geometry
  3520. self.create_geometry()
  3521. def skew(self, angle_x=None, angle_y=None, point=None):
  3522. """
  3523. Shear/Skew the geometries of an object by angles along x and y dimensions.
  3524. Tool sizes, feedrates an Z-plane dimensions are untouched.
  3525. Parameters
  3526. ----------
  3527. xs, ys : float, float
  3528. The shear angle(s) for the x and y axes respectively. These can be
  3529. specified in either degrees (default) or radians by setting
  3530. use_radians=True.
  3531. See shapely manual for more information:
  3532. http://toblerity.org/shapely/manual.html#affine-transformations
  3533. """
  3534. if angle_x is None:
  3535. angle_x = 0.0
  3536. if angle_y is None:
  3537. angle_y = 0.0
  3538. if point is None:
  3539. # Drills
  3540. for drill in self.drills:
  3541. drill['point'] = affinity.skew(drill['point'], angle_x, angle_y,
  3542. origin=(0, 0))
  3543. # Slots
  3544. for slot in self.slots:
  3545. slot['stop'] = affinity.skew(slot['stop'], angle_x, angle_y, origin=(0, 0))
  3546. slot['start'] = affinity.skew(slot['start'], angle_x, angle_y, origin=(0, 0))
  3547. else:
  3548. px, py = point
  3549. # Drills
  3550. for drill in self.drills:
  3551. drill['point'] = affinity.skew(drill['point'], angle_x, angle_y,
  3552. origin=(px, py))
  3553. # Slots
  3554. for slot in self.slots:
  3555. slot['stop'] = affinity.skew(slot['stop'], angle_x, angle_y, origin=(px, py))
  3556. slot['start'] = affinity.skew(slot['start'], angle_x, angle_y, origin=(px, py))
  3557. self.create_geometry()
  3558. def rotate(self, angle, point=None):
  3559. """
  3560. Rotate the geometry of an object by an angle around the 'point' coordinates
  3561. :param angle:
  3562. :param point: tuple of coordinates (x, y)
  3563. :return:
  3564. """
  3565. if point is None:
  3566. # Drills
  3567. for drill in self.drills:
  3568. drill['point'] = affinity.rotate(drill['point'], angle, origin='center')
  3569. # Slots
  3570. for slot in self.slots:
  3571. slot['stop'] = affinity.rotate(slot['stop'], angle, origin='center')
  3572. slot['start'] = affinity.rotate(slot['start'], angle, origin='center')
  3573. else:
  3574. px, py = point
  3575. # Drills
  3576. for drill in self.drills:
  3577. drill['point'] = affinity.rotate(drill['point'], angle, origin=(px, py))
  3578. # Slots
  3579. for slot in self.slots:
  3580. slot['stop'] = affinity.rotate(slot['stop'], angle, origin=(px, py))
  3581. slot['start'] = affinity.rotate(slot['start'], angle, origin=(px, py))
  3582. self.create_geometry()
  3583. class AttrDict(dict):
  3584. def __init__(self, *args, **kwargs):
  3585. super(AttrDict, self).__init__(*args, **kwargs)
  3586. self.__dict__ = self
  3587. class CNCjob(Geometry):
  3588. """
  3589. Represents work to be done by a CNC machine.
  3590. *ATTRIBUTES*
  3591. * ``gcode_parsed`` (list): Each is a dictionary:
  3592. ===================== =========================================
  3593. Key Value
  3594. ===================== =========================================
  3595. geom (Shapely.LineString) Tool path (XY plane)
  3596. kind (string) "AB", A is "T" (travel) or
  3597. "C" (cut). B is "F" (fast) or "S" (slow).
  3598. ===================== =========================================
  3599. """
  3600. defaults = {
  3601. "global_zdownrate": None,
  3602. "pp_geometry_name":'default',
  3603. "pp_excellon_name":'default',
  3604. "excellon_optimization_type": "B",
  3605. "steps_per_circle": 64
  3606. }
  3607. def __init__(self,
  3608. units="in", kind="generic", tooldia=0.0,
  3609. z_cut=-0.002, z_move=0.1,
  3610. feedrate=3.0, feedrate_z=3.0, feedrate_rapid=3.0, feedrate_probe=3.0,
  3611. pp_geometry_name='default', pp_excellon_name='default',
  3612. depthpercut=0.1,z_pdepth=-0.02,
  3613. spindlespeed=None, dwell=True, dwelltime=1000,
  3614. toolchangez=0.787402, toolchange_xy=[0.0, 0.0],
  3615. endz=2.0,
  3616. segx=None,
  3617. segy=None,
  3618. steps_per_circle=None):
  3619. # Used when parsing G-code arcs
  3620. if steps_per_circle is None:
  3621. steps_per_circle = int(CNCjob.defaults["steps_per_circle"])
  3622. self.steps_per_circle = int(steps_per_circle)
  3623. Geometry.__init__(self, geo_steps_per_circle=int(steps_per_circle))
  3624. self.kind = kind
  3625. self.units = units
  3626. self.z_cut = z_cut
  3627. self.z_move = z_move
  3628. self.feedrate = feedrate
  3629. self.feedrate_z = feedrate_z
  3630. self.feedrate_rapid = feedrate_rapid
  3631. self.tooldia = tooldia
  3632. self.toolchangez = toolchangez
  3633. self.toolchange_xy = toolchange_xy
  3634. self.toolchange_xy_type = None
  3635. self.endz = endz
  3636. self.depthpercut = depthpercut
  3637. self.unitcode = {"IN": "G20", "MM": "G21"}
  3638. self.feedminutecode = "G94"
  3639. self.absolutecode = "G90"
  3640. self.gcode = ""
  3641. self.gcode_parsed = None
  3642. self.pp_geometry_name = pp_geometry_name
  3643. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  3644. self.pp_excellon_name = pp_excellon_name
  3645. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  3646. # Controls if the move from Z_Toolchange to Z_Move is done fast with G0 or normally with G1
  3647. self.f_plunge = None
  3648. # how much depth the probe can probe before error
  3649. self.z_pdepth = z_pdepth if z_pdepth else None
  3650. # the feedrate(speed) with which the probel travel while probing
  3651. self.feedrate_probe = feedrate_probe if feedrate_probe else None
  3652. self.spindlespeed = spindlespeed
  3653. self.dwell = dwell
  3654. self.dwelltime = dwelltime
  3655. self.segx = float(segx) if segx is not None else 0.0
  3656. self.segy = float(segy) if segy is not None else 0.0
  3657. self.input_geometry_bounds = None
  3658. self.oldx = None
  3659. self.oldy = None
  3660. # Attributes to be included in serialization
  3661. # Always append to it because it carries contents
  3662. # from Geometry.
  3663. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'toolchangez', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  3664. 'tooldia', 'gcode', 'input_geometry_bounds', 'gcode_parsed', 'steps_per_circle',
  3665. 'depthpercut', 'spindlespeed', 'dwell', 'dwelltime']
  3666. @property
  3667. def postdata(self):
  3668. return self.__dict__
  3669. def convert_units(self, units):
  3670. factor = Geometry.convert_units(self, units)
  3671. log.debug("CNCjob.convert_units()")
  3672. self.z_cut = float(self.z_cut) * factor
  3673. self.z_move *= factor
  3674. self.feedrate *= factor
  3675. self.feedrate_z *= factor
  3676. self.feedrate_rapid *= factor
  3677. self.tooldia *= factor
  3678. self.toolchangez *= factor
  3679. self.endz *= factor
  3680. self.depthpercut = float(self.depthpercut) * factor
  3681. return factor
  3682. def doformat(self, fun, **kwargs):
  3683. return self.doformat2(fun, **kwargs) + "\n"
  3684. def doformat2(self, fun, **kwargs):
  3685. attributes = AttrDict()
  3686. attributes.update(self.postdata)
  3687. attributes.update(kwargs)
  3688. try:
  3689. returnvalue = fun(attributes)
  3690. return returnvalue
  3691. except Exception as e:
  3692. self.app.log.error('Exception occurred within a postprocessor: ' + traceback.format_exc())
  3693. return ''
  3694. def optimized_travelling_salesman(self, points, start=None):
  3695. """
  3696. As solving the problem in the brute force way is too slow,
  3697. this function implements a simple heuristic: always
  3698. go to the nearest city.
  3699. Even if this algorithm is extremely simple, it works pretty well
  3700. giving a solution only about 25% longer than the optimal one (cit. Wikipedia),
  3701. and runs very fast in O(N^2) time complexity.
  3702. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  3703. [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], [2, 0], [2, 1], [2, 2],
  3704. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  3705. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  3706. [[0, 0], [6, 0], [10, 0]]
  3707. """
  3708. if start is None:
  3709. start = points[0]
  3710. must_visit = points
  3711. path = [start]
  3712. # must_visit.remove(start)
  3713. while must_visit:
  3714. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  3715. path.append(nearest)
  3716. must_visit.remove(nearest)
  3717. return path
  3718. def generate_from_excellon_by_tool(self, exobj, tools="all", drillz = 3.0,
  3719. toolchange=False, toolchangez=0.1, toolchangexy='',
  3720. endz=2.0, startz=None,
  3721. excellon_optimization_type='B'):
  3722. """
  3723. Creates gcode for this object from an Excellon object
  3724. for the specified tools.
  3725. :param exobj: Excellon object to process
  3726. :type exobj: Excellon
  3727. :param tools: Comma separated tool names
  3728. :type: tools: str
  3729. :param drillz: drill Z depth
  3730. :type drillz: float
  3731. :param toolchange: Use tool change sequence between tools.
  3732. :type toolchange: bool
  3733. :param toolchangez: Height at which to perform the tool change.
  3734. :type toolchangez: float
  3735. :param toolchangexy: Toolchange X,Y position
  3736. :type toolchangexy: String containing 2 floats separated by comma
  3737. :param startz: Z position just before starting the job
  3738. :type startz: float
  3739. :param endz: final Z position to move to at the end of the CNC job
  3740. :type endz: float
  3741. :param excellon_optimization_type: Single character that defines which drill re-ordering optimisation algorithm
  3742. is to be used: 'M' for meta-heuristic and 'B' for basic
  3743. :type excellon_optimization_type: string
  3744. :return: None
  3745. :rtype: None
  3746. """
  3747. if drillz > 0:
  3748. self.app.inform.emit("[WARNING] The Cut Z parameter has positive value. "
  3749. "It is the depth value to drill into material.\n"
  3750. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  3751. "therefore the app will convert the value to negative. "
  3752. "Check the resulting CNC code (Gcode etc).")
  3753. self.z_cut = -drillz
  3754. elif drillz == 0:
  3755. self.app.inform.emit("[WARNING] The Cut Z parameter is zero. "
  3756. "There will be no cut, skipping %s file" % exobj.options['name'])
  3757. return 'fail'
  3758. else:
  3759. self.z_cut = drillz
  3760. self.toolchangez = toolchangez
  3761. try:
  3762. if toolchangexy == '':
  3763. self.toolchange_xy = None
  3764. else:
  3765. self.toolchange_xy = [float(eval(a)) for a in toolchangexy.split(",")]
  3766. if len(self.toolchange_xy) < 2:
  3767. self.app.inform.emit("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  3768. "in the format (x, y) \nbut now there is only one value, not two. ")
  3769. return 'fail'
  3770. except Exception as e:
  3771. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  3772. pass
  3773. self.startz = startz
  3774. self.endz = endz
  3775. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  3776. p = self.pp_excellon
  3777. log.debug("Creating CNC Job from Excellon...")
  3778. # Tools
  3779. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  3780. # so we actually are sorting the tools by diameter
  3781. #sorted_tools = sorted(exobj.tools.items(), key=lambda t1: t1['C'])
  3782. sort = []
  3783. for k, v in list(exobj.tools.items()):
  3784. sort.append((k, v.get('C')))
  3785. sorted_tools = sorted(sort,key=lambda t1: t1[1])
  3786. if tools == "all":
  3787. tools = [i[0] for i in sorted_tools] # we get a array of ordered tools
  3788. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  3789. else:
  3790. selected_tools = [x.strip() for x in tools.split(",")] # we strip spaces and also separate the tools by ','
  3791. selected_tools = [t1 for t1 in selected_tools if t1 in selected_tools]
  3792. # Create a sorted list of selected tools from the sorted_tools list
  3793. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  3794. log.debug("Tools selected and sorted are: %s" % str(tools))
  3795. # Points (Group by tool)
  3796. points = {}
  3797. for drill in exobj.drills:
  3798. if drill['tool'] in tools:
  3799. try:
  3800. points[drill['tool']].append(drill['point'])
  3801. except KeyError:
  3802. points[drill['tool']] = [drill['point']]
  3803. #log.debug("Found %d drills." % len(points))
  3804. self.gcode = []
  3805. self.f_plunge = self.app.defaults["excellon_f_plunge"]
  3806. # Initialization
  3807. gcode = self.doformat(p.start_code)
  3808. gcode += self.doformat(p.feedrate_code)
  3809. if toolchange is False:
  3810. if self.toolchange_xy is not None:
  3811. gcode += self.doformat(p.lift_code, x=self.toolchange_xy[0], y=self.toolchange_xy[1])
  3812. gcode += self.doformat(p.startz_code, x=self.toolchange_xy[0], y=self.toolchange_xy[1])
  3813. else:
  3814. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  3815. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  3816. # Distance callback
  3817. class CreateDistanceCallback(object):
  3818. """Create callback to calculate distances between points."""
  3819. def __init__(self):
  3820. """Initialize distance array."""
  3821. locations = create_data_array()
  3822. size = len(locations)
  3823. self.matrix = {}
  3824. for from_node in range(size):
  3825. self.matrix[from_node] = {}
  3826. for to_node in range(size):
  3827. if from_node == to_node:
  3828. self.matrix[from_node][to_node] = 0
  3829. else:
  3830. x1 = locations[from_node][0]
  3831. y1 = locations[from_node][1]
  3832. x2 = locations[to_node][0]
  3833. y2 = locations[to_node][1]
  3834. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  3835. def Distance(self, from_node, to_node):
  3836. return int(self.matrix[from_node][to_node])
  3837. # Create the data.
  3838. def create_data_array():
  3839. locations = []
  3840. for point in points[tool]:
  3841. locations.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  3842. return locations
  3843. if self.toolchange_xy is not None:
  3844. self.oldx = self.toolchange_xy[0]
  3845. self.oldy = self.toolchange_xy[1]
  3846. else:
  3847. self.oldx = 0.0
  3848. self.oldy = 0.0
  3849. measured_distance = 0
  3850. current_platform = platform.architecture()[0]
  3851. if current_platform == '64bit':
  3852. if excellon_optimization_type == 'M':
  3853. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  3854. if exobj.drills:
  3855. for tool in tools:
  3856. self.tool=tool
  3857. self.postdata['toolC']=exobj.tools[tool]["C"]
  3858. ################################################
  3859. # Create the data.
  3860. node_list = []
  3861. locations = create_data_array()
  3862. tsp_size = len(locations)
  3863. num_routes = 1 # The number of routes, which is 1 in the TSP.
  3864. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  3865. depot = 0
  3866. # Create routing model.
  3867. if tsp_size > 0:
  3868. routing = pywrapcp.RoutingModel(tsp_size, num_routes, depot)
  3869. search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
  3870. search_parameters.local_search_metaheuristic = (
  3871. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  3872. # Set search time limit in milliseconds.
  3873. if float(self.app.defaults["excellon_search_time"]) != 0:
  3874. search_parameters.time_limit_ms = int(
  3875. float(self.app.defaults["excellon_search_time"]) * 1000)
  3876. else:
  3877. search_parameters.time_limit_ms = 3000
  3878. # Callback to the distance function. The callback takes two
  3879. # arguments (the from and to node indices) and returns the distance between them.
  3880. dist_between_locations = CreateDistanceCallback()
  3881. dist_callback = dist_between_locations.Distance
  3882. routing.SetArcCostEvaluatorOfAllVehicles(dist_callback)
  3883. # Solve, returns a solution if any.
  3884. assignment = routing.SolveWithParameters(search_parameters)
  3885. if assignment:
  3886. # Solution cost.
  3887. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  3888. # Inspect solution.
  3889. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  3890. route_number = 0
  3891. node = routing.Start(route_number)
  3892. start_node = node
  3893. while not routing.IsEnd(node):
  3894. node_list.append(node)
  3895. node = assignment.Value(routing.NextVar(node))
  3896. else:
  3897. log.warning('No solution found.')
  3898. else:
  3899. log.warning('Specify an instance greater than 0.')
  3900. ################################################
  3901. # Only if tool has points.
  3902. if tool in points:
  3903. # Tool change sequence (optional)
  3904. if toolchange:
  3905. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  3906. gcode += self.doformat(p.spindle_code) # Spindle start
  3907. if self.dwell is True:
  3908. gcode += self.doformat(p.dwell_code) # Dwell time
  3909. else:
  3910. gcode += self.doformat(p.spindle_code)
  3911. if self.dwell is True:
  3912. gcode += self.doformat(p.dwell_code) # Dwell time
  3913. # Drillling!
  3914. for k in node_list:
  3915. locx = locations[k][0]
  3916. locy = locations[k][1]
  3917. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3918. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3919. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3920. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3921. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3922. self.oldx = locx
  3923. self.oldy = locy
  3924. else:
  3925. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3926. "The loaded Excellon file has no drills ...")
  3927. self.app.inform.emit('[ERROR_NOTCL]The loaded Excellon file has no drills ...')
  3928. return 'fail'
  3929. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  3930. elif excellon_optimization_type == 'B':
  3931. log.debug("Using OR-Tools Basic drill path optimization.")
  3932. if exobj.drills:
  3933. for tool in tools:
  3934. self.tool=tool
  3935. self.postdata['toolC']=exobj.tools[tool]["C"]
  3936. ################################################
  3937. node_list = []
  3938. locations = create_data_array()
  3939. tsp_size = len(locations)
  3940. num_routes = 1 # The number of routes, which is 1 in the TSP.
  3941. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  3942. depot = 0
  3943. # Create routing model.
  3944. if tsp_size > 0:
  3945. routing = pywrapcp.RoutingModel(tsp_size, num_routes, depot)
  3946. search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
  3947. # Callback to the distance function. The callback takes two
  3948. # arguments (the from and to node indices) and returns the distance between them.
  3949. dist_between_locations = CreateDistanceCallback()
  3950. dist_callback = dist_between_locations.Distance
  3951. routing.SetArcCostEvaluatorOfAllVehicles(dist_callback)
  3952. # Solve, returns a solution if any.
  3953. assignment = routing.SolveWithParameters(search_parameters)
  3954. if assignment:
  3955. # Solution cost.
  3956. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  3957. # Inspect solution.
  3958. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  3959. route_number = 0
  3960. node = routing.Start(route_number)
  3961. start_node = node
  3962. while not routing.IsEnd(node):
  3963. node_list.append(node)
  3964. node = assignment.Value(routing.NextVar(node))
  3965. else:
  3966. log.warning('No solution found.')
  3967. else:
  3968. log.warning('Specify an instance greater than 0.')
  3969. ################################################
  3970. # Only if tool has points.
  3971. if tool in points:
  3972. # Tool change sequence (optional)
  3973. if toolchange:
  3974. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  3975. gcode += self.doformat(p.spindle_code) # Spindle start)
  3976. if self.dwell is True:
  3977. gcode += self.doformat(p.dwell_code) # Dwell time
  3978. else:
  3979. gcode += self.doformat(p.spindle_code)
  3980. if self.dwell is True:
  3981. gcode += self.doformat(p.dwell_code) # Dwell time
  3982. # Drillling!
  3983. for k in node_list:
  3984. locx = locations[k][0]
  3985. locy = locations[k][1]
  3986. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3987. gcode += self.doformat(p.down_code, x=locx, y=locy)
  3988. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3989. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3990. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3991. self.oldx = locx
  3992. self.oldy = locy
  3993. else:
  3994. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3995. "The loaded Excellon file has no drills ...")
  3996. self.app.inform.emit('[ERROR_NOTCL]The loaded Excellon file has no drills ...')
  3997. return 'fail'
  3998. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  3999. else:
  4000. self.app.inform.emit("[ERROR_NOTCL] Wrong optimization type selected.")
  4001. return 'fail'
  4002. else:
  4003. log.debug("Using Travelling Salesman drill path optimization.")
  4004. for tool in tools:
  4005. if exobj.drills:
  4006. self.tool = tool
  4007. self.postdata['toolC'] = exobj.tools[tool]["C"]
  4008. # Only if tool has points.
  4009. if tool in points:
  4010. # Tool change sequence (optional)
  4011. if toolchange:
  4012. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  4013. gcode += self.doformat(p.spindle_code) # Spindle start)
  4014. if self.dwell is True:
  4015. gcode += self.doformat(p.dwell_code) # Dwell time
  4016. else:
  4017. gcode += self.doformat(p.spindle_code)
  4018. if self.dwell is True:
  4019. gcode += self.doformat(p.dwell_code) # Dwell time
  4020. # Drillling!
  4021. altPoints = []
  4022. for point in points[tool]:
  4023. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  4024. for point in self.optimized_travelling_salesman(altPoints):
  4025. gcode += self.doformat(p.rapid_code, x=point[0], y=point[1])
  4026. gcode += self.doformat(p.down_code, x=point[0], y=point[1])
  4027. gcode += self.doformat(p.up_to_zero_code, x=point[0], y=point[1])
  4028. gcode += self.doformat(p.lift_code, x=point[0], y=point[1])
  4029. measured_distance += abs(distance_euclidian(point[0], point[1], self.oldx, self.oldy))
  4030. self.oldx = point[0]
  4031. self.oldy = point[1]
  4032. else:
  4033. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  4034. "The loaded Excellon file has no drills ...")
  4035. self.app.inform.emit('[ERROR_NOTCL]The loaded Excellon file has no drills ...')
  4036. return 'fail'
  4037. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  4038. gcode += self.doformat(p.spindle_stop_code) # Spindle stop
  4039. gcode += self.doformat(p.end_code, x=0, y=0)
  4040. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  4041. log.debug("The total travel distance including travel to end position is: %s" %
  4042. str(measured_distance) + '\n')
  4043. self.gcode = gcode
  4044. return 'OK'
  4045. def generate_from_multitool_geometry(self, geometry, append=True,
  4046. tooldia=None, offset=0.0, tolerance=0, z_cut=1.0, z_move=2.0,
  4047. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  4048. spindlespeed=None, dwell=False, dwelltime=1.0,
  4049. multidepth=False, depthpercut=None,
  4050. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0", extracut=False,
  4051. startz=None, endz=2.0, pp_geometry_name=None, tool_no=1):
  4052. """
  4053. Algorithm to generate from multitool Geometry.
  4054. Algorithm description:
  4055. ----------------------
  4056. Uses RTree to find the nearest path to follow.
  4057. :param geometry:
  4058. :param append:
  4059. :param tooldia:
  4060. :param tolerance:
  4061. :param multidepth: If True, use multiple passes to reach
  4062. the desired depth.
  4063. :param depthpercut: Maximum depth in each pass.
  4064. :param extracut: Adds (or not) an extra cut at the end of each path
  4065. overlapping the first point in path to ensure complete copper removal
  4066. :return: None
  4067. """
  4068. log.debug("Generate_from_multitool_geometry()")
  4069. temp_solid_geometry = []
  4070. if offset != 0.0:
  4071. for it in geometry:
  4072. # if the geometry is a closed shape then create a Polygon out of it
  4073. if isinstance(it, LineString):
  4074. c = it.coords
  4075. if c[0] == c[-1]:
  4076. it = Polygon(it)
  4077. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  4078. else:
  4079. temp_solid_geometry = geometry
  4080. ## Flatten the geometry. Only linear elements (no polygons) remain.
  4081. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  4082. log.debug("%d paths" % len(flat_geometry))
  4083. self.tooldia = tooldia
  4084. self.z_cut = z_cut
  4085. self.z_move = z_move
  4086. self.feedrate = feedrate
  4087. self.feedrate_z = feedrate_z
  4088. self.feedrate_rapid = feedrate_rapid
  4089. self.spindlespeed = spindlespeed
  4090. self.dwell = dwell
  4091. self.dwelltime = dwelltime
  4092. self.startz = startz
  4093. self.endz = endz
  4094. self.depthpercut = depthpercut
  4095. self.multidepth = multidepth
  4096. self.toolchangez = toolchangez
  4097. try:
  4098. if toolchangexy == '':
  4099. self.toolchange_xy = None
  4100. else:
  4101. self.toolchange_xy = [float(eval(a)) for a in toolchangexy.split(",")]
  4102. if len(self.toolchange_xy) < 2:
  4103. self.app.inform.emit("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  4104. "in the format (x, y) \nbut now there is only one value, not two. ")
  4105. return 'fail'
  4106. except Exception as e:
  4107. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  4108. pass
  4109. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4110. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4111. if self.z_cut > 0:
  4112. self.app.inform.emit("[WARNING] The Cut Z parameter has positive value. "
  4113. "It is the depth value to cut into material.\n"
  4114. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4115. "therefore the app will convert the value to negative."
  4116. "Check the resulting CNC code (Gcode etc).")
  4117. self.z_cut = -self.z_cut
  4118. elif self.z_cut == 0:
  4119. self.app.inform.emit("[WARNING] The Cut Z parameter is zero. "
  4120. "There will be no cut, skipping %s file" % self.options['name'])
  4121. ## Index first and last points in paths
  4122. # What points to index.
  4123. def get_pts(o):
  4124. return [o.coords[0], o.coords[-1]]
  4125. # Create the indexed storage.
  4126. storage = FlatCAMRTreeStorage()
  4127. storage.get_points = get_pts
  4128. # Store the geometry
  4129. log.debug("Indexing geometry before generating G-Code...")
  4130. for shape in flat_geometry:
  4131. if shape is not None: # TODO: This shouldn't have happened.
  4132. storage.insert(shape)
  4133. # self.input_geometry_bounds = geometry.bounds()
  4134. if not append:
  4135. self.gcode = ""
  4136. # tell postprocessor the number of tool (for toolchange)
  4137. self.tool = tool_no
  4138. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  4139. # given under the name 'toolC'
  4140. self.postdata['toolC'] = self.tooldia
  4141. # Initial G-Code
  4142. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  4143. p = self.pp_geometry
  4144. self.gcode = self.doformat(p.start_code)
  4145. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4146. if toolchange is False:
  4147. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  4148. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  4149. if toolchange:
  4150. # if "line_xyz" in self.pp_geometry_name:
  4151. # self.gcode += self.doformat(p.toolchange_code, x=self.toolchange_xy[0], y=self.toolchange_xy[1])
  4152. # else:
  4153. # self.gcode += self.doformat(p.toolchange_code)
  4154. self.gcode += self.doformat(p.toolchange_code)
  4155. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4156. if self.dwell is True:
  4157. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4158. else:
  4159. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4160. if self.dwell is True:
  4161. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4162. ## Iterate over geometry paths getting the nearest each time.
  4163. log.debug("Starting G-Code...")
  4164. path_count = 0
  4165. current_pt = (0, 0)
  4166. pt, geo = storage.nearest(current_pt)
  4167. try:
  4168. while True:
  4169. path_count += 1
  4170. # Remove before modifying, otherwise deletion will fail.
  4171. storage.remove(geo)
  4172. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4173. # then reverse coordinates.
  4174. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4175. geo.coords = list(geo.coords)[::-1]
  4176. #---------- Single depth/pass --------
  4177. if not multidepth:
  4178. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance)
  4179. #--------- Multi-pass ---------
  4180. else:
  4181. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  4182. postproc=p, current_point=current_pt)
  4183. current_pt = geo.coords[-1]
  4184. pt, geo = storage.nearest(current_pt) # Next
  4185. except StopIteration: # Nothing found in storage.
  4186. pass
  4187. log.debug("Finishing G-Code... %s paths traced." % path_count)
  4188. # Finish
  4189. self.gcode += self.doformat(p.spindle_stop_code)
  4190. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4191. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4192. return self.gcode
  4193. def generate_from_geometry_2(self, geometry, append=True,
  4194. tooldia=None, offset=0.0, tolerance=0,
  4195. z_cut=1.0, z_move=2.0,
  4196. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  4197. spindlespeed=None, dwell=False, dwelltime=1.0,
  4198. multidepth=False, depthpercut=None,
  4199. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0",
  4200. extracut=False, startz=None, endz=2.0,
  4201. pp_geometry_name=None, tool_no=1):
  4202. """
  4203. Second algorithm to generate from Geometry.
  4204. Algorithm description:
  4205. ----------------------
  4206. Uses RTree to find the nearest path to follow.
  4207. :param geometry:
  4208. :param append:
  4209. :param tooldia:
  4210. :param tolerance:
  4211. :param multidepth: If True, use multiple passes to reach
  4212. the desired depth.
  4213. :param depthpercut: Maximum depth in each pass.
  4214. :param extracut: Adds (or not) an extra cut at the end of each path
  4215. overlapping the first point in path to ensure complete copper removal
  4216. :return: None
  4217. """
  4218. if not isinstance(geometry, Geometry):
  4219. self.app.inform.emit("[ERROR]Expected a Geometry, got %s" % type(geometry))
  4220. return 'fail'
  4221. log.debug("Generate_from_geometry_2()")
  4222. # if solid_geometry is empty raise an exception
  4223. if not geometry.solid_geometry:
  4224. self.app.inform.emit("[ERROR_NOTCL]Trying to generate a CNC Job "
  4225. "from a Geometry object without solid_geometry.")
  4226. temp_solid_geometry = []
  4227. if offset != 0.0:
  4228. for it in geometry.solid_geometry:
  4229. # if the geometry is a closed shape then create a Polygon out of it
  4230. if isinstance(it, LineString):
  4231. c = it.coords
  4232. if c[0] == c[-1]:
  4233. it = Polygon(it)
  4234. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  4235. else:
  4236. temp_solid_geometry = geometry.solid_geometry
  4237. ## Flatten the geometry. Only linear elements (no polygons) remain.
  4238. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  4239. log.debug("%d paths" % len(flat_geometry))
  4240. self.tooldia = tooldia
  4241. self.z_cut = z_cut
  4242. self.z_move = z_move
  4243. self.feedrate = feedrate
  4244. self.feedrate_z = feedrate_z
  4245. self.feedrate_rapid = feedrate_rapid
  4246. self.spindlespeed = spindlespeed
  4247. self.dwell = dwell
  4248. self.dwelltime = dwelltime
  4249. self.startz = startz
  4250. self.endz = endz
  4251. self.depthpercut = depthpercut
  4252. self.multidepth = multidepth
  4253. self.toolchangez = toolchangez
  4254. try:
  4255. if toolchangexy == '':
  4256. self.toolchange_xy = None
  4257. else:
  4258. self.toolchange_xy = [float(eval(a)) for a in toolchangexy.split(",")]
  4259. if len(self.toolchange_xy) < 2:
  4260. self.app.inform.emit("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  4261. "in the format (x, y) \nbut now there is only one value, not two. ")
  4262. return 'fail'
  4263. except Exception as e:
  4264. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  4265. pass
  4266. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4267. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4268. if self.z_cut > 0:
  4269. self.app.inform.emit("[WARNING] The Cut Z parameter has positive value. "
  4270. "It is the depth value to cut into material.\n"
  4271. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4272. "therefore the app will convert the value to negative."
  4273. "Check the resulting CNC code (Gcode etc).")
  4274. self.z_cut = -self.z_cut
  4275. elif self.z_cut == 0:
  4276. self.app.inform.emit("[WARNING] The Cut Z parameter is zero. "
  4277. "There will be no cut, skipping %s file" % geometry.options['name'])
  4278. ## Index first and last points in paths
  4279. # What points to index.
  4280. def get_pts(o):
  4281. return [o.coords[0], o.coords[-1]]
  4282. # Create the indexed storage.
  4283. storage = FlatCAMRTreeStorage()
  4284. storage.get_points = get_pts
  4285. # Store the geometry
  4286. log.debug("Indexing geometry before generating G-Code...")
  4287. for shape in flat_geometry:
  4288. if shape is not None: # TODO: This shouldn't have happened.
  4289. storage.insert(shape)
  4290. # self.input_geometry_bounds = geometry.bounds()
  4291. if not append:
  4292. self.gcode = ""
  4293. # tell postprocessor the number of tool (for toolchange)
  4294. self.tool = tool_no
  4295. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  4296. # given under the name 'toolC'
  4297. self.postdata['toolC'] = self.tooldia
  4298. # Initial G-Code
  4299. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  4300. p = self.pp_geometry
  4301. self.oldx = 0.0
  4302. self.oldy = 0.0
  4303. self.gcode = self.doformat(p.start_code)
  4304. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4305. if toolchange is False:
  4306. self.gcode += self.doformat(p.lift_code, x=self.oldx , y=self.oldy ) # Move (up) to travel height
  4307. self.gcode += self.doformat(p.startz_code, x=self.oldx , y=self.oldy )
  4308. if toolchange:
  4309. # if "line_xyz" in self.pp_geometry_name:
  4310. # self.gcode += self.doformat(p.toolchange_code, x=self.toolchange_xy[0], y=self.toolchange_xy[1])
  4311. # else:
  4312. # self.gcode += self.doformat(p.toolchange_code)
  4313. self.gcode += self.doformat(p.toolchange_code)
  4314. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4315. if self.dwell is True:
  4316. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4317. else:
  4318. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4319. if self.dwell is True:
  4320. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4321. ## Iterate over geometry paths getting the nearest each time.
  4322. log.debug("Starting G-Code...")
  4323. path_count = 0
  4324. current_pt = (0, 0)
  4325. pt, geo = storage.nearest(current_pt)
  4326. try:
  4327. while True:
  4328. path_count += 1
  4329. # Remove before modifying, otherwise deletion will fail.
  4330. storage.remove(geo)
  4331. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4332. # then reverse coordinates.
  4333. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4334. geo.coords = list(geo.coords)[::-1]
  4335. #---------- Single depth/pass --------
  4336. if not multidepth:
  4337. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance)
  4338. #--------- Multi-pass ---------
  4339. else:
  4340. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  4341. postproc=p, current_point=current_pt)
  4342. current_pt = geo.coords[-1]
  4343. pt, geo = storage.nearest(current_pt) # Next
  4344. except StopIteration: # Nothing found in storage.
  4345. pass
  4346. log.debug("Finishing G-Code... %s paths traced." % path_count)
  4347. # Finish
  4348. self.gcode += self.doformat(p.spindle_stop_code)
  4349. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4350. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4351. return self.gcode
  4352. def create_gcode_single_pass(self, geometry, extracut, tolerance):
  4353. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  4354. gcode_single_pass = ''
  4355. if type(geometry) == LineString or type(geometry) == LinearRing:
  4356. if extracut is False:
  4357. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance, )
  4358. else:
  4359. if geometry.is_ring:
  4360. gcode_single_pass = self.linear2gcode_extra(geometry, tolerance=tolerance)
  4361. else:
  4362. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance)
  4363. elif type(geometry) == Point:
  4364. gcode_single_pass = self.point2gcode(geometry)
  4365. else:
  4366. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  4367. return
  4368. return gcode_single_pass
  4369. def create_gcode_multi_pass(self, geometry, extracut, tolerance, postproc, current_point):
  4370. gcode_multi_pass = ''
  4371. if isinstance(self.z_cut, Decimal):
  4372. z_cut = self.z_cut
  4373. else:
  4374. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  4375. if self.depthpercut is None:
  4376. self.depthpercut = z_cut
  4377. elif not isinstance(self.depthpercut, Decimal):
  4378. self.depthpercut = Decimal(self.depthpercut).quantize(Decimal('0.000000001'))
  4379. depth = 0
  4380. reverse = False
  4381. while depth > z_cut:
  4382. # Increase depth. Limit to z_cut.
  4383. depth -= self.depthpercut
  4384. if depth < z_cut:
  4385. depth = z_cut
  4386. # Cut at specific depth and do not lift the tool.
  4387. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  4388. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  4389. # is inconsequential.
  4390. if type(geometry) == LineString or type(geometry) == LinearRing:
  4391. if extracut is False:
  4392. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False)
  4393. else:
  4394. if geometry.is_ring:
  4395. gcode_multi_pass += self.linear2gcode_extra(geometry, tolerance=tolerance, z_cut=depth, up=False)
  4396. else:
  4397. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False)
  4398. # Ignore multi-pass for points.
  4399. elif type(geometry) == Point:
  4400. gcode_multi_pass += self.point2gcode(geometry)
  4401. break # Ignoring ...
  4402. else:
  4403. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  4404. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  4405. if type(geometry) == LineString:
  4406. geometry.coords = list(geometry.coords)[::-1]
  4407. reverse = True
  4408. # If geometry is reversed, revert.
  4409. if reverse:
  4410. if type(geometry) == LineString:
  4411. geometry.coords = list(geometry.coords)[::-1]
  4412. # Lift the tool
  4413. gcode_multi_pass += self.doformat(postproc.lift_code, x=current_point[0], y=current_point[1])
  4414. return gcode_multi_pass
  4415. def codes_split(self, gline):
  4416. """
  4417. Parses a line of G-Code such as "G01 X1234 Y987" into
  4418. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  4419. :param gline: G-Code line string
  4420. :return: Dictionary with parsed line.
  4421. """
  4422. command = {}
  4423. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4424. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  4425. if match_z:
  4426. command['G'] = 0
  4427. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  4428. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  4429. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  4430. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  4431. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  4432. if match_pa:
  4433. command['G'] = 0
  4434. command['X'] = float(match_pa.group(1).replace(" ", ""))
  4435. command['Y'] = float(match_pa.group(2).replace(" ", ""))
  4436. match_pen = re.search(r"^(P[U|D])", gline)
  4437. if match_pen:
  4438. if match_pen.group(1) == 'PU':
  4439. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  4440. # therefore the move is of kind T (travel)
  4441. command['Z'] = 1
  4442. else:
  4443. command['Z'] = 0
  4444. elif 'grbl_laser' in self.pp_excellon_name or 'grbl_laser' in self.pp_geometry_name:
  4445. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  4446. if match_lsr:
  4447. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  4448. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  4449. match_lsr_pos = re.search(r"^(M0[3|5])", gline)
  4450. if match_lsr_pos:
  4451. if match_lsr_pos.group(1) == 'M05':
  4452. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  4453. # therefore the move is of kind T (travel)
  4454. command['Z'] = 1
  4455. else:
  4456. command['Z'] = 0
  4457. else:
  4458. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  4459. while match:
  4460. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  4461. gline = gline[match.end():]
  4462. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  4463. return command
  4464. def gcode_parse(self):
  4465. """
  4466. G-Code parser (from self.gcode). Generates dictionary with
  4467. single-segment LineString's and "kind" indicating cut or travel,
  4468. fast or feedrate speed.
  4469. """
  4470. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  4471. # Results go here
  4472. geometry = []
  4473. # Last known instruction
  4474. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  4475. # Current path: temporary storage until tool is
  4476. # lifted or lowered.
  4477. if self.toolchange_xy_type == "excellon":
  4478. if self.app.defaults["excellon_toolchangexy"] == '':
  4479. pos_xy = [0, 0]
  4480. else:
  4481. pos_xy = [float(eval(a)) for a in self.app.defaults["excellon_toolchangexy"].split(",")]
  4482. else:
  4483. if self.app.defaults["geometry_toolchangexy"] == '':
  4484. pos_xy = [0, 0]
  4485. else:
  4486. pos_xy = [float(eval(a)) for a in self.app.defaults["geometry_toolchangexy"].split(",")]
  4487. path = [pos_xy]
  4488. # path = [(0, 0)]
  4489. # Process every instruction
  4490. for line in StringIO(self.gcode):
  4491. if '%MO' in line or '%' in line:
  4492. return "fail"
  4493. gobj = self.codes_split(line)
  4494. ## Units
  4495. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  4496. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  4497. continue
  4498. ## Changing height
  4499. if 'Z' in gobj:
  4500. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4501. pass
  4502. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  4503. pass
  4504. elif 'grbl_laser' in self.pp_excellon_name or 'grbl_laser' in self.pp_geometry_name:
  4505. pass
  4506. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  4507. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  4508. pass
  4509. else:
  4510. log.warning("Non-orthogonal motion: From %s" % str(current))
  4511. log.warning(" To: %s" % str(gobj))
  4512. current['Z'] = gobj['Z']
  4513. # Store the path into geometry and reset path
  4514. if len(path) > 1:
  4515. geometry.append({"geom": LineString(path),
  4516. "kind": kind})
  4517. path = [path[-1]] # Start with the last point of last path.
  4518. if 'G' in gobj:
  4519. current['G'] = int(gobj['G'])
  4520. if 'X' in gobj or 'Y' in gobj:
  4521. # TODO: I think there is a problem here, current['X] (and the rest of current[...] are not initialized
  4522. if 'X' in gobj:
  4523. x = gobj['X']
  4524. # current['X'] = x
  4525. else:
  4526. x = current['X']
  4527. if 'Y' in gobj:
  4528. y = gobj['Y']
  4529. else:
  4530. y = current['Y']
  4531. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  4532. if current['Z'] > 0:
  4533. kind[0] = 'T'
  4534. if current['G'] > 0:
  4535. kind[1] = 'S'
  4536. if current['G'] in [0, 1]: # line
  4537. path.append((x, y))
  4538. arcdir = [None, None, "cw", "ccw"]
  4539. if current['G'] in [2, 3]: # arc
  4540. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  4541. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  4542. start = arctan2(-gobj['J'], -gobj['I'])
  4543. stop = arctan2(-center[1] + y, -center[0] + x)
  4544. path += arc(center, radius, start, stop,
  4545. arcdir[current['G']],
  4546. int(self.steps_per_circle / 4))
  4547. # Update current instruction
  4548. for code in gobj:
  4549. current[code] = gobj[code]
  4550. # There might not be a change in height at the
  4551. # end, therefore, see here too if there is
  4552. # a final path.
  4553. if len(path) > 1:
  4554. geometry.append({"geom": LineString(path),
  4555. "kind": kind})
  4556. self.gcode_parsed = geometry
  4557. return geometry
  4558. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  4559. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  4560. # alpha={"T": 0.3, "C": 1.0}):
  4561. # """
  4562. # Creates a Matplotlib figure with a plot of the
  4563. # G-code job.
  4564. # """
  4565. # if tooldia is None:
  4566. # tooldia = self.tooldia
  4567. #
  4568. # fig = Figure(dpi=dpi)
  4569. # ax = fig.add_subplot(111)
  4570. # ax.set_aspect(1)
  4571. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  4572. # ax.set_xlim(xmin-margin, xmax+margin)
  4573. # ax.set_ylim(ymin-margin, ymax+margin)
  4574. #
  4575. # if tooldia == 0:
  4576. # for geo in self.gcode_parsed:
  4577. # linespec = '--'
  4578. # linecolor = color[geo['kind'][0]][1]
  4579. # if geo['kind'][0] == 'C':
  4580. # linespec = 'k-'
  4581. # x, y = geo['geom'].coords.xy
  4582. # ax.plot(x, y, linespec, color=linecolor)
  4583. # else:
  4584. # for geo in self.gcode_parsed:
  4585. # poly = geo['geom'].buffer(tooldia/2.0)
  4586. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  4587. # edgecolor=color[geo['kind'][0]][1],
  4588. # alpha=alpha[geo['kind'][0]], zorder=2)
  4589. # ax.add_patch(patch)
  4590. #
  4591. # return fig
  4592. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  4593. color={"T": ["#F0E24D4C", "#B5AB3A4C"], "C": ["#5E6CFFFF", "#4650BDFF"]},
  4594. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  4595. """
  4596. Plots the G-code job onto the given axes.
  4597. :param tooldia: Tool diameter.
  4598. :param dpi: Not used!
  4599. :param margin: Not used!
  4600. :param color: Color specification.
  4601. :param alpha: Transparency specification.
  4602. :param tool_tolerance: Tolerance when drawing the toolshape.
  4603. :return: None
  4604. """
  4605. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  4606. path_num = 0
  4607. if tooldia is None:
  4608. tooldia = self.tooldia
  4609. if tooldia == 0:
  4610. for geo in gcode_parsed:
  4611. if kind == 'all':
  4612. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  4613. elif kind == 'travel':
  4614. if geo['kind'][0] == 'T':
  4615. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  4616. elif kind == 'cut':
  4617. if geo['kind'][0] == 'C':
  4618. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  4619. else:
  4620. text = []
  4621. pos = []
  4622. for geo in gcode_parsed:
  4623. path_num += 1
  4624. text.append(str(path_num))
  4625. pos.append(geo['geom'].coords[0])
  4626. poly = geo['geom'].buffer(tooldia / 2.0).simplify(tool_tolerance)
  4627. if kind == 'all':
  4628. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  4629. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  4630. elif kind == 'travel':
  4631. if geo['kind'][0] == 'T':
  4632. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  4633. visible=visible, layer=2)
  4634. elif kind == 'cut':
  4635. if geo['kind'][0] == 'C':
  4636. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  4637. visible=visible, layer=1)
  4638. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'])
  4639. def create_geometry(self):
  4640. # TODO: This takes forever. Too much data?
  4641. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  4642. return self.solid_geometry
  4643. # code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  4644. def segment(self, coords):
  4645. """
  4646. break long linear lines to make it more auto level friendly
  4647. """
  4648. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  4649. return list(coords)
  4650. path = [coords[0]]
  4651. # break the line in either x or y dimension only
  4652. def linebreak_single(line, dim, dmax):
  4653. if dmax <= 0:
  4654. return None
  4655. if line[1][dim] > line[0][dim]:
  4656. sign = 1.0
  4657. d = line[1][dim] - line[0][dim]
  4658. else:
  4659. sign = -1.0
  4660. d = line[0][dim] - line[1][dim]
  4661. if d > dmax:
  4662. # make sure we don't make any new lines too short
  4663. if d > dmax * 2:
  4664. dd = dmax
  4665. else:
  4666. dd = d / 2
  4667. other = dim ^ 1
  4668. return (line[0][dim] + dd * sign, line[0][other] + \
  4669. dd * (line[1][other] - line[0][other]) / d)
  4670. return None
  4671. # recursively breaks down a given line until it is within the
  4672. # required step size
  4673. def linebreak(line):
  4674. pt_new = linebreak_single(line, 0, self.segx)
  4675. if pt_new is None:
  4676. pt_new2 = linebreak_single(line, 1, self.segy)
  4677. else:
  4678. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  4679. if pt_new2 is not None:
  4680. pt_new = pt_new2[::-1]
  4681. if pt_new is None:
  4682. path.append(line[1])
  4683. else:
  4684. path.append(pt_new)
  4685. linebreak((pt_new, line[1]))
  4686. for pt in coords[1:]:
  4687. linebreak((path[-1], pt))
  4688. return path
  4689. def linear2gcode(self, linear, tolerance=0, down=True, up=True,
  4690. z_cut=None, z_move=None, zdownrate=None,
  4691. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False):
  4692. """
  4693. Generates G-code to cut along the linear feature.
  4694. :param linear: The path to cut along.
  4695. :type: Shapely.LinearRing or Shapely.Linear String
  4696. :param tolerance: All points in the simplified object will be within the
  4697. tolerance distance of the original geometry.
  4698. :type tolerance: float
  4699. :param feedrate: speed for cut on X - Y plane
  4700. :param feedrate_z: speed for cut on Z plane
  4701. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  4702. :return: G-code to cut along the linear feature.
  4703. :rtype: str
  4704. """
  4705. if z_cut is None:
  4706. z_cut = self.z_cut
  4707. if z_move is None:
  4708. z_move = self.z_move
  4709. #
  4710. # if zdownrate is None:
  4711. # zdownrate = self.zdownrate
  4712. if feedrate is None:
  4713. feedrate = self.feedrate
  4714. if feedrate_z is None:
  4715. feedrate_z = self.feedrate_z
  4716. if feedrate_rapid is None:
  4717. feedrate_rapid = self.feedrate_rapid
  4718. # Simplify paths?
  4719. if tolerance > 0:
  4720. target_linear = linear.simplify(tolerance)
  4721. else:
  4722. target_linear = linear
  4723. gcode = ""
  4724. # path = list(target_linear.coords)
  4725. path = self.segment(target_linear.coords)
  4726. p = self.pp_geometry
  4727. # Move fast to 1st point
  4728. if not cont:
  4729. gcode += self.doformat(p.rapid_code, x=path[0][0], y=path[0][1]) # Move to first point
  4730. # Move down to cutting depth
  4731. if down:
  4732. # Different feedrate for vertical cut?
  4733. gcode += self.doformat(p.feedrate_z_code)
  4734. # gcode += self.doformat(p.feedrate_code)
  4735. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut=z_cut)
  4736. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  4737. # Cutting...
  4738. for pt in path[1:]:
  4739. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1], z=z_cut) # Linear motion to point
  4740. # Up to travelling height.
  4741. if up:
  4742. gcode += self.doformat(p.lift_code, x=pt[0], y=pt[1], z_move=z_move) # Stop cutting
  4743. return gcode
  4744. def linear2gcode_extra(self, linear, tolerance=0, down=True, up=True,
  4745. z_cut=None, z_move=None, zdownrate=None,
  4746. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False):
  4747. """
  4748. Generates G-code to cut along the linear feature.
  4749. :param linear: The path to cut along.
  4750. :type: Shapely.LinearRing or Shapely.Linear String
  4751. :param tolerance: All points in the simplified object will be within the
  4752. tolerance distance of the original geometry.
  4753. :type tolerance: float
  4754. :param feedrate: speed for cut on X - Y plane
  4755. :param feedrate_z: speed for cut on Z plane
  4756. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  4757. :return: G-code to cut along the linear feature.
  4758. :rtype: str
  4759. """
  4760. if z_cut is None:
  4761. z_cut = self.z_cut
  4762. if z_move is None:
  4763. z_move = self.z_move
  4764. #
  4765. # if zdownrate is None:
  4766. # zdownrate = self.zdownrate
  4767. if feedrate is None:
  4768. feedrate = self.feedrate
  4769. if feedrate_z is None:
  4770. feedrate_z = self.feedrate_z
  4771. if feedrate_rapid is None:
  4772. feedrate_rapid = self.feedrate_rapid
  4773. # Simplify paths?
  4774. if tolerance > 0:
  4775. target_linear = linear.simplify(tolerance)
  4776. else:
  4777. target_linear = linear
  4778. gcode = ""
  4779. path = list(target_linear.coords)
  4780. p = self.pp_geometry
  4781. # Move fast to 1st point
  4782. if not cont:
  4783. gcode += self.doformat(p.rapid_code, x=path[0][0], y=path[0][1]) # Move to first point
  4784. # Move down to cutting depth
  4785. if down:
  4786. # Different feedrate for vertical cut?
  4787. if self.feedrate_z is not None:
  4788. gcode += self.doformat(p.feedrate_z_code)
  4789. # gcode += self.doformat(p.feedrate_code)
  4790. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut=z_cut)
  4791. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  4792. else:
  4793. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut=z_cut) # Start cutting
  4794. # Cutting...
  4795. for pt in path[1:]:
  4796. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1], z=z_cut) # Linear motion to point
  4797. # this line is added to create an extra cut over the first point in patch
  4798. # to make sure that we remove the copper leftovers
  4799. gcode += self.doformat(p.linear_code, x=path[1][0], y=path[1][1]) # Linear motion to the 1st point in the cut path
  4800. # Up to travelling height.
  4801. if up:
  4802. gcode += self.doformat(p.lift_code, x=path[1][0], y=path[1][1], z_move=z_move) # Stop cutting
  4803. return gcode
  4804. def point2gcode(self, point):
  4805. gcode = ""
  4806. path = list(point.coords)
  4807. p = self.pp_geometry
  4808. gcode += self.doformat(p.linear_code, x=path[0][0], y=path[0][1]) # Move to first point
  4809. if self.feedrate_z is not None:
  4810. gcode += self.doformat(p.feedrate_z_code)
  4811. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut = self.z_cut)
  4812. gcode += self.doformat(p.feedrate_code)
  4813. else:
  4814. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut = self.z_cut) # Start cutting
  4815. gcode += self.doformat(p.lift_code, x=path[0][0], y=path[0][1]) # Stop cutting
  4816. return gcode
  4817. def export_svg(self, scale_factor=0.00):
  4818. """
  4819. Exports the CNC Job as a SVG Element
  4820. :scale_factor: float
  4821. :return: SVG Element string
  4822. """
  4823. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  4824. # If not specified then try and use the tool diameter
  4825. # This way what is on screen will match what is outputed for the svg
  4826. # This is quite a useful feature for svg's used with visicut
  4827. if scale_factor <= 0:
  4828. scale_factor = self.options['tooldia'] / 2
  4829. # If still 0 then default to 0.05
  4830. # This value appears to work for zooming, and getting the output svg line width
  4831. # to match that viewed on screen with FlatCam
  4832. if scale_factor == 0:
  4833. scale_factor = 0.01
  4834. # Separate the list of cuts and travels into 2 distinct lists
  4835. # This way we can add different formatting / colors to both
  4836. cuts = []
  4837. travels = []
  4838. for g in self.gcode_parsed:
  4839. if g['kind'][0] == 'C': cuts.append(g)
  4840. if g['kind'][0] == 'T': travels.append(g)
  4841. # Used to determine the overall board size
  4842. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  4843. # Convert the cuts and travels into single geometry objects we can render as svg xml
  4844. if travels:
  4845. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  4846. if cuts:
  4847. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  4848. # Render the SVG Xml
  4849. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  4850. # It's better to have the travels sitting underneath the cuts for visicut
  4851. svg_elem = ""
  4852. if travels:
  4853. svg_elem = travelsgeom.svg(scale_factor=scale_factor, stroke_color="#F0E24D")
  4854. if cuts:
  4855. svg_elem += cutsgeom.svg(scale_factor=scale_factor, stroke_color="#5E6CFF")
  4856. return svg_elem
  4857. def bounds(self):
  4858. """
  4859. Returns coordinates of rectangular bounds
  4860. of geometry: (xmin, ymin, xmax, ymax).
  4861. """
  4862. # fixed issue of getting bounds only for one level lists of objects
  4863. # now it can get bounds for nested lists of objects
  4864. def bounds_rec(obj):
  4865. if type(obj) is list:
  4866. minx = Inf
  4867. miny = Inf
  4868. maxx = -Inf
  4869. maxy = -Inf
  4870. for k in obj:
  4871. if type(k) is dict:
  4872. for key in k:
  4873. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  4874. minx = min(minx, minx_)
  4875. miny = min(miny, miny_)
  4876. maxx = max(maxx, maxx_)
  4877. maxy = max(maxy, maxy_)
  4878. else:
  4879. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  4880. minx = min(minx, minx_)
  4881. miny = min(miny, miny_)
  4882. maxx = max(maxx, maxx_)
  4883. maxy = max(maxy, maxy_)
  4884. return minx, miny, maxx, maxy
  4885. else:
  4886. # it's a Shapely object, return it's bounds
  4887. return obj.bounds
  4888. if self.multitool is False:
  4889. log.debug("CNCJob->bounds()")
  4890. if self.solid_geometry is None:
  4891. log.debug("solid_geometry is None")
  4892. return 0, 0, 0, 0
  4893. bounds_coords = bounds_rec(self.solid_geometry)
  4894. else:
  4895. for k, v in self.cnc_tools.items():
  4896. minx = Inf
  4897. miny = Inf
  4898. maxx = -Inf
  4899. maxy = -Inf
  4900. try:
  4901. for k in v['solid_geometry']:
  4902. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  4903. minx = min(minx, minx_)
  4904. miny = min(miny, miny_)
  4905. maxx = max(maxx, maxx_)
  4906. maxy = max(maxy, maxy_)
  4907. except TypeError:
  4908. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  4909. minx = min(minx, minx_)
  4910. miny = min(miny, miny_)
  4911. maxx = max(maxx, maxx_)
  4912. maxy = max(maxy, maxy_)
  4913. bounds_coords = minx, miny, maxx, maxy
  4914. return bounds_coords
  4915. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  4916. def scale(self, xfactor, yfactor=None, point=None):
  4917. """
  4918. Scales all the geometry on the XY plane in the object by the
  4919. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  4920. not altered.
  4921. :param factor: Number by which to scale the object.
  4922. :type factor: float
  4923. :param point: the (x,y) coords for the point of origin of scale
  4924. :type tuple of floats
  4925. :return: None
  4926. :rtype: None
  4927. """
  4928. if yfactor is None:
  4929. yfactor = xfactor
  4930. if point is None:
  4931. px = 0
  4932. py = 0
  4933. else:
  4934. px, py = point
  4935. def scale_g(g):
  4936. """
  4937. :param g: 'g' parameter it's a gcode string
  4938. :return: scaled gcode string
  4939. """
  4940. temp_gcode = ''
  4941. header_start = False
  4942. header_stop = False
  4943. units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  4944. lines = StringIO(g)
  4945. for line in lines:
  4946. # this changes the GCODE header ---- UGLY HACK
  4947. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  4948. header_start = True
  4949. if "G20" in line or "G21" in line:
  4950. header_start = False
  4951. header_stop = True
  4952. if header_start is True:
  4953. header_stop = False
  4954. if "in" in line:
  4955. if units == 'MM':
  4956. line = line.replace("in", "mm")
  4957. if "mm" in line:
  4958. if units == 'IN':
  4959. line = line.replace("mm", "in")
  4960. # find any float number in header (even multiple on the same line) and convert it
  4961. numbers_in_header = re.findall(self.g_nr_re, line)
  4962. if numbers_in_header:
  4963. for nr in numbers_in_header:
  4964. new_nr = float(nr) * xfactor
  4965. # replace the updated string
  4966. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  4967. )
  4968. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  4969. if header_stop is True:
  4970. if "G20" in line:
  4971. if units == 'MM':
  4972. line = line.replace("G20", "G21")
  4973. if "G21" in line:
  4974. if units == 'IN':
  4975. line = line.replace("G21", "G20")
  4976. # find the X group
  4977. match_x = self.g_x_re.search(line)
  4978. if match_x:
  4979. if match_x.group(1) is not None:
  4980. new_x = float(match_x.group(1)[1:]) * xfactor
  4981. # replace the updated string
  4982. line = line.replace(
  4983. match_x.group(1),
  4984. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  4985. )
  4986. # find the Y group
  4987. match_y = self.g_y_re.search(line)
  4988. if match_y:
  4989. if match_y.group(1) is not None:
  4990. new_y = float(match_y.group(1)[1:]) * yfactor
  4991. line = line.replace(
  4992. match_y.group(1),
  4993. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  4994. )
  4995. # find the Z group
  4996. match_z = self.g_z_re.search(line)
  4997. if match_z:
  4998. if match_z.group(1) is not None:
  4999. new_z = float(match_z.group(1)[1:]) * xfactor
  5000. line = line.replace(
  5001. match_z.group(1),
  5002. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  5003. )
  5004. # find the F group
  5005. match_f = self.g_f_re.search(line)
  5006. if match_f:
  5007. if match_f.group(1) is not None:
  5008. new_f = float(match_f.group(1)[1:]) * xfactor
  5009. line = line.replace(
  5010. match_f.group(1),
  5011. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  5012. )
  5013. # find the T group (tool dia on toolchange)
  5014. match_t = self.g_t_re.search(line)
  5015. if match_t:
  5016. if match_t.group(1) is not None:
  5017. new_t = float(match_t.group(1)[1:]) * xfactor
  5018. line = line.replace(
  5019. match_t.group(1),
  5020. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  5021. )
  5022. temp_gcode += line
  5023. lines.close()
  5024. header_stop = False
  5025. return temp_gcode
  5026. if self.multitool is False:
  5027. # offset Gcode
  5028. self.gcode = scale_g(self.gcode)
  5029. # offset geometry
  5030. for g in self.gcode_parsed:
  5031. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  5032. self.create_geometry()
  5033. else:
  5034. for k, v in self.cnc_tools.items():
  5035. # scale Gcode
  5036. v['gcode'] = scale_g(v['gcode'])
  5037. # scale gcode_parsed
  5038. for g in v['gcode_parsed']:
  5039. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  5040. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  5041. self.create_geometry()
  5042. def offset(self, vect):
  5043. """
  5044. Offsets all the geometry on the XY plane in the object by the
  5045. given vector.
  5046. Offsets all the GCODE on the XY plane in the object by the
  5047. given vector.
  5048. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  5049. :param vect: (x, y) offset vector.
  5050. :type vect: tuple
  5051. :return: None
  5052. """
  5053. dx, dy = vect
  5054. def offset_g(g):
  5055. """
  5056. :param g: 'g' parameter it's a gcode string
  5057. :return: offseted gcode string
  5058. """
  5059. temp_gcode = ''
  5060. lines = StringIO(g)
  5061. for line in lines:
  5062. # find the X group
  5063. match_x = self.g_x_re.search(line)
  5064. if match_x:
  5065. if match_x.group(1) is not None:
  5066. # get the coordinate and add X offset
  5067. new_x = float(match_x.group(1)[1:]) + dx
  5068. # replace the updated string
  5069. line = line.replace(
  5070. match_x.group(1),
  5071. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  5072. )
  5073. match_y = self.g_y_re.search(line)
  5074. if match_y:
  5075. if match_y.group(1) is not None:
  5076. new_y = float(match_y.group(1)[1:]) + dy
  5077. line = line.replace(
  5078. match_y.group(1),
  5079. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  5080. )
  5081. temp_gcode += line
  5082. lines.close()
  5083. return temp_gcode
  5084. if self.multitool is False:
  5085. # offset Gcode
  5086. self.gcode = offset_g(self.gcode)
  5087. # offset geometry
  5088. for g in self.gcode_parsed:
  5089. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  5090. self.create_geometry()
  5091. else:
  5092. for k, v in self.cnc_tools.items():
  5093. # offset Gcode
  5094. v['gcode'] = offset_g(v['gcode'])
  5095. # offset gcode_parsed
  5096. for g in v['gcode_parsed']:
  5097. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  5098. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  5099. def mirror(self, axis, point):
  5100. """
  5101. Mirror the geometrys of an object by an given axis around the coordinates of the 'point'
  5102. :param angle:
  5103. :param point: tupple of coordinates (x,y)
  5104. :return:
  5105. """
  5106. px, py = point
  5107. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  5108. for g in self.gcode_parsed:
  5109. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  5110. self.create_geometry()
  5111. def skew(self, angle_x, angle_y, point):
  5112. """
  5113. Shear/Skew the geometries of an object by angles along x and y dimensions.
  5114. Parameters
  5115. ----------
  5116. angle_x, angle_y : float, float
  5117. The shear angle(s) for the x and y axes respectively. These can be
  5118. specified in either degrees (default) or radians by setting
  5119. use_radians=True.
  5120. point: tupple of coordinates (x,y)
  5121. See shapely manual for more information:
  5122. http://toblerity.org/shapely/manual.html#affine-transformations
  5123. """
  5124. px, py = point
  5125. for g in self.gcode_parsed:
  5126. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y,
  5127. origin=(px, py))
  5128. self.create_geometry()
  5129. def rotate(self, angle, point):
  5130. """
  5131. Rotate the geometrys of an object by an given angle around the coordinates of the 'point'
  5132. :param angle:
  5133. :param point: tupple of coordinates (x,y)
  5134. :return:
  5135. """
  5136. px, py = point
  5137. for g in self.gcode_parsed:
  5138. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  5139. self.create_geometry()
  5140. def get_bounds(geometry_list):
  5141. xmin = Inf
  5142. ymin = Inf
  5143. xmax = -Inf
  5144. ymax = -Inf
  5145. #print "Getting bounds of:", str(geometry_set)
  5146. for gs in geometry_list:
  5147. try:
  5148. gxmin, gymin, gxmax, gymax = gs.bounds()
  5149. xmin = min([xmin, gxmin])
  5150. ymin = min([ymin, gymin])
  5151. xmax = max([xmax, gxmax])
  5152. ymax = max([ymax, gymax])
  5153. except:
  5154. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  5155. return [xmin, ymin, xmax, ymax]
  5156. def arc(center, radius, start, stop, direction, steps_per_circ):
  5157. """
  5158. Creates a list of point along the specified arc.
  5159. :param center: Coordinates of the center [x, y]
  5160. :type center: list
  5161. :param radius: Radius of the arc.
  5162. :type radius: float
  5163. :param start: Starting angle in radians
  5164. :type start: float
  5165. :param stop: End angle in radians
  5166. :type stop: float
  5167. :param direction: Orientation of the arc, "CW" or "CCW"
  5168. :type direction: string
  5169. :param steps_per_circ: Number of straight line segments to
  5170. represent a circle.
  5171. :type steps_per_circ: int
  5172. :return: The desired arc, as list of tuples
  5173. :rtype: list
  5174. """
  5175. # TODO: Resolution should be established by maximum error from the exact arc.
  5176. da_sign = {"cw": -1.0, "ccw": 1.0}
  5177. points = []
  5178. if direction == "ccw" and stop <= start:
  5179. stop += 2 * pi
  5180. if direction == "cw" and stop >= start:
  5181. stop -= 2 * pi
  5182. angle = abs(stop - start)
  5183. #angle = stop-start
  5184. steps = max([int(ceil(angle / (2 * pi) * steps_per_circ)), 2])
  5185. delta_angle = da_sign[direction] * angle * 1.0 / steps
  5186. for i in range(steps + 1):
  5187. theta = start + delta_angle * i
  5188. points.append((center[0] + radius * cos(theta), center[1] + radius * sin(theta)))
  5189. return points
  5190. def arc2(p1, p2, center, direction, steps_per_circ):
  5191. r = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  5192. start = arctan2(p1[1] - center[1], p1[0] - center[0])
  5193. stop = arctan2(p2[1] - center[1], p2[0] - center[0])
  5194. return arc(center, r, start, stop, direction, steps_per_circ)
  5195. def arc_angle(start, stop, direction):
  5196. if direction == "ccw" and stop <= start:
  5197. stop += 2 * pi
  5198. if direction == "cw" and stop >= start:
  5199. stop -= 2 * pi
  5200. angle = abs(stop - start)
  5201. return angle
  5202. # def find_polygon(poly, point):
  5203. # """
  5204. # Find an object that object.contains(Point(point)) in
  5205. # poly, which can can be iterable, contain iterable of, or
  5206. # be itself an implementer of .contains().
  5207. #
  5208. # :param poly: See description
  5209. # :return: Polygon containing point or None.
  5210. # """
  5211. #
  5212. # if poly is None:
  5213. # return None
  5214. #
  5215. # try:
  5216. # for sub_poly in poly:
  5217. # p = find_polygon(sub_poly, point)
  5218. # if p is not None:
  5219. # return p
  5220. # except TypeError:
  5221. # try:
  5222. # if poly.contains(Point(point)):
  5223. # return poly
  5224. # except AttributeError:
  5225. # return None
  5226. #
  5227. # return None
  5228. def to_dict(obj):
  5229. """
  5230. Makes the following types into serializable form:
  5231. * ApertureMacro
  5232. * BaseGeometry
  5233. :param obj: Shapely geometry.
  5234. :type obj: BaseGeometry
  5235. :return: Dictionary with serializable form if ``obj`` was
  5236. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  5237. """
  5238. if isinstance(obj, ApertureMacro):
  5239. return {
  5240. "__class__": "ApertureMacro",
  5241. "__inst__": obj.to_dict()
  5242. }
  5243. if isinstance(obj, BaseGeometry):
  5244. return {
  5245. "__class__": "Shply",
  5246. "__inst__": sdumps(obj)
  5247. }
  5248. return obj
  5249. def dict2obj(d):
  5250. """
  5251. Default deserializer.
  5252. :param d: Serializable dictionary representation of an object
  5253. to be reconstructed.
  5254. :return: Reconstructed object.
  5255. """
  5256. if '__class__' in d and '__inst__' in d:
  5257. if d['__class__'] == "Shply":
  5258. return sloads(d['__inst__'])
  5259. if d['__class__'] == "ApertureMacro":
  5260. am = ApertureMacro()
  5261. am.from_dict(d['__inst__'])
  5262. return am
  5263. return d
  5264. else:
  5265. return d
  5266. # def plotg(geo, solid_poly=False, color="black"):
  5267. # try:
  5268. # _ = iter(geo)
  5269. # except:
  5270. # geo = [geo]
  5271. #
  5272. # for g in geo:
  5273. # if type(g) == Polygon:
  5274. # if solid_poly:
  5275. # patch = PolygonPatch(g,
  5276. # facecolor="#BBF268",
  5277. # edgecolor="#006E20",
  5278. # alpha=0.75,
  5279. # zorder=2)
  5280. # ax = subplot(111)
  5281. # ax.add_patch(patch)
  5282. # else:
  5283. # x, y = g.exterior.coords.xy
  5284. # plot(x, y, color=color)
  5285. # for ints in g.interiors:
  5286. # x, y = ints.coords.xy
  5287. # plot(x, y, color=color)
  5288. # continue
  5289. #
  5290. # if type(g) == LineString or type(g) == LinearRing:
  5291. # x, y = g.coords.xy
  5292. # plot(x, y, color=color)
  5293. # continue
  5294. #
  5295. # if type(g) == Point:
  5296. # x, y = g.coords.xy
  5297. # plot(x, y, 'o')
  5298. # continue
  5299. #
  5300. # try:
  5301. # _ = iter(g)
  5302. # plotg(g, color=color)
  5303. # except:
  5304. # log.error("Cannot plot: " + str(type(g)))
  5305. # continue
  5306. def parse_gerber_number(strnumber, int_digits, frac_digits, zeros):
  5307. """
  5308. Parse a single number of Gerber coordinates.
  5309. :param strnumber: String containing a number in decimal digits
  5310. from a coordinate data block, possibly with a leading sign.
  5311. :type strnumber: str
  5312. :param int_digits: Number of digits used for the integer
  5313. part of the number
  5314. :type frac_digits: int
  5315. :param frac_digits: Number of digits used for the fractional
  5316. part of the number
  5317. :type frac_digits: int
  5318. :param zeros: If 'L', leading zeros are removed and trailing zeros are kept. If 'T', is in reverse.
  5319. :type zeros: str
  5320. :return: The number in floating point.
  5321. :rtype: float
  5322. """
  5323. if zeros == 'L':
  5324. ret_val = int(strnumber) * (10 ** (-frac_digits))
  5325. if zeros == 'T':
  5326. int_val = int(strnumber)
  5327. ret_val = (int_val * (10 ** ((int_digits + frac_digits) - len(strnumber)))) * (10 ** (-frac_digits))
  5328. return ret_val
  5329. # def voronoi(P):
  5330. # """
  5331. # Returns a list of all edges of the voronoi diagram for the given input points.
  5332. # """
  5333. # delauny = Delaunay(P)
  5334. # triangles = delauny.points[delauny.vertices]
  5335. #
  5336. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  5337. # long_lines_endpoints = []
  5338. #
  5339. # lineIndices = []
  5340. # for i, triangle in enumerate(triangles):
  5341. # circum_center = circum_centers[i]
  5342. # for j, neighbor in enumerate(delauny.neighbors[i]):
  5343. # if neighbor != -1:
  5344. # lineIndices.append((i, neighbor))
  5345. # else:
  5346. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  5347. # ps = np.array((ps[1], -ps[0]))
  5348. #
  5349. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  5350. # di = middle - triangle[j]
  5351. #
  5352. # ps /= np.linalg.norm(ps)
  5353. # di /= np.linalg.norm(di)
  5354. #
  5355. # if np.dot(di, ps) < 0.0:
  5356. # ps *= -1000.0
  5357. # else:
  5358. # ps *= 1000.0
  5359. #
  5360. # long_lines_endpoints.append(circum_center + ps)
  5361. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  5362. #
  5363. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  5364. #
  5365. # # filter out any duplicate lines
  5366. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  5367. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  5368. # lineIndicesUnique = np.unique(lineIndicesTupled)
  5369. #
  5370. # return vertices, lineIndicesUnique
  5371. #
  5372. #
  5373. # def triangle_csc(pts):
  5374. # rows, cols = pts.shape
  5375. #
  5376. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  5377. # [np.ones((1, rows)), np.zeros((1, 1))]])
  5378. #
  5379. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  5380. # x = np.linalg.solve(A,b)
  5381. # bary_coords = x[:-1]
  5382. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  5383. #
  5384. #
  5385. # def voronoi_cell_lines(points, vertices, lineIndices):
  5386. # """
  5387. # Returns a mapping from a voronoi cell to its edges.
  5388. #
  5389. # :param points: shape (m,2)
  5390. # :param vertices: shape (n,2)
  5391. # :param lineIndices: shape (o,2)
  5392. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  5393. # """
  5394. # kd = KDTree(points)
  5395. #
  5396. # cells = collections.defaultdict(list)
  5397. # for i1, i2 in lineIndices:
  5398. # v1, v2 = vertices[i1], vertices[i2]
  5399. # mid = (v1+v2)/2
  5400. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  5401. # cells[p1Idx].append((i1, i2))
  5402. # cells[p2Idx].append((i1, i2))
  5403. #
  5404. # return cells
  5405. #
  5406. #
  5407. # def voronoi_edges2polygons(cells):
  5408. # """
  5409. # Transforms cell edges into polygons.
  5410. #
  5411. # :param cells: as returned from voronoi_cell_lines
  5412. # :rtype: dict point index -> list of vertex indices which form a polygon
  5413. # """
  5414. #
  5415. # # first, close the outer cells
  5416. # for pIdx, lineIndices_ in cells.items():
  5417. # dangling_lines = []
  5418. # for i1, i2 in lineIndices_:
  5419. # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  5420. # assert 1 <= len(connections) <= 2
  5421. # if len(connections) == 1:
  5422. # dangling_lines.append((i1, i2))
  5423. # assert len(dangling_lines) in [0, 2]
  5424. # if len(dangling_lines) == 2:
  5425. # (i11, i12), (i21, i22) = dangling_lines
  5426. #
  5427. # # determine which line ends are unconnected
  5428. # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  5429. # i11Unconnected = len(connected) == 0
  5430. #
  5431. # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  5432. # i21Unconnected = len(connected) == 0
  5433. #
  5434. # startIdx = i11 if i11Unconnected else i12
  5435. # endIdx = i21 if i21Unconnected else i22
  5436. #
  5437. # cells[pIdx].append((startIdx, endIdx))
  5438. #
  5439. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  5440. # polys = dict()
  5441. # for pIdx, lineIndices_ in cells.items():
  5442. # # get a directed graph which contains both directions and arbitrarily follow one of both
  5443. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  5444. # directedGraphMap = collections.defaultdict(list)
  5445. # for (i1, i2) in directedGraph:
  5446. # directedGraphMap[i1].append(i2)
  5447. # orderedEdges = []
  5448. # currentEdge = directedGraph[0]
  5449. # while len(orderedEdges) < len(lineIndices_):
  5450. # i1 = currentEdge[1]
  5451. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  5452. # nextEdge = (i1, i2)
  5453. # orderedEdges.append(nextEdge)
  5454. # currentEdge = nextEdge
  5455. #
  5456. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  5457. #
  5458. # return polys
  5459. #
  5460. #
  5461. # def voronoi_polygons(points):
  5462. # """
  5463. # Returns the voronoi polygon for each input point.
  5464. #
  5465. # :param points: shape (n,2)
  5466. # :rtype: list of n polygons where each polygon is an array of vertices
  5467. # """
  5468. # vertices, lineIndices = voronoi(points)
  5469. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  5470. # polys = voronoi_edges2polygons(cells)
  5471. # polylist = []
  5472. # for i in xrange(len(points)):
  5473. # poly = vertices[np.asarray(polys[i])]
  5474. # polylist.append(poly)
  5475. # return polylist
  5476. #
  5477. #
  5478. # class Zprofile:
  5479. # def __init__(self):
  5480. #
  5481. # # data contains lists of [x, y, z]
  5482. # self.data = []
  5483. #
  5484. # # Computed voronoi polygons (shapely)
  5485. # self.polygons = []
  5486. # pass
  5487. #
  5488. # def plot_polygons(self):
  5489. # axes = plt.subplot(1, 1, 1)
  5490. #
  5491. # plt.axis([-0.05, 1.05, -0.05, 1.05])
  5492. #
  5493. # for poly in self.polygons:
  5494. # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  5495. # axes.add_patch(p)
  5496. #
  5497. # def init_from_csv(self, filename):
  5498. # pass
  5499. #
  5500. # def init_from_string(self, zpstring):
  5501. # pass
  5502. #
  5503. # def init_from_list(self, zplist):
  5504. # self.data = zplist
  5505. #
  5506. # def generate_polygons(self):
  5507. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  5508. #
  5509. # def normalize(self, origin):
  5510. # pass
  5511. #
  5512. # def paste(self, path):
  5513. # """
  5514. # Return a list of dictionaries containing the parts of the original
  5515. # path and their z-axis offset.
  5516. # """
  5517. #
  5518. # # At most one region/polygon will contain the path
  5519. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  5520. #
  5521. # if len(containing) > 0:
  5522. # return [{"path": path, "z": self.data[containing[0]][2]}]
  5523. #
  5524. # # All region indexes that intersect with the path
  5525. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  5526. #
  5527. # return [{"path": path.intersection(self.polygons[i]),
  5528. # "z": self.data[i][2]} for i in crossing]
  5529. def autolist(obj):
  5530. try:
  5531. _ = iter(obj)
  5532. return obj
  5533. except TypeError:
  5534. return [obj]
  5535. def three_point_circle(p1, p2, p3):
  5536. """
  5537. Computes the center and radius of a circle from
  5538. 3 points on its circumference.
  5539. :param p1: Point 1
  5540. :param p2: Point 2
  5541. :param p3: Point 3
  5542. :return: center, radius
  5543. """
  5544. # Midpoints
  5545. a1 = (p1 + p2) / 2.0
  5546. a2 = (p2 + p3) / 2.0
  5547. # Normals
  5548. b1 = dot((p2 - p1), array([[0, -1], [1, 0]], dtype=float32))
  5549. b2 = dot((p3 - p2), array([[0, 1], [-1, 0]], dtype=float32))
  5550. # Params
  5551. T = solve(transpose(array([-b1, b2])), a1 - a2)
  5552. # Center
  5553. center = a1 + b1 * T[0]
  5554. # Radius
  5555. radius = norm(center - p1)
  5556. return center, radius, T[0]
  5557. def distance(pt1, pt2):
  5558. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  5559. def distance_euclidian(x1, y1, x2, y2):
  5560. return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  5561. class FlatCAMRTree(object):
  5562. """
  5563. Indexes geometry (Any object with "cooords" property containing
  5564. a list of tuples with x, y values). Objects are indexed by
  5565. all their points by default. To index by arbitrary points,
  5566. override self.points2obj.
  5567. """
  5568. def __init__(self):
  5569. # Python RTree Index
  5570. self.rti = rtindex.Index()
  5571. ## Track object-point relationship
  5572. # Each is list of points in object.
  5573. self.obj2points = []
  5574. # Index is index in rtree, value is index of
  5575. # object in obj2points.
  5576. self.points2obj = []
  5577. self.get_points = lambda go: go.coords
  5578. def grow_obj2points(self, idx):
  5579. """
  5580. Increases the size of self.obj2points to fit
  5581. idx + 1 items.
  5582. :param idx: Index to fit into list.
  5583. :return: None
  5584. """
  5585. if len(self.obj2points) > idx:
  5586. # len == 2, idx == 1, ok.
  5587. return
  5588. else:
  5589. # len == 2, idx == 2, need 1 more.
  5590. # range(2, 3)
  5591. for i in range(len(self.obj2points), idx + 1):
  5592. self.obj2points.append([])
  5593. def insert(self, objid, obj):
  5594. self.grow_obj2points(objid)
  5595. self.obj2points[objid] = []
  5596. for pt in self.get_points(obj):
  5597. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  5598. self.obj2points[objid].append(len(self.points2obj))
  5599. self.points2obj.append(objid)
  5600. def remove_obj(self, objid, obj):
  5601. # Use all ptids to delete from index
  5602. for i, pt in enumerate(self.get_points(obj)):
  5603. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  5604. def nearest(self, pt):
  5605. """
  5606. Will raise StopIteration if no items are found.
  5607. :param pt:
  5608. :return:
  5609. """
  5610. return next(self.rti.nearest(pt, objects=True))
  5611. class FlatCAMRTreeStorage(FlatCAMRTree):
  5612. """
  5613. Just like FlatCAMRTree it indexes geometry, but also serves
  5614. as storage for the geometry.
  5615. """
  5616. def __init__(self):
  5617. # super(FlatCAMRTreeStorage, self).__init__()
  5618. super().__init__()
  5619. self.objects = []
  5620. # Optimization attempt!
  5621. self.indexes = {}
  5622. def insert(self, obj):
  5623. self.objects.append(obj)
  5624. idx = len(self.objects) - 1
  5625. # Note: Shapely objects are not hashable any more, althought
  5626. # there seem to be plans to re-introduce the feature in
  5627. # version 2.0. For now, we will index using the object's id,
  5628. # but it's important to remember that shapely geometry is
  5629. # mutable, ie. it can be modified to a totally different shape
  5630. # and continue to have the same id.
  5631. # self.indexes[obj] = idx
  5632. self.indexes[id(obj)] = idx
  5633. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  5634. super().insert(idx, obj)
  5635. #@profile
  5636. def remove(self, obj):
  5637. # See note about self.indexes in insert().
  5638. # objidx = self.indexes[obj]
  5639. objidx = self.indexes[id(obj)]
  5640. # Remove from list
  5641. self.objects[objidx] = None
  5642. # Remove from index
  5643. self.remove_obj(objidx, obj)
  5644. def get_objects(self):
  5645. return (o for o in self.objects if o is not None)
  5646. def nearest(self, pt):
  5647. """
  5648. Returns the nearest matching points and the object
  5649. it belongs to.
  5650. :param pt: Query point.
  5651. :return: (match_x, match_y), Object owner of
  5652. matching point.
  5653. :rtype: tuple
  5654. """
  5655. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  5656. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  5657. # class myO:
  5658. # def __init__(self, coords):
  5659. # self.coords = coords
  5660. #
  5661. #
  5662. # def test_rti():
  5663. #
  5664. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  5665. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  5666. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  5667. #
  5668. # os = [o1, o2]
  5669. #
  5670. # idx = FlatCAMRTree()
  5671. #
  5672. # for o in range(len(os)):
  5673. # idx.insert(o, os[o])
  5674. #
  5675. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  5676. #
  5677. # idx.remove_obj(0, o1)
  5678. #
  5679. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  5680. #
  5681. # idx.remove_obj(1, o2)
  5682. #
  5683. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  5684. #
  5685. #
  5686. # def test_rtis():
  5687. #
  5688. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  5689. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  5690. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  5691. #
  5692. # os = [o1, o2]
  5693. #
  5694. # idx = FlatCAMRTreeStorage()
  5695. #
  5696. # for o in range(len(os)):
  5697. # idx.insert(os[o])
  5698. #
  5699. # #os = None
  5700. # #o1 = None
  5701. # #o2 = None
  5702. #
  5703. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  5704. #
  5705. # idx.remove(idx.nearest((2,0))[1])
  5706. #
  5707. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  5708. #
  5709. # idx.remove(idx.nearest((0,0))[1])
  5710. #
  5711. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]