camlib.py 338 KB

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