camlib.py 375 KB

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