camlib.py 270 KB

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