camlib.py 312 KB

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