camlib.py 312 KB

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