camlib.py 346 KB

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