camlib.py 325 KB

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