camlib.py 253 KB

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