camlib.py 282 KB

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