camlib.py 333 KB

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