camlib.py 310 KB

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