camlib.py 360 KB

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