camlib.py 346 KB

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