camlib.py 360 KB

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