camlib.py 260 KB

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