camlib.py 297 KB

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