camlib.py 369 KB

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