camlib.py 305 KB

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