camlib.py 321 KB

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