camlib.py 312 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586
  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, LineString, Point, LinearRing, MultiLineString, MultiPoint, MultiPolygon
  19. from shapely.geometry import box as shply_box
  20. from shapely.ops import cascaded_union, unary_union, substring
  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' %
  459. _("self.solid_geometry is neither BaseGeometry or list."))
  460. return
  461. def subtract_polygon(self, points):
  462. """
  463. Subtract polygon from the given object. This only operates on the paths in the original geometry,
  464. i.e. it converts polygons into paths.
  465. :param points: The vertices of the polygon.
  466. :return: none
  467. """
  468. if self.solid_geometry is None:
  469. self.solid_geometry = []
  470. # pathonly should be allways True, otherwise polygons are not subtracted
  471. flat_geometry = self.flatten(pathonly=True)
  472. log.debug("%d paths" % len(flat_geometry))
  473. polygon = Polygon(points)
  474. toolgeo = cascaded_union(polygon)
  475. diffs = []
  476. for target in flat_geometry:
  477. if type(target) == LineString or type(target) == LinearRing:
  478. diffs.append(target.difference(toolgeo))
  479. else:
  480. log.warning("Not implemented.")
  481. self.solid_geometry = cascaded_union(diffs)
  482. def bounds(self, flatten=False):
  483. """
  484. Returns coordinates of rectangular bounds
  485. of geometry: (xmin, ymin, xmax, ymax).
  486. :param flatten: will flatten the solid_geometry if True
  487. :return:
  488. """
  489. # fixed issue of getting bounds only for one level lists of objects
  490. # now it can get bounds for nested lists of objects
  491. log.debug("camlib.Geometry.bounds()")
  492. if self.solid_geometry is None:
  493. log.debug("solid_geometry is None")
  494. return 0, 0, 0, 0
  495. def bounds_rec(obj):
  496. if type(obj) is list:
  497. gminx = np.Inf
  498. gminy = np.Inf
  499. gmaxx = -np.Inf
  500. gmaxy = -np.Inf
  501. for k in obj:
  502. if type(k) is dict:
  503. for key in k:
  504. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  505. gminx = min(gminx, minx_)
  506. gminy = min(gminy, miny_)
  507. gmaxx = max(gmaxx, maxx_)
  508. gmaxy = max(gmaxy, maxy_)
  509. else:
  510. try:
  511. if k.is_empty:
  512. continue
  513. except Exception:
  514. pass
  515. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  516. gminx = min(gminx, minx_)
  517. gminy = min(gminy, miny_)
  518. gmaxx = max(gmaxx, maxx_)
  519. gmaxy = max(gmaxy, maxy_)
  520. return gminx, gminy, gmaxx, gmaxy
  521. else:
  522. # it's a Shapely object, return it's bounds
  523. return obj.bounds
  524. if self.multigeo is True:
  525. minx_list = []
  526. miny_list = []
  527. maxx_list = []
  528. maxy_list = []
  529. for tool in self.tools:
  530. working_geo = self.tools[tool]['solid_geometry']
  531. if flatten:
  532. self.flatten(geometry=working_geo, reset=True)
  533. working_geo = self.flat_geometry
  534. minx, miny, maxx, maxy = bounds_rec(working_geo)
  535. minx_list.append(minx)
  536. miny_list.append(miny)
  537. maxx_list.append(maxx)
  538. maxy_list.append(maxy)
  539. return min(minx_list), min(miny_list), max(maxx_list), max(maxy_list)
  540. else:
  541. if flatten:
  542. self.flatten(reset=True)
  543. self.solid_geometry = self.flat_geometry
  544. bounds_coords = bounds_rec(self.solid_geometry)
  545. return bounds_coords
  546. # try:
  547. # # from here: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
  548. # def flatten(l, ltypes=(list, tuple)):
  549. # ltype = type(l)
  550. # l = list(l)
  551. # i = 0
  552. # while i < len(l):
  553. # while isinstance(l[i], ltypes):
  554. # if not l[i]:
  555. # l.pop(i)
  556. # i -= 1
  557. # break
  558. # else:
  559. # l[i:i + 1] = l[i]
  560. # i += 1
  561. # return ltype(l)
  562. #
  563. # log.debug("Geometry->bounds()")
  564. # if self.solid_geometry is None:
  565. # log.debug("solid_geometry is None")
  566. # return 0, 0, 0, 0
  567. #
  568. # if type(self.solid_geometry) is list:
  569. # if len(self.solid_geometry) == 0:
  570. # log.debug('solid_geometry is empty []')
  571. # return 0, 0, 0, 0
  572. # return cascaded_union(flatten(self.solid_geometry)).bounds
  573. # else:
  574. # return self.solid_geometry.bounds
  575. # except Exception as e:
  576. # self.app.inform.emit("[ERROR_NOTCL] Error cause: %s" % str(e))
  577. # log.debug("Geometry->bounds()")
  578. # if self.solid_geometry is None:
  579. # log.debug("solid_geometry is None")
  580. # return 0, 0, 0, 0
  581. #
  582. # if type(self.solid_geometry) is list:
  583. # if len(self.solid_geometry) == 0:
  584. # log.debug('solid_geometry is empty []')
  585. # return 0, 0, 0, 0
  586. # return cascaded_union(self.solid_geometry).bounds
  587. # else:
  588. # return self.solid_geometry.bounds
  589. def find_polygon(self, point, geoset=None):
  590. """
  591. Find an object that object.contains(Point(point)) in
  592. poly, which can can be iterable, contain iterable of, or
  593. be itself an implementer of .contains().
  594. :param point: See description
  595. :param geoset: a polygon or list of polygons where to find if the param point is contained
  596. :return: Polygon containing point or None.
  597. """
  598. if geoset is None:
  599. geoset = self.solid_geometry
  600. try: # Iterable
  601. for sub_geo in geoset:
  602. p = self.find_polygon(point, geoset=sub_geo)
  603. if p is not None:
  604. return p
  605. except TypeError: # Non-iterable
  606. try: # Implements .contains()
  607. if isinstance(geoset, LinearRing):
  608. geoset = Polygon(geoset)
  609. if geoset.contains(Point(point)):
  610. return geoset
  611. except AttributeError: # Does not implement .contains()
  612. return None
  613. return None
  614. def get_interiors(self, geometry=None):
  615. interiors = []
  616. if geometry is None:
  617. geometry = self.solid_geometry
  618. # ## If iterable, expand recursively.
  619. try:
  620. for geo in geometry:
  621. interiors.extend(self.get_interiors(geometry=geo))
  622. # ## Not iterable, get the interiors if polygon.
  623. except TypeError:
  624. if type(geometry) == Polygon:
  625. interiors.extend(geometry.interiors)
  626. return interiors
  627. def get_exteriors(self, geometry=None):
  628. """
  629. Returns all exteriors of polygons in geometry. Uses
  630. ``self.solid_geometry`` if geometry is not provided.
  631. :param geometry: Shapely type or list or list of list of such.
  632. :return: List of paths constituting the exteriors
  633. of polygons in geometry.
  634. """
  635. exteriors = []
  636. if geometry is None:
  637. geometry = self.solid_geometry
  638. # ## If iterable, expand recursively.
  639. try:
  640. for geo in geometry:
  641. exteriors.extend(self.get_exteriors(geometry=geo))
  642. # ## Not iterable, get the exterior if polygon.
  643. except TypeError:
  644. if type(geometry) == Polygon:
  645. exteriors.append(geometry.exterior)
  646. return exteriors
  647. def flatten(self, geometry=None, reset=True, pathonly=False):
  648. """
  649. Creates a list of non-iterable linear geometry objects.
  650. Polygons are expanded into its exterior and interiors if specified.
  651. Results are placed in self.flat_geometry
  652. :param geometry: Shapely type or list or list of list of such.
  653. :param reset: Clears the contents of self.flat_geometry.
  654. :param pathonly: Expands polygons into linear elements.
  655. """
  656. if geometry is None:
  657. geometry = self.solid_geometry
  658. if reset:
  659. self.flat_geometry = []
  660. # ## If iterable, expand recursively.
  661. try:
  662. for geo in geometry:
  663. if geo is not None:
  664. self.flatten(geometry=geo,
  665. reset=False,
  666. pathonly=pathonly)
  667. # ## Not iterable, do the actual indexing and add.
  668. except TypeError:
  669. if pathonly and type(geometry) == Polygon:
  670. self.flat_geometry.append(geometry.exterior)
  671. self.flatten(geometry=geometry.interiors,
  672. reset=False,
  673. pathonly=True)
  674. else:
  675. self.flat_geometry.append(geometry)
  676. return self.flat_geometry
  677. # def make2Dstorage(self):
  678. #
  679. # self.flatten()
  680. #
  681. # def get_pts(o):
  682. # pts = []
  683. # if type(o) == Polygon:
  684. # g = o.exterior
  685. # pts += list(g.coords)
  686. # for i in o.interiors:
  687. # pts += list(i.coords)
  688. # else:
  689. # pts += list(o.coords)
  690. # return pts
  691. #
  692. # storage = FlatCAMRTreeStorage()
  693. # storage.get_points = get_pts
  694. # for shape in self.flat_geometry:
  695. # storage.insert(shape)
  696. # return storage
  697. # def flatten_to_paths(self, geometry=None, reset=True):
  698. # """
  699. # Creates a list of non-iterable linear geometry elements and
  700. # indexes them in rtree.
  701. #
  702. # :param geometry: Iterable geometry
  703. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  704. # :return: self.flat_geometry, self.flat_geometry_rtree
  705. # """
  706. #
  707. # if geometry is None:
  708. # geometry = self.solid_geometry
  709. #
  710. # if reset:
  711. # self.flat_geometry = []
  712. #
  713. # # ## If iterable, expand recursively.
  714. # try:
  715. # for geo in geometry:
  716. # self.flatten_to_paths(geometry=geo, reset=False)
  717. #
  718. # # ## Not iterable, do the actual indexing and add.
  719. # except TypeError:
  720. # if type(geometry) == Polygon:
  721. # g = geometry.exterior
  722. # self.flat_geometry.append(g)
  723. #
  724. # # ## Add first and last points of the path to the index.
  725. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  726. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  727. #
  728. # for interior in geometry.interiors:
  729. # g = interior
  730. # self.flat_geometry.append(g)
  731. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  732. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  733. # else:
  734. # g = geometry
  735. # self.flat_geometry.append(g)
  736. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  737. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  738. #
  739. # return self.flat_geometry, self.flat_geometry_rtree
  740. def isolation_geometry(self, offset, geometry=None, iso_type=2, corner=None, follow=None, passes=0,
  741. prog_plot=False):
  742. """
  743. Creates contours around geometry at a given
  744. offset distance.
  745. :param offset: Offset distance.
  746. :type offset: float
  747. :param geometry The geometry to work with
  748. :param iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  749. :param corner: type of corner for the isolation:
  750. 0 = round; 1 = square; 2= beveled (line that connects the ends)
  751. :param follow: whether the geometry to be isolated is a follow_geometry
  752. :param passes: current pass out of possible multiple passes for which the isolation is done
  753. :param prog_plot: type of plotting: "normal" or "progressive"
  754. :return: The buffered geometry.
  755. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  756. """
  757. if self.app.abort_flag:
  758. # graceful abort requested by the user
  759. raise grace
  760. geo_iso = []
  761. if follow:
  762. return geometry
  763. if geometry:
  764. working_geo = geometry
  765. else:
  766. working_geo = self.solid_geometry
  767. try:
  768. geo_len = len(working_geo)
  769. except TypeError:
  770. geo_len = 1
  771. old_disp_number = 0
  772. pol_nr = 0
  773. # yet, it can be done by issuing an unary_union in the end, thus getting rid of the overlapping geo
  774. try:
  775. for pol in working_geo:
  776. if self.app.abort_flag:
  777. # graceful abort requested by the user
  778. raise grace
  779. if offset == 0:
  780. temp_geo = pol
  781. else:
  782. corner_type = 1 if corner is None else corner
  783. temp_geo = pol.buffer(offset, int(self.geo_steps_per_circle), join_style=corner_type)
  784. geo_iso.append(temp_geo)
  785. pol_nr += 1
  786. # activity view update
  787. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  788. if old_disp_number < disp_number <= 100:
  789. self.app.proc_container.update_view_text(' %s %d: %d%%' %
  790. (_("Pass"), int(passes + 1), int(disp_number)))
  791. old_disp_number = disp_number
  792. except TypeError:
  793. # taking care of the case when the self.solid_geometry is just a single Polygon, not a list or a
  794. # MultiPolygon (not an iterable)
  795. if offset == 0:
  796. temp_geo = working_geo
  797. else:
  798. corner_type = 1 if corner is None else corner
  799. temp_geo = working_geo.buffer(offset, int(self.geo_steps_per_circle), join_style=corner_type)
  800. geo_iso.append(temp_geo)
  801. self.app.proc_container.update_view_text(' %s' % _("Buffering"))
  802. geo_iso = unary_union(geo_iso)
  803. self.app.proc_container.update_view_text('')
  804. # end of replaced block
  805. if iso_type == 2:
  806. ret_geo = geo_iso
  807. elif iso_type == 0:
  808. self.app.proc_container.update_view_text(' %s' % _("Get Exteriors"))
  809. ret_geo = self.get_exteriors(geo_iso)
  810. elif iso_type == 1:
  811. self.app.proc_container.update_view_text(' %s' % _("Get Interiors"))
  812. ret_geo = self.get_interiors(geo_iso)
  813. else:
  814. log.debug("Geometry.isolation_geometry() --> Type of isolation not supported")
  815. return "fail"
  816. if prog_plot == 'progressive':
  817. for elem in ret_geo:
  818. self.plot_temp_shapes(elem)
  819. return ret_geo
  820. def flatten_list(self, obj_list):
  821. for item in obj_list:
  822. if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
  823. yield from self.flatten_list(item)
  824. else:
  825. yield item
  826. def import_svg(self, filename, object_type=None, flip=True, units='MM'):
  827. """
  828. Imports shapes from an SVG file into the object's geometry.
  829. :param filename: Path to the SVG file.
  830. :type filename: str
  831. :param object_type: parameter passed further along
  832. :param flip: Flip the vertically.
  833. :type flip: bool
  834. :param units: FlatCAM units
  835. :return: None
  836. """
  837. log.debug("camlib.Geometry.import_svg()")
  838. # Parse into list of shapely objects
  839. svg_tree = ET.parse(filename)
  840. svg_root = svg_tree.getroot()
  841. # Change origin to bottom left
  842. # h = float(svg_root.get('height'))
  843. # w = float(svg_root.get('width'))
  844. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  845. geos = getsvggeo(svg_root, object_type)
  846. if flip:
  847. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  848. # Add to object
  849. if self.solid_geometry is None:
  850. self.solid_geometry = []
  851. if type(self.solid_geometry) is list:
  852. if type(geos) is list:
  853. self.solid_geometry += geos
  854. else:
  855. self.solid_geometry.append(geos)
  856. else: # It's shapely geometry
  857. self.solid_geometry = [self.solid_geometry, geos]
  858. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  859. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  860. geos_text = getsvgtext(svg_root, object_type, units=units)
  861. if geos_text is not None:
  862. geos_text_f = []
  863. if flip:
  864. # Change origin to bottom left
  865. for i in geos_text:
  866. _, minimy, _, maximy = i.bounds
  867. h2 = (maximy - minimy) * 0.5
  868. geos_text_f.append(translate(scale(i, 1.0, -1.0, origin=(0, 0)), yoff=(h + h2)))
  869. if geos_text_f:
  870. self.solid_geometry = self.solid_geometry + geos_text_f
  871. def import_dxf(self, filename, object_type=None, units='MM'):
  872. """
  873. Imports shapes from an DXF file into the object's geometry.
  874. :param filename: Path to the DXF file.
  875. :type filename: str
  876. :param object_type:
  877. :param units: Application units
  878. :return: None
  879. """
  880. # Parse into list of shapely objects
  881. dxf = ezdxf.readfile(filename)
  882. geos = getdxfgeo(dxf)
  883. # Add to object
  884. if self.solid_geometry is None:
  885. self.solid_geometry = []
  886. if type(self.solid_geometry) is list:
  887. if type(geos) is list:
  888. self.solid_geometry += geos
  889. else:
  890. self.solid_geometry.append(geos)
  891. else: # It's shapely geometry
  892. self.solid_geometry = [self.solid_geometry, geos]
  893. # flatten the self.solid_geometry list for import_dxf() to import DXF as Gerber
  894. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  895. if self.solid_geometry is not None:
  896. self.solid_geometry = cascaded_union(self.solid_geometry)
  897. else:
  898. return
  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 self.app.abort_flag:
  2484. # graceful abort requested by the user
  2485. raise grace
  2486. if 'drills' in tool_dict and tool_dict['drills']:
  2487. for drill_pt in tool_dict['drills']:
  2488. try:
  2489. points[tool].append(drill_pt)
  2490. except KeyError:
  2491. points[tool] = [drill_pt]
  2492. log.debug("Found %d TOOLS with drills." % len(points))
  2493. # check if there are drill points in the exclusion areas.
  2494. # If we find any within the exclusion areas return 'fail'
  2495. for tool in points:
  2496. for pt in points[tool]:
  2497. for area in self.app.exc_areas.exclusion_areas_storage:
  2498. pt_buf = pt.buffer(self.exc_tools[tool]['tooldia'] / 2.0)
  2499. if pt_buf.within(area['shape']) or pt_buf.intersects(area['shape']):
  2500. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Failed. Drill points inside the exclusion zones."))
  2501. return 'fail'
  2502. # this holds the resulting GCode
  2503. self.gcode = []
  2504. self.f_plunge = self.app.defaults["excellon_f_plunge"]
  2505. self.f_retract = self.app.defaults["excellon_f_retract"]
  2506. # #############################################################################################################
  2507. # #############################################################################################################
  2508. # Initialization
  2509. # #############################################################################################################
  2510. # #############################################################################################################
  2511. gcode = self.doformat(p.start_code)
  2512. if use_ui is False:
  2513. gcode += self.doformat(p.z_feedrate_code)
  2514. if self.toolchange is False:
  2515. if self.xy_toolchange is not None:
  2516. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2517. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2518. else:
  2519. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  2520. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  2521. if self.xy_toolchange is not None:
  2522. self.oldx = self.xy_toolchange[0]
  2523. self.oldy = self.xy_toolchange[1]
  2524. else:
  2525. self.oldx = 0.0
  2526. self.oldy = 0.0
  2527. measured_distance = 0.0
  2528. measured_down_distance = 0.0
  2529. measured_up_to_zero_distance = 0.0
  2530. measured_lift_distance = 0.0
  2531. # #############################################################################################################
  2532. # #############################################################################################################
  2533. # GCODE creation
  2534. # #############################################################################################################
  2535. # #############################################################################################################
  2536. self.app.inform.emit('%s...' % _("Starting G-Code"))
  2537. has_drills = None
  2538. for tool, tool_dict in self.exc_tools.items():
  2539. if 'drills' in tool_dict and tool_dict['drills']:
  2540. has_drills = True
  2541. break
  2542. if not has_drills:
  2543. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2544. "The loaded Excellon file has no drills ...")
  2545. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  2546. return 'fail'
  2547. current_platform = platform.architecture()[0]
  2548. if current_platform == '64bit':
  2549. used_excellon_optimization_type = self.excellon_optimization_type
  2550. else:
  2551. used_excellon_optimization_type = 'T'
  2552. # #############################################################################################################
  2553. # #############################################################################################################
  2554. # ################################## DRILLING !!! #########################################################
  2555. # #############################################################################################################
  2556. # #############################################################################################################
  2557. if used_excellon_optimization_type == 'M':
  2558. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2559. elif used_excellon_optimization_type == 'B':
  2560. log.debug("Using OR-Tools Basic drill path optimization.")
  2561. elif used_excellon_optimization_type == 'T':
  2562. log.debug("Using Travelling Salesman drill path optimization.")
  2563. else:
  2564. log.debug("Using no path optimization.")
  2565. if self.toolchange is True:
  2566. for tool in tools:
  2567. # check if it has drills
  2568. if not self.exc_tools[tool]['drills']:
  2569. continue
  2570. if self.app.abort_flag:
  2571. # graceful abort requested by the user
  2572. raise grace
  2573. self.tool = tool
  2574. self.tooldia = self.exc_tools[tool]["tooldia"]
  2575. self.postdata['toolC'] = self.tooldia
  2576. if self.use_ui:
  2577. self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  2578. self.feedrate = self.exc_tools[tool]['data']['feedrate']
  2579. self.z_cut = self.exc_tools[tool]['data']['cutz']
  2580. gcode += self.doformat(p.z_feedrate_code)
  2581. if self.machinist_setting == 0:
  2582. if self.z_cut > 0:
  2583. self.app.inform.emit('[WARNING] %s' %
  2584. _("The Cut Z parameter has positive value. "
  2585. "It is the depth value to drill into material.\n"
  2586. "The Cut Z parameter needs to have a negative value, "
  2587. "assuming it is a typo "
  2588. "therefore the app will convert the value to negative. "
  2589. "Check the resulting CNC code (Gcode etc)."))
  2590. self.z_cut = -self.z_cut
  2591. elif self.z_cut == 0:
  2592. self.app.inform.emit('[WARNING] %s: %s' %
  2593. (_(
  2594. "The Cut Z parameter is zero. There will be no cut, "
  2595. "skipping file"),
  2596. exobj.options['name']))
  2597. return 'fail'
  2598. old_zcut = deepcopy(self.z_cut)
  2599. self.z_move = self.exc_tools[tool]['data']['travelz']
  2600. self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  2601. self.dwell = self.exc_tools[tool]['data']['dwell']
  2602. self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  2603. self.multidepth = self.exc_tools[tool]['data']['multidepth']
  2604. self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  2605. else:
  2606. old_zcut = deepcopy(self.z_cut)
  2607. # #########################################################################################################
  2608. # ############ Create the data. #################
  2609. # #########################################################################################################
  2610. locations = []
  2611. altPoints = []
  2612. optimized_path = []
  2613. if used_excellon_optimization_type == 'M':
  2614. if tool in points:
  2615. locations = self.create_tool_data_array(points=points[tool])
  2616. # if there are no locations then go to the next tool
  2617. if not locations:
  2618. continue
  2619. optimized_path = self.optimized_ortools_meta(locations=locations)
  2620. elif used_excellon_optimization_type == 'B':
  2621. if tool in points:
  2622. locations = self.create_tool_data_array(points=points[tool])
  2623. # if there are no locations then go to the next tool
  2624. if not locations:
  2625. continue
  2626. optimized_path = self.optimized_ortools_basic(locations=locations)
  2627. elif used_excellon_optimization_type == 'T':
  2628. for point in points[tool]:
  2629. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2630. optimized_path = self.optimized_travelling_salesman(altPoints)
  2631. else:
  2632. # it's actually not optimized path but here we build a list of (x,y) coordinates
  2633. # out of the tool's drills
  2634. for drill in self.exc_tools[tool]['drills']:
  2635. unoptimized_coords = (
  2636. drill.x,
  2637. drill.y
  2638. )
  2639. optimized_path.append(unoptimized_coords)
  2640. # #########################################################################################################
  2641. # #########################################################################################################
  2642. # Only if there are locations to drill
  2643. if not optimized_path:
  2644. continue
  2645. if self.app.abort_flag:
  2646. # graceful abort requested by the user
  2647. raise grace
  2648. # Tool change sequence (optional)
  2649. if self.toolchange:
  2650. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  2651. # Spindle start
  2652. gcode += self.doformat(p.spindle_code)
  2653. # Dwell time
  2654. if self.dwell is True:
  2655. gcode += self.doformat(p.dwell_code)
  2656. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  2657. self.app.inform.emit(
  2658. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2659. str(current_tooldia),
  2660. str(self.units))
  2661. )
  2662. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2663. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  2664. # because the values for Z offset are created in build_ui()
  2665. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2666. try:
  2667. z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  2668. except KeyError:
  2669. z_offset = 0
  2670. self.z_cut = z_offset + old_zcut
  2671. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2672. if self.coordinates_type == "G90":
  2673. # Drillling! for Absolute coordinates type G90
  2674. # variables to display the percentage of work done
  2675. geo_len = len(optimized_path)
  2676. old_disp_number = 0
  2677. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2678. loc_nr = 0
  2679. for point in optimized_path:
  2680. if self.app.abort_flag:
  2681. # graceful abort requested by the user
  2682. raise grace
  2683. if used_excellon_optimization_type == 'T':
  2684. locx = point[0]
  2685. locy = point[1]
  2686. else:
  2687. locx = locations[point][0]
  2688. locy = locations[point][1]
  2689. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  2690. end_point=(locx, locy),
  2691. tooldia=current_tooldia)
  2692. prev_z = None
  2693. for travel in travels:
  2694. locx = travel[1][0]
  2695. locy = travel[1][1]
  2696. if travel[0] is not None:
  2697. # move to next point
  2698. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2699. # raise to safe Z (travel[0]) each time because safe Z may be different
  2700. self.z_move = travel[0]
  2701. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2702. # restore z_move
  2703. self.z_move = self.exc_tools[tool]['data']['travelz']
  2704. else:
  2705. if prev_z is not None:
  2706. # move to next point
  2707. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2708. # we assume that previously the z_move was altered therefore raise to
  2709. # the travel_z (z_move)
  2710. self.z_move = self.exc_tools[tool]['data']['travelz']
  2711. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2712. else:
  2713. # move to next point
  2714. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2715. # store prev_z
  2716. prev_z = travel[0]
  2717. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2718. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  2719. doc = deepcopy(self.z_cut)
  2720. self.z_cut = 0.0
  2721. while abs(self.z_cut) < abs(doc):
  2722. self.z_cut -= self.z_depthpercut
  2723. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  2724. self.z_cut = doc
  2725. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2726. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2727. if self.f_retract is False:
  2728. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2729. measured_up_to_zero_distance += abs(self.z_cut)
  2730. measured_lift_distance += abs(self.z_move)
  2731. else:
  2732. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2733. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2734. else:
  2735. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2736. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2737. if self.f_retract is False:
  2738. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2739. measured_up_to_zero_distance += abs(self.z_cut)
  2740. measured_lift_distance += abs(self.z_move)
  2741. else:
  2742. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2743. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2744. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  2745. self.oldx = locx
  2746. self.oldy = locy
  2747. loc_nr += 1
  2748. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2749. if old_disp_number < disp_number <= 100:
  2750. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2751. old_disp_number = disp_number
  2752. else:
  2753. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2754. return 'fail'
  2755. self.z_cut = deepcopy(old_zcut)
  2756. else:
  2757. # We are not using Toolchange therefore we need to decide which tool properties to use
  2758. one_tool = 1
  2759. all_points = []
  2760. for tool in points:
  2761. # check if it has drills
  2762. if not points[tool]:
  2763. continue
  2764. all_points += points[tool]
  2765. if self.app.abort_flag:
  2766. # graceful abort requested by the user
  2767. raise grace
  2768. self.tool = one_tool
  2769. self.tooldia = self.exc_tools[one_tool]["tooldia"]
  2770. self.postdata['toolC'] = self.tooldia
  2771. if self.use_ui:
  2772. self.z_feedrate = self.exc_tools[one_tool]['data']['feedrate_z']
  2773. self.feedrate = self.exc_tools[one_tool]['data']['feedrate']
  2774. self.z_cut = self.exc_tools[one_tool]['data']['cutz']
  2775. gcode += self.doformat(p.z_feedrate_code)
  2776. if self.machinist_setting == 0:
  2777. if self.z_cut > 0:
  2778. self.app.inform.emit('[WARNING] %s' %
  2779. _("The Cut Z parameter has positive value. "
  2780. "It is the depth value to drill into material.\n"
  2781. "The Cut Z parameter needs to have a negative value, "
  2782. "assuming it is a typo "
  2783. "therefore the app will convert the value to negative. "
  2784. "Check the resulting CNC code (Gcode etc)."))
  2785. self.z_cut = -self.z_cut
  2786. elif self.z_cut == 0:
  2787. self.app.inform.emit('[WARNING] %s: %s' %
  2788. (_(
  2789. "The Cut Z parameter is zero. There will be no cut, "
  2790. "skipping file"),
  2791. exobj.options['name']))
  2792. return 'fail'
  2793. old_zcut = deepcopy(self.z_cut)
  2794. self.z_move = self.exc_tools[one_tool]['data']['travelz']
  2795. self.spindlespeed = self.exc_tools[one_tool]['data']['spindlespeed']
  2796. self.dwell = self.exc_tools[one_tool]['data']['dwell']
  2797. self.dwelltime = self.exc_tools[one_tool]['data']['dwelltime']
  2798. self.multidepth = self.exc_tools[one_tool]['data']['multidepth']
  2799. self.z_depthpercut = self.exc_tools[one_tool]['data']['depthperpass']
  2800. else:
  2801. old_zcut = deepcopy(self.z_cut)
  2802. # #########################################################################################################
  2803. # ############ Create the data. #################
  2804. # #########################################################################################################
  2805. locations = []
  2806. altPoints = []
  2807. optimized_path = []
  2808. if used_excellon_optimization_type == 'M':
  2809. if all_points:
  2810. locations = self.create_tool_data_array(points=all_points)
  2811. # if there are no locations then go to the next tool
  2812. if not locations:
  2813. return 'fail'
  2814. optimized_path = self.optimized_ortools_meta(locations=locations)
  2815. elif used_excellon_optimization_type == 'B':
  2816. if all_points:
  2817. locations = self.create_tool_data_array(points=all_points)
  2818. # if there are no locations then go to the next tool
  2819. if not locations:
  2820. return 'fail'
  2821. optimized_path = self.optimized_ortools_basic(locations=locations)
  2822. elif used_excellon_optimization_type == 'T':
  2823. for point in all_points:
  2824. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2825. optimized_path = self.optimized_travelling_salesman(altPoints)
  2826. else:
  2827. # it's actually not optimized path but here we build a list of (x,y) coordinates
  2828. # out of the tool's drills
  2829. for pt in all_points:
  2830. unoptimized_coords = (
  2831. pt.x,
  2832. pt.y
  2833. )
  2834. optimized_path.append(unoptimized_coords)
  2835. # #########################################################################################################
  2836. # #########################################################################################################
  2837. # Only if there are locations to drill
  2838. if not optimized_path:
  2839. return 'fail'
  2840. if self.app.abort_flag:
  2841. # graceful abort requested by the user
  2842. raise grace
  2843. # Spindle start
  2844. gcode += self.doformat(p.spindle_code)
  2845. # Dwell time
  2846. if self.dwell is True:
  2847. gcode += self.doformat(p.dwell_code)
  2848. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[one_tool]["tooldia"])))
  2849. self.app.inform.emit(
  2850. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2851. str(current_tooldia),
  2852. str(self.units))
  2853. )
  2854. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2855. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  2856. # because the values for Z offset are created in build_ui()
  2857. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2858. try:
  2859. z_offset = float(self.exc_tools[one_tool]['data']['offset']) * (-1)
  2860. except KeyError:
  2861. z_offset = 0
  2862. self.z_cut = z_offset + old_zcut
  2863. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2864. if self.coordinates_type == "G90":
  2865. # Drillling! for Absolute coordinates type G90
  2866. # variables to display the percentage of work done
  2867. geo_len = len(optimized_path)
  2868. old_disp_number = 0
  2869. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2870. loc_nr = 0
  2871. for point in optimized_path:
  2872. if self.app.abort_flag:
  2873. # graceful abort requested by the user
  2874. raise grace
  2875. if used_excellon_optimization_type == 'T':
  2876. locx = point[0]
  2877. locy = point[1]
  2878. else:
  2879. locx = locations[point][0]
  2880. locy = locations[point][1]
  2881. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  2882. end_point=(locx, locy),
  2883. tooldia=current_tooldia)
  2884. prev_z = None
  2885. for travel in travels:
  2886. locx = travel[1][0]
  2887. locy = travel[1][1]
  2888. if travel[0] is not None:
  2889. # move to next point
  2890. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2891. # raise to safe Z (travel[0]) each time because safe Z may be different
  2892. self.z_move = travel[0]
  2893. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2894. # restore z_move
  2895. self.z_move = self.exc_tools[one_tool]['data']['travelz']
  2896. else:
  2897. if prev_z is not None:
  2898. # move to next point
  2899. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2900. # we assume that previously the z_move was altered therefore raise to
  2901. # the travel_z (z_move)
  2902. self.z_move = self.exc_tools[one_tool]['data']['travelz']
  2903. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2904. else:
  2905. # move to next point
  2906. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2907. # store prev_z
  2908. prev_z = travel[0]
  2909. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2910. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  2911. doc = deepcopy(self.z_cut)
  2912. self.z_cut = 0.0
  2913. while abs(self.z_cut) < abs(doc):
  2914. self.z_cut -= self.z_depthpercut
  2915. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  2916. self.z_cut = doc
  2917. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2918. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2919. if self.f_retract is False:
  2920. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2921. measured_up_to_zero_distance += abs(self.z_cut)
  2922. measured_lift_distance += abs(self.z_move)
  2923. else:
  2924. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2925. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2926. else:
  2927. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2928. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2929. if self.f_retract is False:
  2930. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2931. measured_up_to_zero_distance += abs(self.z_cut)
  2932. measured_lift_distance += abs(self.z_move)
  2933. else:
  2934. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2935. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2936. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  2937. self.oldx = locx
  2938. self.oldy = locy
  2939. loc_nr += 1
  2940. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2941. if old_disp_number < disp_number <= 100:
  2942. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2943. old_disp_number = disp_number
  2944. else:
  2945. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2946. return 'fail'
  2947. self.z_cut = deepcopy(old_zcut)
  2948. if used_excellon_optimization_type == 'M':
  2949. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  2950. elif used_excellon_optimization_type == 'B':
  2951. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  2952. elif used_excellon_optimization_type == 'T':
  2953. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  2954. else:
  2955. log.debug("The total travel distance with with no optimization is: %s" % str(measured_distance))
  2956. # if used_excellon_optimization_type == 'M':
  2957. # log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2958. #
  2959. # if has_drills:
  2960. # for tool in tools:
  2961. # if self.app.abort_flag:
  2962. # # graceful abort requested by the user
  2963. # raise grace
  2964. #
  2965. # self.tool = tool
  2966. # self.tooldia = self.exc_tools[tool]["tooldia"]
  2967. # self.postdata['toolC'] = self.tooldia
  2968. #
  2969. # if self.use_ui:
  2970. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  2971. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  2972. # gcode += self.doformat(p.z_feedrate_code)
  2973. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  2974. #
  2975. # if self.machinist_setting == 0:
  2976. # if self.z_cut > 0:
  2977. # self.app.inform.emit('[WARNING] %s' %
  2978. # _("The Cut Z parameter has positive value. "
  2979. # "It is the depth value to drill into material.\n"
  2980. # "The Cut Z parameter needs to have a negative value, "
  2981. # "assuming it is a typo "
  2982. # "therefore the app will convert the value to negative. "
  2983. # "Check the resulting CNC code (Gcode etc)."))
  2984. # self.z_cut = -self.z_cut
  2985. # elif self.z_cut == 0:
  2986. # self.app.inform.emit('[WARNING] %s: %s' %
  2987. # (_(
  2988. # "The Cut Z parameter is zero. There will be no cut, "
  2989. # "skipping file"),
  2990. # exobj.options['name']))
  2991. # return 'fail'
  2992. #
  2993. # old_zcut = deepcopy(self.z_cut)
  2994. #
  2995. # self.z_move = self.exc_tools[tool]['data']['travelz']
  2996. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  2997. # self.dwell = self.exc_tools[tool]['data']['dwell']
  2998. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  2999. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3000. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3001. # else:
  3002. # old_zcut = deepcopy(self.z_cut)
  3003. #
  3004. # # ###############################################
  3005. # # ############ Create the data. #################
  3006. # # ###############################################
  3007. # locations = self.create_tool_data_array(tool=tool, points=points)
  3008. # # if there are no locations then go to the next tool
  3009. # if not locations:
  3010. # continue
  3011. # optimized_path = self.optimized_ortools_meta(locations=locations)
  3012. #
  3013. # # Only if tool has points.
  3014. # if tool in points:
  3015. # if self.app.abort_flag:
  3016. # # graceful abort requested by the user
  3017. # raise grace
  3018. #
  3019. # # Tool change sequence (optional)
  3020. # if self.toolchange:
  3021. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3022. # # Spindle start
  3023. # gcode += self.doformat(p.spindle_code)
  3024. # # Dwell time
  3025. # if self.dwell is True:
  3026. # gcode += self.doformat(p.dwell_code)
  3027. #
  3028. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3029. #
  3030. # self.app.inform.emit(
  3031. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3032. # str(current_tooldia),
  3033. # str(self.units))
  3034. # )
  3035. #
  3036. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3037. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3038. # # because the values for Z offset are created in build_ui()
  3039. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3040. # try:
  3041. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3042. # except KeyError:
  3043. # z_offset = 0
  3044. # self.z_cut = z_offset + old_zcut
  3045. #
  3046. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3047. # if self.coordinates_type == "G90":
  3048. # # Drillling! for Absolute coordinates type G90
  3049. # # variables to display the percentage of work done
  3050. # geo_len = len(optimized_path)
  3051. #
  3052. # old_disp_number = 0
  3053. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3054. #
  3055. # loc_nr = 0
  3056. # for k in optimized_path:
  3057. # if self.app.abort_flag:
  3058. # # graceful abort requested by the user
  3059. # raise grace
  3060. #
  3061. # locx = locations[k][0]
  3062. # locy = locations[k][1]
  3063. #
  3064. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3065. # end_point=(locx, locy),
  3066. # tooldia=current_tooldia)
  3067. # prev_z = None
  3068. # for travel in travels:
  3069. # locx = travel[1][0]
  3070. # locy = travel[1][1]
  3071. #
  3072. # if travel[0] is not None:
  3073. # # move to next point
  3074. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3075. #
  3076. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3077. # self.z_move = travel[0]
  3078. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3079. #
  3080. # # restore z_move
  3081. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3082. # else:
  3083. # if prev_z is not None:
  3084. # # move to next point
  3085. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3086. #
  3087. # # we assume that previously the z_move was altered therefore raise to
  3088. # # the travel_z (z_move)
  3089. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3090. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3091. # else:
  3092. # # move to next point
  3093. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3094. #
  3095. # # store prev_z
  3096. # prev_z = travel[0]
  3097. #
  3098. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3099. #
  3100. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3101. # doc = deepcopy(self.z_cut)
  3102. # self.z_cut = 0.0
  3103. #
  3104. # while abs(self.z_cut) < abs(doc):
  3105. #
  3106. # self.z_cut -= self.z_depthpercut
  3107. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3108. # self.z_cut = doc
  3109. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3110. #
  3111. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3112. #
  3113. # if self.f_retract is False:
  3114. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3115. # measured_up_to_zero_distance += abs(self.z_cut)
  3116. # measured_lift_distance += abs(self.z_move)
  3117. # else:
  3118. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3119. #
  3120. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3121. #
  3122. # else:
  3123. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3124. #
  3125. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3126. #
  3127. # if self.f_retract is False:
  3128. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3129. # measured_up_to_zero_distance += abs(self.z_cut)
  3130. # measured_lift_distance += abs(self.z_move)
  3131. # else:
  3132. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3133. #
  3134. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3135. #
  3136. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3137. # self.oldx = locx
  3138. # self.oldy = locy
  3139. #
  3140. # loc_nr += 1
  3141. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3142. #
  3143. # if old_disp_number < disp_number <= 100:
  3144. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3145. # old_disp_number = disp_number
  3146. #
  3147. # else:
  3148. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3149. # return 'fail'
  3150. # self.z_cut = deepcopy(old_zcut)
  3151. # else:
  3152. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3153. # "The loaded Excellon file has no drills ...")
  3154. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3155. # return 'fail'
  3156. #
  3157. # log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  3158. #
  3159. # elif used_excellon_optimization_type == 'B':
  3160. # log.debug("Using OR-Tools Basic drill path optimization.")
  3161. #
  3162. # if has_drills:
  3163. # for tool in tools:
  3164. # if self.app.abort_flag:
  3165. # # graceful abort requested by the user
  3166. # raise grace
  3167. #
  3168. # self.tool = tool
  3169. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3170. # self.postdata['toolC'] = self.tooldia
  3171. #
  3172. # if self.use_ui:
  3173. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3174. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3175. # gcode += self.doformat(p.z_feedrate_code)
  3176. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3177. #
  3178. # if self.machinist_setting == 0:
  3179. # if self.z_cut > 0:
  3180. # self.app.inform.emit('[WARNING] %s' %
  3181. # _("The Cut Z parameter has positive value. "
  3182. # "It is the depth value to drill into material.\n"
  3183. # "The Cut Z parameter needs to have a negative value, "
  3184. # "assuming it is a typo "
  3185. # "therefore the app will convert the value to negative. "
  3186. # "Check the resulting CNC code (Gcode etc)."))
  3187. # self.z_cut = -self.z_cut
  3188. # elif self.z_cut == 0:
  3189. # self.app.inform.emit('[WARNING] %s: %s' %
  3190. # (_(
  3191. # "The Cut Z parameter is zero. There will be no cut, "
  3192. # "skipping file"),
  3193. # exobj.options['name']))
  3194. # return 'fail'
  3195. #
  3196. # old_zcut = deepcopy(self.z_cut)
  3197. #
  3198. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3199. #
  3200. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3201. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3202. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3203. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3204. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3205. # else:
  3206. # old_zcut = deepcopy(self.z_cut)
  3207. #
  3208. # # ###############################################
  3209. # # ############ Create the data. #################
  3210. # # ###############################################
  3211. # locations = self.create_tool_data_array(tool=tool, points=points)
  3212. # # if there are no locations then go to the next tool
  3213. # if not locations:
  3214. # continue
  3215. # optimized_path = self.optimized_ortools_basic(locations=locations)
  3216. #
  3217. # # Only if tool has points.
  3218. # if tool in points:
  3219. # if self.app.abort_flag:
  3220. # # graceful abort requested by the user
  3221. # raise grace
  3222. #
  3223. # # Tool change sequence (optional)
  3224. # if self.toolchange:
  3225. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3226. # gcode += self.doformat(p.spindle_code) # Spindle start)
  3227. # if self.dwell is True:
  3228. # gcode += self.doformat(p.dwell_code) # Dwell time
  3229. # else:
  3230. # gcode += self.doformat(p.spindle_code)
  3231. # if self.dwell is True:
  3232. # gcode += self.doformat(p.dwell_code) # Dwell time
  3233. #
  3234. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3235. #
  3236. # self.app.inform.emit(
  3237. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3238. # str(current_tooldia),
  3239. # str(self.units))
  3240. # )
  3241. #
  3242. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3243. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3244. # # because the values for Z offset are created in build_ui()
  3245. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3246. # try:
  3247. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3248. # except KeyError:
  3249. # z_offset = 0
  3250. # self.z_cut = z_offset + old_zcut
  3251. #
  3252. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3253. # if self.coordinates_type == "G90":
  3254. # # Drillling! for Absolute coordinates type G90
  3255. # # variables to display the percentage of work done
  3256. # geo_len = len(optimized_path)
  3257. # old_disp_number = 0
  3258. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3259. #
  3260. # loc_nr = 0
  3261. # for k in optimized_path:
  3262. # if self.app.abort_flag:
  3263. # # graceful abort requested by the user
  3264. # raise grace
  3265. #
  3266. # locx = locations[k][0]
  3267. # locy = locations[k][1]
  3268. #
  3269. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3270. # end_point=(locx, locy),
  3271. # tooldia=current_tooldia)
  3272. # prev_z = None
  3273. # for travel in travels:
  3274. # locx = travel[1][0]
  3275. # locy = travel[1][1]
  3276. #
  3277. # if travel[0] is not None:
  3278. # # move to next point
  3279. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3280. #
  3281. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3282. # self.z_move = travel[0]
  3283. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3284. #
  3285. # # restore z_move
  3286. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3287. # else:
  3288. # if prev_z is not None:
  3289. # # move to next point
  3290. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3291. #
  3292. # # we assume that previously the z_move was altered therefore raise to
  3293. # # the travel_z (z_move)
  3294. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3295. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3296. # else:
  3297. # # move to next point
  3298. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3299. #
  3300. # # store prev_z
  3301. # prev_z = travel[0]
  3302. #
  3303. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3304. #
  3305. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3306. # doc = deepcopy(self.z_cut)
  3307. # self.z_cut = 0.0
  3308. #
  3309. # while abs(self.z_cut) < abs(doc):
  3310. #
  3311. # self.z_cut -= self.z_depthpercut
  3312. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3313. # self.z_cut = doc
  3314. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3315. #
  3316. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3317. #
  3318. # if self.f_retract is False:
  3319. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3320. # measured_up_to_zero_distance += abs(self.z_cut)
  3321. # measured_lift_distance += abs(self.z_move)
  3322. # else:
  3323. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3324. #
  3325. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3326. #
  3327. # else:
  3328. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3329. #
  3330. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3331. #
  3332. # if self.f_retract is False:
  3333. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3334. # measured_up_to_zero_distance += abs(self.z_cut)
  3335. # measured_lift_distance += abs(self.z_move)
  3336. # else:
  3337. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3338. #
  3339. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3340. #
  3341. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3342. # self.oldx = locx
  3343. # self.oldy = locy
  3344. #
  3345. # loc_nr += 1
  3346. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3347. #
  3348. # if old_disp_number < disp_number <= 100:
  3349. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3350. # old_disp_number = disp_number
  3351. #
  3352. # else:
  3353. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3354. # return 'fail'
  3355. # self.z_cut = deepcopy(old_zcut)
  3356. # else:
  3357. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3358. # "The loaded Excellon file has no drills ...")
  3359. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3360. # return 'fail'
  3361. #
  3362. # log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  3363. #
  3364. # elif used_excellon_optimization_type == 'T':
  3365. # log.debug("Using Travelling Salesman drill path optimization.")
  3366. #
  3367. # for tool in tools:
  3368. # if self.app.abort_flag:
  3369. # # graceful abort requested by the user
  3370. # raise grace
  3371. #
  3372. # if has_drills:
  3373. # self.tool = tool
  3374. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3375. # self.postdata['toolC'] = self.tooldia
  3376. #
  3377. # if self.use_ui:
  3378. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3379. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3380. # gcode += self.doformat(p.z_feedrate_code)
  3381. #
  3382. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3383. #
  3384. # if self.machinist_setting == 0:
  3385. # if self.z_cut > 0:
  3386. # self.app.inform.emit('[WARNING] %s' %
  3387. # _("The Cut Z parameter has positive value. "
  3388. # "It is the depth value to drill into material.\n"
  3389. # "The Cut Z parameter needs to have a negative value, "
  3390. # "assuming it is a typo "
  3391. # "therefore the app will convert the value to negative. "
  3392. # "Check the resulting CNC code (Gcode etc)."))
  3393. # self.z_cut = -self.z_cut
  3394. # elif self.z_cut == 0:
  3395. # self.app.inform.emit('[WARNING] %s: %s' %
  3396. # (_(
  3397. # "The Cut Z parameter is zero. There will be no cut, "
  3398. # "skipping file"),
  3399. # exobj.options['name']))
  3400. # return 'fail'
  3401. #
  3402. # old_zcut = deepcopy(self.z_cut)
  3403. #
  3404. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3405. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3406. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3407. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3408. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3409. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3410. # else:
  3411. # old_zcut = deepcopy(self.z_cut)
  3412. #
  3413. # # ###############################################
  3414. # # ############ Create the data. #################
  3415. # # ###############################################
  3416. # altPoints = []
  3417. # for point in points[tool]:
  3418. # altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  3419. # optimized_path = self.optimized_travelling_salesman(altPoints)
  3420. #
  3421. # # Only if tool has points.
  3422. # if tool in points:
  3423. # if self.app.abort_flag:
  3424. # # graceful abort requested by the user
  3425. # raise grace
  3426. #
  3427. # # Tool change sequence (optional)
  3428. # if self.toolchange:
  3429. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3430. # gcode += self.doformat(p.spindle_code) # Spindle start)
  3431. # if self.dwell is True:
  3432. # gcode += self.doformat(p.dwell_code) # Dwell time
  3433. # else:
  3434. # gcode += self.doformat(p.spindle_code)
  3435. # if self.dwell is True:
  3436. # gcode += self.doformat(p.dwell_code) # Dwell time
  3437. #
  3438. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3439. #
  3440. # self.app.inform.emit(
  3441. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3442. # str(current_tooldia),
  3443. # str(self.units))
  3444. # )
  3445. #
  3446. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3447. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3448. # # because the values for Z offset are created in build_ui()
  3449. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3450. # try:
  3451. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3452. # except KeyError:
  3453. # z_offset = 0
  3454. # self.z_cut = z_offset + old_zcut
  3455. #
  3456. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3457. # if self.coordinates_type == "G90":
  3458. # # Drillling! for Absolute coordinates type G90
  3459. # # variables to display the percentage of work done
  3460. # geo_len = len(optimized_path)
  3461. # old_disp_number = 0
  3462. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3463. #
  3464. # loc_nr = 0
  3465. # for point in optimized_path:
  3466. # if self.app.abort_flag:
  3467. # # graceful abort requested by the user
  3468. # raise grace
  3469. #
  3470. # locx = point[0]
  3471. # locy = point[1]
  3472. #
  3473. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3474. # end_point=(locx, locy),
  3475. # tooldia=current_tooldia)
  3476. # prev_z = None
  3477. # for travel in travels:
  3478. # locx = travel[1][0]
  3479. # locy = travel[1][1]
  3480. #
  3481. # if travel[0] is not None:
  3482. # # move to next point
  3483. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3484. #
  3485. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3486. # self.z_move = travel[0]
  3487. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3488. #
  3489. # # restore z_move
  3490. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3491. # else:
  3492. # if prev_z is not None:
  3493. # # move to next point
  3494. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3495. #
  3496. # # we assume that previously the z_move was altered therefore raise to
  3497. # # the travel_z (z_move)
  3498. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3499. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3500. # else:
  3501. # # move to next point
  3502. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3503. #
  3504. # # store prev_z
  3505. # prev_z = travel[0]
  3506. #
  3507. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3508. #
  3509. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3510. # doc = deepcopy(self.z_cut)
  3511. # self.z_cut = 0.0
  3512. #
  3513. # while abs(self.z_cut) < abs(doc):
  3514. #
  3515. # self.z_cut -= self.z_depthpercut
  3516. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3517. # self.z_cut = doc
  3518. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3519. #
  3520. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3521. #
  3522. # if self.f_retract is False:
  3523. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3524. # measured_up_to_zero_distance += abs(self.z_cut)
  3525. # measured_lift_distance += abs(self.z_move)
  3526. # else:
  3527. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3528. #
  3529. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3530. #
  3531. # else:
  3532. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3533. #
  3534. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3535. #
  3536. # if self.f_retract is False:
  3537. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3538. # measured_up_to_zero_distance += abs(self.z_cut)
  3539. # measured_lift_distance += abs(self.z_move)
  3540. # else:
  3541. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3542. #
  3543. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3544. #
  3545. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3546. # self.oldx = locx
  3547. # self.oldy = locy
  3548. #
  3549. # loc_nr += 1
  3550. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3551. #
  3552. # if old_disp_number < disp_number <= 100:
  3553. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3554. # old_disp_number = disp_number
  3555. # else:
  3556. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3557. # return 'fail'
  3558. # else:
  3559. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3560. # "The loaded Excellon file has no drills ...")
  3561. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3562. # return 'fail'
  3563. # self.z_cut = deepcopy(old_zcut)
  3564. # log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  3565. #
  3566. # else:
  3567. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool(): Chosen drill optimization doesn't exist.")
  3568. # return 'fail'
  3569. # Spindle stop
  3570. gcode += self.doformat(p.spindle_stop_code)
  3571. # Move to End position
  3572. gcode += self.doformat(p.end_code, x=0, y=0)
  3573. # #############################################################################################################
  3574. # ############################# Calculate DISTANCE and ESTIMATED TIME #########################################
  3575. # #############################################################################################################
  3576. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  3577. log.debug("The total travel distance including travel to end position is: %s" %
  3578. str(measured_distance) + '\n')
  3579. self.travel_distance = measured_distance
  3580. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  3581. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  3582. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only with
  3583. # Marlin preprocessor and derivatives.
  3584. self.routing_time = (measured_down_distance + measured_up_to_zero_distance) / self.feedrate
  3585. lift_time = measured_lift_distance / self.feedrate_rapid
  3586. traveled_time = measured_distance / self.feedrate_rapid
  3587. self.routing_time += lift_time + traveled_time
  3588. # #############################################################################################################
  3589. # ############################# Store the GCODE for further usage ############################################
  3590. # #############################################################################################################
  3591. self.gcode = gcode
  3592. self.app.inform.emit(_("Finished G-Code generation..."))
  3593. return 'OK'
  3594. def generate_from_multitool_geometry(self, geometry, append=True, tooldia=None, offset=0.0, tolerance=0, z_cut=1.0,
  3595. z_move=2.0, feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  3596. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  3597. multidepth=False, depthpercut=None, toolchange=False, toolchangez=1.0,
  3598. toolchangexy="0.0, 0.0", extracut=False, extracut_length=0.2,
  3599. startz=None, endz=2.0, endxy='', pp_geometry_name=None, tool_no=1):
  3600. """
  3601. Algorithm to generate from multitool Geometry.
  3602. Algorithm description:
  3603. ----------------------
  3604. Uses RTree to find the nearest path to follow.
  3605. :param geometry:
  3606. :param append:
  3607. :param tooldia:
  3608. :param offset:
  3609. :param tolerance:
  3610. :param z_cut:
  3611. :param z_move:
  3612. :param feedrate:
  3613. :param feedrate_z:
  3614. :param feedrate_rapid:
  3615. :param spindlespeed:
  3616. :param spindledir: Direction of rotation for the spindle. If using GRBL laser mode will
  3617. adjust the laser mode
  3618. :param dwell:
  3619. :param dwelltime:
  3620. :param multidepth: If True, use multiple passes to reach the desired depth.
  3621. :param depthpercut: Maximum depth in each pass.
  3622. :param toolchange:
  3623. :param toolchangez:
  3624. :param toolchangexy:
  3625. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the
  3626. first point in path to ensure complete copper removal
  3627. :param extracut_length: Extra cut legth at the end of the path
  3628. :param startz:
  3629. :param endz:
  3630. :param endxy:
  3631. :param pp_geometry_name:
  3632. :param tool_no:
  3633. :return: GCode - string
  3634. """
  3635. log.debug("Generate_from_multitool_geometry()")
  3636. temp_solid_geometry = []
  3637. if offset != 0.0:
  3638. for it in geometry:
  3639. # if the geometry is a closed shape then create a Polygon out of it
  3640. if isinstance(it, LineString):
  3641. c = it.coords
  3642. if c[0] == c[-1]:
  3643. it = Polygon(it)
  3644. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  3645. else:
  3646. temp_solid_geometry = geometry
  3647. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  3648. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  3649. log.debug("%d paths" % len(flat_geometry))
  3650. try:
  3651. self.tooldia = float(tooldia)
  3652. except Exception as e:
  3653. self.app.inform.emit('[ERROR] %s\n%s' % (_("Failed."), str(e)))
  3654. return 'fail'
  3655. self.z_cut = float(z_cut) if z_cut else None
  3656. self.z_move = float(z_move) if z_move is not None else None
  3657. self.feedrate = float(feedrate) if feedrate else self.app.defaults["geometry_feedrate"]
  3658. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else self.app.defaults["geometry_feedrate_z"]
  3659. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else self.app.defaults["geometry_feedrate_rapid"]
  3660. self.spindlespeed = int(spindlespeed) if spindlespeed != 0 else None
  3661. self.spindledir = spindledir
  3662. self.dwell = dwell
  3663. self.dwelltime = float(dwelltime) if dwelltime else self.app.defaults["geometry_dwelltime"]
  3664. self.startz = float(startz) if startz is not None else self.app.defaults["geometry_startz"]
  3665. self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"]
  3666. self.xy_end = re.sub('[()\[\]]', '', str(endxy)) if endxy else self.app.defaults["geometry_endxy"]
  3667. if self.xy_end and self.xy_end != '':
  3668. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  3669. if self.xy_end and len(self.xy_end) < 2:
  3670. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  3671. "in the format (x, y) but now there is only one value, not two."))
  3672. return 'fail'
  3673. self.z_depthpercut = float(depthpercut) if depthpercut else self.app.defaults["geometry_depthperpass"]
  3674. self.multidepth = multidepth
  3675. self.z_toolchange = float(toolchangez) if toolchangez is not None else self.app.defaults["geometry_toolchangez"]
  3676. # it servers in the preprocessor file
  3677. self.tool = tool_no
  3678. try:
  3679. if toolchangexy == '':
  3680. self.xy_toolchange = None
  3681. else:
  3682. self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) \
  3683. if toolchangexy else self.app.defaults["geometry_toolchangexy"]
  3684. if self.xy_toolchange and self.xy_toolchange != '':
  3685. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  3686. if len(self.xy_toolchange) < 2:
  3687. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  3688. "in the format (x, y) \n"
  3689. "but now there is only one value, not two."))
  3690. return 'fail'
  3691. except Exception as e:
  3692. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  3693. pass
  3694. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  3695. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  3696. if self.z_cut is None:
  3697. if 'laser' not in self.pp_geometry_name:
  3698. self.app.inform.emit(
  3699. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  3700. "other parameters."))
  3701. return 'fail'
  3702. else:
  3703. self.z_cut = 0
  3704. if self.machinist_setting == 0:
  3705. if self.z_cut > 0:
  3706. self.app.inform.emit('[WARNING] %s' %
  3707. _("The Cut Z parameter has positive value. "
  3708. "It is the depth value to cut into material.\n"
  3709. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  3710. "therefore the app will convert the value to negative."
  3711. "Check the resulting CNC code (Gcode etc)."))
  3712. self.z_cut = -self.z_cut
  3713. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  3714. self.app.inform.emit('[WARNING] %s: %s' %
  3715. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  3716. self.options['name']))
  3717. return 'fail'
  3718. if self.z_move is None:
  3719. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  3720. return 'fail'
  3721. if self.z_move < 0:
  3722. self.app.inform.emit('[WARNING] %s' %
  3723. _("The Travel Z parameter has negative value. "
  3724. "It is the height value to travel between cuts.\n"
  3725. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  3726. "therefore the app will convert the value to positive."
  3727. "Check the resulting CNC code (Gcode etc)."))
  3728. self.z_move = -self.z_move
  3729. elif self.z_move == 0:
  3730. self.app.inform.emit('[WARNING] %s: %s' %
  3731. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  3732. self.options['name']))
  3733. return 'fail'
  3734. # made sure that depth_per_cut is no more then the z_cut
  3735. if abs(self.z_cut) < self.z_depthpercut:
  3736. self.z_depthpercut = abs(self.z_cut)
  3737. # ## Index first and last points in paths
  3738. # What points to index.
  3739. def get_pts(o):
  3740. return [o.coords[0], o.coords[-1]]
  3741. # Create the indexed storage.
  3742. storage = FlatCAMRTreeStorage()
  3743. storage.get_points = get_pts
  3744. # Store the geometry
  3745. log.debug("Indexing geometry before generating G-Code...")
  3746. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  3747. for geo_shape in flat_geometry:
  3748. if self.app.abort_flag:
  3749. # graceful abort requested by the user
  3750. raise grace
  3751. if geo_shape is not None:
  3752. storage.insert(geo_shape)
  3753. # self.input_geometry_bounds = geometry.bounds()
  3754. if not append:
  3755. self.gcode = ""
  3756. # tell preprocessor the number of tool (for toolchange)
  3757. self.tool = tool_no
  3758. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  3759. # given under the name 'toolC'
  3760. self.postdata['toolC'] = self.tooldia
  3761. # Initial G-Code
  3762. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  3763. p = self.pp_geometry
  3764. self.gcode = self.doformat(p.start_code)
  3765. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  3766. if toolchange is False:
  3767. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  3768. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  3769. if toolchange:
  3770. # if "line_xyz" in self.pp_geometry_name:
  3771. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  3772. # else:
  3773. # self.gcode += self.doformat(p.toolchange_code)
  3774. self.gcode += self.doformat(p.toolchange_code)
  3775. if 'laser' not in self.pp_geometry_name:
  3776. self.gcode += self.doformat(p.spindle_code) # Spindle start
  3777. else:
  3778. # for laser this will disable the laser
  3779. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  3780. if self.dwell is True:
  3781. self.gcode += self.doformat(p.dwell_code) # Dwell time
  3782. else:
  3783. if 'laser' not in self.pp_geometry_name:
  3784. self.gcode += self.doformat(p.spindle_code) # Spindle start
  3785. if self.dwell is True:
  3786. self.gcode += self.doformat(p.dwell_code) # Dwell time
  3787. total_travel = 0.0
  3788. total_cut = 0.0
  3789. # ## Iterate over geometry paths getting the nearest each time.
  3790. log.debug("Starting G-Code...")
  3791. self.app.inform.emit('%s...' % _("Starting G-Code"))
  3792. path_count = 0
  3793. current_pt = (0, 0)
  3794. # variables to display the percentage of work done
  3795. geo_len = len(flat_geometry)
  3796. old_disp_number = 0
  3797. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  3798. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  3799. self.app.inform.emit('%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3800. str(current_tooldia),
  3801. str(self.units)))
  3802. pt, geo = storage.nearest(current_pt)
  3803. try:
  3804. while True:
  3805. if self.app.abort_flag:
  3806. # graceful abort requested by the user
  3807. raise grace
  3808. path_count += 1
  3809. # Remove before modifying, otherwise deletion will fail.
  3810. storage.remove(geo)
  3811. # If last point in geometry is the nearest but prefer the first one if last point == first point
  3812. # then reverse coordinates.
  3813. if pt != geo.coords[0] and pt == geo.coords[-1]:
  3814. geo.coords = list(geo.coords)[::-1]
  3815. # ---------- Single depth/pass --------
  3816. if not multidepth:
  3817. # calculate the cut distance
  3818. total_cut = total_cut + geo.length
  3819. self.gcode += self.create_gcode_single_pass(geo, current_tooldia, extracut, extracut_length,
  3820. tolerance, z_move=z_move, old_point=current_pt)
  3821. # --------- Multi-pass ---------
  3822. else:
  3823. # calculate the cut distance
  3824. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  3825. nr_cuts = 0
  3826. depth = abs(self.z_cut)
  3827. while depth > 0:
  3828. nr_cuts += 1
  3829. depth -= float(self.z_depthpercut)
  3830. total_cut += (geo.length * nr_cuts)
  3831. self.gcode += self.create_gcode_multi_pass(geo, current_tooldia, extracut, extracut_length,
  3832. tolerance, z_move=z_move, postproc=p,
  3833. old_point=current_pt)
  3834. # calculate the total distance
  3835. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  3836. current_pt = geo.coords[-1]
  3837. pt, geo = storage.nearest(current_pt) # Next
  3838. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  3839. if old_disp_number < disp_number <= 100:
  3840. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3841. old_disp_number = disp_number
  3842. except StopIteration: # Nothing found in storage.
  3843. pass
  3844. log.debug("Finished G-Code... %s paths traced." % path_count)
  3845. # add move to end position
  3846. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  3847. self.travel_distance += total_travel + total_cut
  3848. self.routing_time += total_cut / self.feedrate
  3849. # Finish
  3850. self.gcode += self.doformat(p.spindle_stop_code)
  3851. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  3852. self.gcode += self.doformat(p.end_code, x=0, y=0)
  3853. self.app.inform.emit(
  3854. '%s... %s %s.' % (_("Finished G-Code generation"), str(path_count), _("paths traced"))
  3855. )
  3856. return self.gcode
  3857. def generate_from_geometry_2(self, geometry, append=True, tooldia=None, offset=0.0, tolerance=0, z_cut=None,
  3858. z_move=None, feedrate=None, feedrate_z=None, feedrate_rapid=None, spindlespeed=None,
  3859. spindledir='CW', dwell=False, dwelltime=None, multidepth=False, depthpercut=None,
  3860. toolchange=False, toolchangez=None, toolchangexy="0.0, 0.0", extracut=False,
  3861. extracut_length=None, startz=None, endz=None, endxy='', pp_geometry_name=None,
  3862. tool_no=1):
  3863. """
  3864. Second algorithm to generate from Geometry.
  3865. Algorithm description:
  3866. ----------------------
  3867. Uses RTree to find the nearest path to follow.
  3868. :param geometry:
  3869. :param append:
  3870. :param tooldia:
  3871. :param offset:
  3872. :param tolerance:
  3873. :param z_cut:
  3874. :param z_move:
  3875. :param feedrate:
  3876. :param feedrate_z:
  3877. :param feedrate_rapid:
  3878. :param spindlespeed:
  3879. :param spindledir:
  3880. :param dwell:
  3881. :param dwelltime:
  3882. :param multidepth: If True, use multiple passes to reach the desired depth.
  3883. :param depthpercut: Maximum depth in each pass.
  3884. :param toolchange:
  3885. :param toolchangez:
  3886. :param toolchangexy:
  3887. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the first point in
  3888. path to ensure complete copper removal
  3889. :param extracut_length: The extra cut length
  3890. :param startz:
  3891. :param endz:
  3892. :param endxy:
  3893. :param pp_geometry_name:
  3894. :param tool_no:
  3895. :return: None
  3896. """
  3897. if not isinstance(geometry, Geometry):
  3898. self.app.inform.emit('[ERROR] %s: %s' % (_("Expected a Geometry, got"), type(geometry)))
  3899. return 'fail'
  3900. log.debug("Executing camlib.CNCJob.generate_from_geometry_2()")
  3901. # if solid_geometry is empty raise an exception
  3902. if not geometry.solid_geometry:
  3903. self.app.inform.emit(
  3904. '[ERROR_NOTCL] %s' % _("Trying to generate a CNC Job from a Geometry object without solid_geometry.")
  3905. )
  3906. temp_solid_geometry = []
  3907. def bounds_rec(obj):
  3908. if type(obj) is list:
  3909. minx = np.Inf
  3910. miny = np.Inf
  3911. maxx = -np.Inf
  3912. maxy = -np.Inf
  3913. for k in obj:
  3914. if type(k) is dict:
  3915. for key in k:
  3916. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  3917. minx = min(minx, minx_)
  3918. miny = min(miny, miny_)
  3919. maxx = max(maxx, maxx_)
  3920. maxy = max(maxy, maxy_)
  3921. else:
  3922. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3923. minx = min(minx, minx_)
  3924. miny = min(miny, miny_)
  3925. maxx = max(maxx, maxx_)
  3926. maxy = max(maxy, maxy_)
  3927. return minx, miny, maxx, maxy
  3928. else:
  3929. # it's a Shapely object, return it's bounds
  3930. return obj.bounds
  3931. if offset != 0.0:
  3932. offset_for_use = offset
  3933. if offset < 0:
  3934. a, b, c, d = bounds_rec(geometry.solid_geometry)
  3935. # if the offset is less than half of the total length or less than half of the total width of the
  3936. # solid geometry it's obvious we can't do the offset
  3937. if -offset > ((c - a) / 2) or -offset > ((d - b) / 2):
  3938. self.app.inform.emit(
  3939. '[ERROR_NOTCL] %s' %
  3940. _("The Tool Offset value is too negative to use for the current_geometry.\n"
  3941. "Raise the value (in module) and try again.")
  3942. )
  3943. return 'fail'
  3944. # hack: make offset smaller by 0.0000000001 which is insignificant difference but allow the job
  3945. # to continue
  3946. elif -offset == ((c - a) / 2) or -offset == ((d - b) / 2):
  3947. offset_for_use = offset - 0.0000000001
  3948. for it in geometry.solid_geometry:
  3949. # if the geometry is a closed shape then create a Polygon out of it
  3950. if isinstance(it, LineString):
  3951. c = it.coords
  3952. if c[0] == c[-1]:
  3953. it = Polygon(it)
  3954. temp_solid_geometry.append(it.buffer(offset_for_use, join_style=2))
  3955. else:
  3956. temp_solid_geometry = geometry.solid_geometry
  3957. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  3958. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  3959. log.debug("%d paths" % len(flat_geometry))
  3960. default_dia = None
  3961. if isinstance(self.app.defaults["geometry_cnctooldia"], float):
  3962. default_dia = self.app.defaults["geometry_cnctooldia"]
  3963. else:
  3964. try:
  3965. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  3966. tools_diameters = [eval(a) for a in tools_string if a != '']
  3967. default_dia = tools_diameters[0] if tools_diameters else 0.0
  3968. except Exception as e:
  3969. self.app.log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  3970. try:
  3971. self.tooldia = float(tooldia) if tooldia else default_dia
  3972. except ValueError:
  3973. self.tooldia = [float(el) for el in tooldia.split(',') if el != ''] if tooldia is not None else default_dia
  3974. if self.tooldia is None:
  3975. self.app.inform.emit('[ERROR] %s' % _("Failed."))
  3976. return 'fail'
  3977. self.z_cut = float(z_cut) if z_cut is not None else self.app.defaults["geometry_cutz"]
  3978. self.z_move = float(z_move) if z_move is not None else self.app.defaults["geometry_travelz"]
  3979. self.feedrate = float(feedrate) if feedrate is not None else self.app.defaults["geometry_feedrate"]
  3980. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else self.app.defaults["geometry_feedrate_z"]
  3981. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid is not None else \
  3982. self.app.defaults["geometry_feedrate_rapid"]
  3983. self.spindlespeed = int(spindlespeed) if spindlespeed != 0 and spindlespeed is not None else None
  3984. self.spindledir = spindledir
  3985. self.dwell = dwell
  3986. self.dwelltime = float(dwelltime) if dwelltime is not None else self.app.defaults["geometry_dwelltime"]
  3987. self.startz = float(startz) if startz is not None and startz != '' else self.app.defaults["geometry_startz"]
  3988. self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"]
  3989. self.xy_end = endxy if endxy != '' and endxy else self.app.defaults["geometry_endxy"]
  3990. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  3991. if self.xy_end is not None and self.xy_end != '':
  3992. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  3993. if self.xy_end and len(self.xy_end) < 2:
  3994. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  3995. "in the format (x, y) but now there is only one value, not two."))
  3996. return 'fail'
  3997. self.z_depthpercut = float(depthpercut) if depthpercut is not None and depthpercut != 0 else abs(self.z_cut)
  3998. self.multidepth = multidepth
  3999. self.z_toolchange = float(toolchangez) if toolchangez is not None else self.app.defaults["geometry_toolchangez"]
  4000. self.extracut_length = float(extracut_length) if extracut_length is not None else \
  4001. self.app.defaults["geometry_extracut_length"]
  4002. try:
  4003. if toolchangexy == '':
  4004. self.xy_toolchange = None
  4005. else:
  4006. self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) if self.xy_toolchange else None
  4007. if self.xy_toolchange and self.xy_toolchange != '':
  4008. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  4009. if len(self.xy_toolchange) < 2:
  4010. msg = _("The Toolchange X,Y field in Edit -> Preferences has to be in the format (x, y)\n"
  4011. "but now there is only one value, not two.")
  4012. self.app.inform.emit('[ERROR] %s' % msg)
  4013. return 'fail'
  4014. except Exception as e:
  4015. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  4016. pass
  4017. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4018. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4019. if self.machinist_setting == 0:
  4020. if self.z_cut is None:
  4021. if 'laser' not in self.pp_geometry_name:
  4022. self.app.inform.emit(
  4023. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4024. "other parameters.")
  4025. )
  4026. return 'fail'
  4027. else:
  4028. self.z_cut = 0.0
  4029. if self.z_cut > 0:
  4030. self.app.inform.emit('[WARNING] %s' %
  4031. _("The Cut Z parameter has positive value. "
  4032. "It is the depth value to cut into material.\n"
  4033. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4034. "therefore the app will convert the value to negative."
  4035. "Check the resulting CNC code (Gcode etc)."))
  4036. self.z_cut = -self.z_cut
  4037. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  4038. self.app.inform.emit(
  4039. '[WARNING] %s: %s' % (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  4040. geometry.options['name'])
  4041. )
  4042. return 'fail'
  4043. if self.z_move is None:
  4044. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  4045. return 'fail'
  4046. if self.z_move < 0:
  4047. self.app.inform.emit('[WARNING] %s' %
  4048. _("The Travel Z parameter has negative value. "
  4049. "It is the height value to travel between cuts.\n"
  4050. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4051. "therefore the app will convert the value to positive."
  4052. "Check the resulting CNC code (Gcode etc)."))
  4053. self.z_move = -self.z_move
  4054. elif self.z_move == 0:
  4055. self.app.inform.emit(
  4056. '[WARNING] %s: %s' % (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  4057. self.options['name'])
  4058. )
  4059. return 'fail'
  4060. # made sure that depth_per_cut is no more then the z_cut
  4061. try:
  4062. if abs(self.z_cut) < self.z_depthpercut:
  4063. self.z_depthpercut = abs(self.z_cut)
  4064. except TypeError:
  4065. self.z_depthpercut = abs(self.z_cut)
  4066. # ## Index first and last points in paths
  4067. # What points to index.
  4068. def get_pts(o):
  4069. return [o.coords[0], o.coords[-1]]
  4070. # Create the indexed storage.
  4071. storage = FlatCAMRTreeStorage()
  4072. storage.get_points = get_pts
  4073. # Store the geometry
  4074. log.debug("Indexing geometry before generating G-Code...")
  4075. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  4076. for geo_shape in flat_geometry:
  4077. if self.app.abort_flag:
  4078. # graceful abort requested by the user
  4079. raise grace
  4080. if geo_shape is not None:
  4081. storage.insert(geo_shape)
  4082. if not append:
  4083. self.gcode = ""
  4084. # tell preprocessor the number of tool (for toolchange)
  4085. self.tool = tool_no
  4086. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4087. # given under the name 'toolC'
  4088. # this is a fancy way of adding a class attribute (which should be added in the __init__ method) without doing
  4089. # it there :)
  4090. self.postdata['toolC'] = self.tooldia
  4091. # Initial G-Code
  4092. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  4093. # the 'p' local attribute is a reference to the current preprocessor class
  4094. p = self.pp_geometry
  4095. self.oldx = 0.0
  4096. self.oldy = 0.0
  4097. self.gcode = self.doformat(p.start_code)
  4098. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4099. if toolchange is False:
  4100. # all the x and y parameters in self.doformat() are used only by some preprocessors not by all
  4101. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4102. self.gcode += self.doformat(p.startz_code, x=self.oldx, y=self.oldy)
  4103. if toolchange:
  4104. # if "line_xyz" in self.pp_geometry_name:
  4105. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4106. # else:
  4107. # self.gcode += self.doformat(p.toolchange_code)
  4108. self.gcode += self.doformat(p.toolchange_code)
  4109. if 'laser' not in self.pp_geometry_name:
  4110. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4111. else:
  4112. # for laser this will disable the laser
  4113. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4114. if self.dwell is True:
  4115. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4116. else:
  4117. if 'laser' not in self.pp_geometry_name:
  4118. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4119. if self.dwell is True:
  4120. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4121. total_travel = 0.0
  4122. total_cut = 0.0
  4123. # Iterate over geometry paths getting the nearest each time.
  4124. log.debug("Starting G-Code...")
  4125. self.app.inform.emit('%s...' % _("Starting G-Code"))
  4126. # variables to display the percentage of work done
  4127. geo_len = len(flat_geometry)
  4128. old_disp_number = 0
  4129. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  4130. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  4131. self.app.inform.emit(
  4132. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"), str(current_tooldia), str(self.units))
  4133. )
  4134. path_count = 0
  4135. current_pt = (0, 0)
  4136. pt, geo = storage.nearest(current_pt)
  4137. # when nothing is left in the storage a StopIteration exception will be raised therefore stopping
  4138. # the whole process including the infinite loop while True below.
  4139. try:
  4140. while True:
  4141. if self.app.abort_flag:
  4142. # graceful abort requested by the user
  4143. raise grace
  4144. path_count += 1
  4145. # Remove before modifying, otherwise deletion will fail.
  4146. storage.remove(geo)
  4147. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4148. # then reverse coordinates.
  4149. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4150. geo.coords = list(geo.coords)[::-1]
  4151. # ---------- Single depth/pass --------
  4152. if not multidepth:
  4153. # calculate the cut distance
  4154. total_cut += geo.length
  4155. self.gcode += self.create_gcode_single_pass(geo, current_tooldia, extracut, self.extracut_length,
  4156. tolerance, z_move=z_move, old_point=current_pt)
  4157. # --------- Multi-pass ---------
  4158. else:
  4159. # calculate the cut distance
  4160. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  4161. nr_cuts = 0
  4162. depth = abs(self.z_cut)
  4163. while depth > 0:
  4164. nr_cuts += 1
  4165. depth -= float(self.z_depthpercut)
  4166. total_cut += (geo.length * nr_cuts)
  4167. self.gcode += self.create_gcode_multi_pass(geo, current_tooldia, extracut, self.extracut_length,
  4168. tolerance, z_move=z_move, postproc=p,
  4169. old_point=current_pt)
  4170. # calculate the travel distance
  4171. total_travel += abs(distance(pt1=current_pt, pt2=pt))
  4172. current_pt = geo.coords[-1]
  4173. pt, geo = storage.nearest(current_pt) # Next
  4174. # update the activity counter (lower left side of the app, status bar)
  4175. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4176. if old_disp_number < disp_number <= 100:
  4177. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4178. old_disp_number = disp_number
  4179. except StopIteration: # Nothing found in storage.
  4180. pass
  4181. log.debug("Finishing G-Code... %s paths traced." % path_count)
  4182. # add move to end position
  4183. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  4184. self.travel_distance += total_travel + total_cut
  4185. self.routing_time += total_cut / self.feedrate
  4186. # Finish
  4187. self.gcode += self.doformat(p.spindle_stop_code)
  4188. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4189. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4190. self.app.inform.emit(
  4191. '%s... %s %s' % (_("Finished G-Code generation"), str(path_count), _(" paths traced."))
  4192. )
  4193. return self.gcode
  4194. def generate_gcode_from_solderpaste_geo(self, **kwargs):
  4195. """
  4196. Algorithm to generate from multitool Geometry.
  4197. Algorithm description:
  4198. ----------------------
  4199. Uses RTree to find the nearest path to follow.
  4200. :return: Gcode string
  4201. """
  4202. log.debug("Generate_from_solderpaste_geometry()")
  4203. # ## Index first and last points in paths
  4204. # What points to index.
  4205. def get_pts(o):
  4206. return [o.coords[0], o.coords[-1]]
  4207. self.gcode = ""
  4208. if not kwargs:
  4209. log.debug("camlib.generate_from_solderpaste_geo() --> No tool in the solderpaste geometry.")
  4210. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4211. _("There is no tool data in the SolderPaste geometry."))
  4212. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4213. # given under the name 'toolC'
  4214. self.postdata['z_start'] = kwargs['data']['tools_solderpaste_z_start']
  4215. self.postdata['z_dispense'] = kwargs['data']['tools_solderpaste_z_dispense']
  4216. self.postdata['z_stop'] = kwargs['data']['tools_solderpaste_z_stop']
  4217. self.postdata['z_travel'] = kwargs['data']['tools_solderpaste_z_travel']
  4218. self.postdata['z_toolchange'] = kwargs['data']['tools_solderpaste_z_toolchange']
  4219. self.postdata['xy_toolchange'] = kwargs['data']['tools_solderpaste_xy_toolchange']
  4220. self.postdata['frxy'] = kwargs['data']['tools_solderpaste_frxy']
  4221. self.postdata['frz'] = kwargs['data']['tools_solderpaste_frz']
  4222. self.postdata['frz_dispense'] = kwargs['data']['tools_solderpaste_frz_dispense']
  4223. self.postdata['speedfwd'] = kwargs['data']['tools_solderpaste_speedfwd']
  4224. self.postdata['dwellfwd'] = kwargs['data']['tools_solderpaste_dwellfwd']
  4225. self.postdata['speedrev'] = kwargs['data']['tools_solderpaste_speedrev']
  4226. self.postdata['dwellrev'] = kwargs['data']['tools_solderpaste_dwellrev']
  4227. self.postdata['pp_solderpaste_name'] = kwargs['data']['tools_solderpaste_pp']
  4228. self.postdata['toolC'] = kwargs['tooldia']
  4229. self.pp_solderpaste_name = kwargs['data']['tools_solderpaste_pp'] if kwargs['data']['tools_solderpaste_pp'] \
  4230. else self.app.defaults['tools_solderpaste_pp']
  4231. p = self.app.preprocessors[self.pp_solderpaste_name]
  4232. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4233. flat_geometry = self.flatten(kwargs['solid_geometry'], pathonly=True)
  4234. log.debug("%d paths" % len(flat_geometry))
  4235. # Create the indexed storage.
  4236. storage = FlatCAMRTreeStorage()
  4237. storage.get_points = get_pts
  4238. # Store the geometry
  4239. log.debug("Indexing geometry before generating G-Code...")
  4240. for geo_shape in flat_geometry:
  4241. if self.app.abort_flag:
  4242. # graceful abort requested by the user
  4243. raise grace
  4244. if geo_shape is not None:
  4245. storage.insert(geo_shape)
  4246. # Initial G-Code
  4247. self.gcode = self.doformat(p.start_code)
  4248. self.gcode += self.doformat(p.spindle_off_code)
  4249. self.gcode += self.doformat(p.toolchange_code)
  4250. # ## Iterate over geometry paths getting the nearest each time.
  4251. log.debug("Starting SolderPaste G-Code...")
  4252. path_count = 0
  4253. current_pt = (0, 0)
  4254. # variables to display the percentage of work done
  4255. geo_len = len(flat_geometry)
  4256. old_disp_number = 0
  4257. pt, geo = storage.nearest(current_pt)
  4258. try:
  4259. while True:
  4260. if self.app.abort_flag:
  4261. # graceful abort requested by the user
  4262. raise grace
  4263. path_count += 1
  4264. # Remove before modifying, otherwise deletion will fail.
  4265. storage.remove(geo)
  4266. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4267. # then reverse coordinates.
  4268. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4269. geo.coords = list(geo.coords)[::-1]
  4270. self.gcode += self.create_soldepaste_gcode(geo, p=p, old_point=current_pt)
  4271. current_pt = geo.coords[-1]
  4272. pt, geo = storage.nearest(current_pt) # Next
  4273. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4274. if old_disp_number < disp_number <= 100:
  4275. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4276. old_disp_number = disp_number
  4277. except StopIteration: # Nothing found in storage.
  4278. pass
  4279. log.debug("Finishing SolderPste G-Code... %s paths traced." % path_count)
  4280. self.app.inform.emit(
  4281. '%s... %s %s' % (_("Finished SolderPaste G-Code generation"), str(path_count), _("paths traced."))
  4282. )
  4283. # Finish
  4284. self.gcode += self.doformat(p.lift_code)
  4285. self.gcode += self.doformat(p.end_code)
  4286. return self.gcode
  4287. def create_soldepaste_gcode(self, geometry, p, old_point=(0, 0)):
  4288. gcode = ''
  4289. path = geometry.coords
  4290. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  4291. if self.coordinates_type == "G90":
  4292. # For Absolute coordinates type G90
  4293. first_x = path[0][0]
  4294. first_y = path[0][1]
  4295. else:
  4296. # For Incremental coordinates type G91
  4297. first_x = path[0][0] - old_point[0]
  4298. first_y = path[0][1] - old_point[1]
  4299. if type(geometry) == LineString or type(geometry) == LinearRing:
  4300. # Move fast to 1st point
  4301. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  4302. # Move down to cutting depth
  4303. gcode += self.doformat(p.z_feedrate_code)
  4304. gcode += self.doformat(p.down_z_start_code)
  4305. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  4306. gcode += self.doformat(p.dwell_fwd_code)
  4307. gcode += self.doformat(p.feedrate_z_dispense_code)
  4308. gcode += self.doformat(p.lift_z_dispense_code)
  4309. gcode += self.doformat(p.feedrate_xy_code)
  4310. # Cutting...
  4311. prev_x = first_x
  4312. prev_y = first_y
  4313. for pt in path[1:]:
  4314. if self.coordinates_type == "G90":
  4315. # For Absolute coordinates type G90
  4316. next_x = pt[0]
  4317. next_y = pt[1]
  4318. else:
  4319. # For Incremental coordinates type G91
  4320. next_x = pt[0] - prev_x
  4321. next_y = pt[1] - prev_y
  4322. gcode += self.doformat(p.linear_code, x=next_x, y=next_y) # Linear motion to point
  4323. prev_x = next_x
  4324. prev_y = next_y
  4325. # Up to travelling height.
  4326. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  4327. gcode += self.doformat(p.spindle_rev_code)
  4328. gcode += self.doformat(p.down_z_stop_code)
  4329. gcode += self.doformat(p.spindle_off_code)
  4330. gcode += self.doformat(p.dwell_rev_code)
  4331. gcode += self.doformat(p.z_feedrate_code)
  4332. gcode += self.doformat(p.lift_code)
  4333. elif type(geometry) == Point:
  4334. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  4335. gcode += self.doformat(p.feedrate_z_dispense_code)
  4336. gcode += self.doformat(p.down_z_start_code)
  4337. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  4338. gcode += self.doformat(p.dwell_fwd_code)
  4339. gcode += self.doformat(p.lift_z_dispense_code)
  4340. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  4341. gcode += self.doformat(p.spindle_rev_code)
  4342. gcode += self.doformat(p.spindle_off_code)
  4343. gcode += self.doformat(p.down_z_stop_code)
  4344. gcode += self.doformat(p.dwell_rev_code)
  4345. gcode += self.doformat(p.z_feedrate_code)
  4346. gcode += self.doformat(p.lift_code)
  4347. return gcode
  4348. def create_gcode_single_pass(self, geometry, cdia, extracut, extracut_length, tolerance, z_move, old_point=(0, 0)):
  4349. """
  4350. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  4351. :param geometry: A Shapely Geometry (LineString or LinearRing) which is the path to be cut
  4352. :type geometry: LineString, LinearRing
  4353. :param cdia: Tool diameter
  4354. :type cdia: float
  4355. :param extracut: Will add an extra cut over the point where start of the cut is met with the end cut
  4356. :type extracut: bool
  4357. :param extracut_length: The length of the extra cut: half before the meeting point, half after
  4358. :type extracut_length: float
  4359. :param tolerance: Tolerance used to simplify the paths (making them mre rough)
  4360. :type tolerance: float
  4361. :param z_move: Travel Z
  4362. :type z_move: float
  4363. :param old_point: Previous point
  4364. :type old_point: tuple
  4365. :return: Gcode
  4366. :rtype: str
  4367. """
  4368. # p = postproc
  4369. if type(geometry) == LineString or type(geometry) == LinearRing:
  4370. if extracut is False or not geometry.is_ring:
  4371. gcode_single_pass = self.linear2gcode(geometry, cdia, z_move=z_move, tolerance=tolerance,
  4372. old_point=old_point)
  4373. else:
  4374. gcode_single_pass = self.linear2gcode_extra(geometry, cdia, extracut_length, tolerance=tolerance,
  4375. z_move=z_move, old_point=old_point)
  4376. elif type(geometry) == Point:
  4377. gcode_single_pass = self.point2gcode(geometry, cdia, z_move=z_move, old_point=old_point)
  4378. else:
  4379. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  4380. return
  4381. return gcode_single_pass
  4382. def create_gcode_multi_pass(self, geometry, cdia, extracut, extracut_length, tolerance, postproc, z_move,
  4383. old_point=(0, 0)):
  4384. """
  4385. :param geometry: A Shapely Geometry (LineString or LinearRing) which is the path to be cut
  4386. :type geometry: LineString, LinearRing
  4387. :param cdia: Tool diameter
  4388. :type cdia: float
  4389. :param extracut: Will add an extra cut over the point where start of the cut is met with the end cut
  4390. :type extracut: bool
  4391. :param extracut_length: The length of the extra cut: half before the meeting point, half after
  4392. :type extracut_length: float
  4393. :param tolerance: Tolerance used to simplify the paths (making them mre rough)
  4394. :type tolerance: float
  4395. :param postproc: Preprocessor class
  4396. :type postproc: class
  4397. :param z_move: Travel Z
  4398. :type z_move: float
  4399. :param old_point: Previous point
  4400. :type old_point: tuple
  4401. :return: Gcode
  4402. :rtype: str
  4403. """
  4404. p = postproc
  4405. gcode_multi_pass = ''
  4406. if isinstance(self.z_cut, Decimal):
  4407. z_cut = self.z_cut
  4408. else:
  4409. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  4410. if self.z_depthpercut is None:
  4411. self.z_depthpercut = z_cut
  4412. elif not isinstance(self.z_depthpercut, Decimal):
  4413. self.z_depthpercut = Decimal(self.z_depthpercut).quantize(Decimal('0.000000001'))
  4414. depth = 0
  4415. reverse = False
  4416. while depth > z_cut:
  4417. # Increase depth. Limit to z_cut.
  4418. depth -= self.z_depthpercut
  4419. if depth < z_cut:
  4420. depth = z_cut
  4421. # Cut at specific depth and do not lift the tool.
  4422. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  4423. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  4424. # is inconsequential.
  4425. if type(geometry) == LineString or type(geometry) == LinearRing:
  4426. if extracut is False or not geometry.is_ring:
  4427. gcode_multi_pass += self.linear2gcode(geometry, cdia, tolerance=tolerance, z_cut=depth, up=False,
  4428. z_move=z_move, old_point=old_point)
  4429. else:
  4430. gcode_multi_pass += self.linear2gcode_extra(geometry, cdia, extracut_length, tolerance=tolerance,
  4431. z_move=z_move, z_cut=depth, up=False,
  4432. old_point=old_point)
  4433. # Ignore multi-pass for points.
  4434. elif type(geometry) == Point:
  4435. gcode_multi_pass += self.point2gcode(geometry, cdia, z_move=z_move, old_point=old_point)
  4436. break # Ignoring ...
  4437. else:
  4438. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  4439. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  4440. if type(geometry) == LineString:
  4441. geometry.coords = list(geometry.coords)[::-1]
  4442. reverse = True
  4443. # If geometry is reversed, revert.
  4444. if reverse:
  4445. if type(geometry) == LineString:
  4446. geometry.coords = list(geometry.coords)[::-1]
  4447. # Lift the tool
  4448. gcode_multi_pass += self.doformat(p.lift_code, x=old_point[0], y=old_point[1])
  4449. return gcode_multi_pass
  4450. def codes_split(self, gline):
  4451. """
  4452. Parses a line of G-Code such as "G01 X1234 Y987" into
  4453. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  4454. :param gline: G-Code line string
  4455. :type gline: str
  4456. :return: Dictionary with parsed line.
  4457. :rtype: dict
  4458. """
  4459. command = {}
  4460. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4461. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  4462. if match_z:
  4463. command['G'] = 0
  4464. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  4465. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  4466. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  4467. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  4468. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  4469. if match_pa:
  4470. command['G'] = 0
  4471. command['X'] = float(match_pa.group(1).replace(" ", "")) / 40
  4472. command['Y'] = float(match_pa.group(2).replace(" ", "")) / 40
  4473. match_pen = re.search(r"^(P[U|D])", gline)
  4474. if match_pen:
  4475. if match_pen.group(1) == 'PU':
  4476. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  4477. # therefore the move is of kind T (travel)
  4478. command['Z'] = 1
  4479. else:
  4480. command['Z'] = 0
  4481. elif 'laser' in self.pp_excellon_name.lower() or 'laser' in self.pp_geometry_name.lower() or \
  4482. (self.pp_solderpaste_name is not None and 'paste' in self.pp_solderpaste_name.lower()):
  4483. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  4484. if match_lsr:
  4485. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  4486. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  4487. match_lsr_pos = re.search(r"^(M0?[3-5])", gline)
  4488. if match_lsr_pos:
  4489. if 'M05' in match_lsr_pos.group(1) or 'M5' in match_lsr_pos.group(1):
  4490. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  4491. # therefore the move is of kind T (travel)
  4492. command['Z'] = 1
  4493. else:
  4494. command['Z'] = 0
  4495. match_lsr_pos_2 = re.search(r"^(M10[6|7])", gline)
  4496. if match_lsr_pos_2:
  4497. if 'M107' in match_lsr_pos_2.group(1):
  4498. command['Z'] = 1
  4499. else:
  4500. command['Z'] = 0
  4501. elif self.pp_solderpaste_name is not None:
  4502. if 'Paste' in self.pp_solderpaste_name:
  4503. match_paste = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  4504. if match_paste:
  4505. command['X'] = float(match_paste.group(1).replace(" ", ""))
  4506. command['Y'] = float(match_paste.group(2).replace(" ", ""))
  4507. else:
  4508. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  4509. while match:
  4510. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  4511. gline = gline[match.end():]
  4512. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  4513. return command
  4514. def gcode_parse(self, force_parsing=None):
  4515. """
  4516. G-Code parser (from self.gcode). Generates dictionary with
  4517. single-segment LineString's and "kind" indicating cut or travel,
  4518. fast or feedrate speed.
  4519. Will return a dict in the format:
  4520. {
  4521. "geom": LineString(path),
  4522. "kind": kind
  4523. }
  4524. where kind can be either ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  4525. :param force_parsing:
  4526. :type force_parsing:
  4527. :return:
  4528. :rtype: dict
  4529. """
  4530. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  4531. # Results go here
  4532. geometry = []
  4533. # Last known instruction
  4534. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  4535. # Current path: temporary storage until tool is
  4536. # lifted or lowered.
  4537. if self.toolchange_xy_type == "excellon":
  4538. if self.app.defaults["excellon_toolchangexy"] == '' or self.app.defaults["excellon_toolchangexy"] is None:
  4539. pos_xy = (0, 0)
  4540. else:
  4541. pos_xy = self.app.defaults["excellon_toolchangexy"]
  4542. try:
  4543. pos_xy = [float(eval(a)) for a in pos_xy.split(",")]
  4544. except Exception:
  4545. if len(pos_xy) != 2:
  4546. pos_xy = (0, 0)
  4547. else:
  4548. if self.app.defaults["geometry_toolchangexy"] == '' or self.app.defaults["geometry_toolchangexy"] is None:
  4549. pos_xy = (0, 0)
  4550. else:
  4551. pos_xy = self.app.defaults["geometry_toolchangexy"]
  4552. try:
  4553. pos_xy = [float(eval(a)) for a in pos_xy.split(",")]
  4554. except Exception:
  4555. if len(pos_xy) != 2:
  4556. pos_xy = (0, 0)
  4557. path = [pos_xy]
  4558. # path = [(0, 0)]
  4559. gcode_lines_list = self.gcode.splitlines()
  4560. self.app.inform.emit('%s: %d' % (_("Parsing GCode file. Number of lines"), len(gcode_lines_list)))
  4561. # Process every instruction
  4562. for line in gcode_lines_list:
  4563. if force_parsing is False or force_parsing is None:
  4564. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  4565. return "fail"
  4566. gobj = self.codes_split(line)
  4567. # ## Units
  4568. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  4569. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  4570. continue
  4571. # TODO take into consideration the tools and update the travel line thickness
  4572. if 'T' in gobj:
  4573. pass
  4574. # ## Changing height
  4575. if 'Z' in gobj:
  4576. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4577. pass
  4578. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  4579. pass
  4580. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  4581. pass
  4582. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  4583. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  4584. pass
  4585. else:
  4586. log.warning("Non-orthogonal motion: From %s" % str(current))
  4587. log.warning(" To: %s" % str(gobj))
  4588. current['Z'] = gobj['Z']
  4589. # Store the path into geometry and reset path
  4590. if len(path) > 1:
  4591. geometry.append({"geom": LineString(path),
  4592. "kind": kind})
  4593. path = [path[-1]] # Start with the last point of last path.
  4594. # create the geometry for the holes created when drilling Excellon drills
  4595. if self.origin_kind == 'excellon':
  4596. if current['Z'] < 0:
  4597. current_drill_point_coords = (
  4598. float('%.*f' % (self.decimals, current['X'])),
  4599. float('%.*f' % (self.decimals, current['Y']))
  4600. )
  4601. # find the drill diameter knowing the drill coordinates
  4602. break_loop = False
  4603. for tool, tool_dict in self.exc_tools.items():
  4604. if 'drills' in tool_dict:
  4605. for drill_pt in tool_dict['drills']:
  4606. point_in_dict_coords = (
  4607. float('%.*f' % (self.decimals, drill_pt.x)),
  4608. float('%.*f' % (self.decimals, drill_pt.y))
  4609. )
  4610. if point_in_dict_coords == current_drill_point_coords:
  4611. dia = self.exc_tools[tool]['tooldia']
  4612. kind = ['C', 'F']
  4613. geometry.append(
  4614. {
  4615. "geom": Point(current_drill_point_coords).buffer(dia / 2.0).exterior,
  4616. "kind": kind
  4617. }
  4618. )
  4619. break_loop = True
  4620. break
  4621. if break_loop:
  4622. break
  4623. if 'G' in gobj:
  4624. current['G'] = int(gobj['G'])
  4625. if 'X' in gobj or 'Y' in gobj:
  4626. if 'X' in gobj:
  4627. x = gobj['X']
  4628. # current['X'] = x
  4629. else:
  4630. x = current['X']
  4631. if 'Y' in gobj:
  4632. y = gobj['Y']
  4633. else:
  4634. y = current['Y']
  4635. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  4636. if current['Z'] > 0:
  4637. kind[0] = 'T'
  4638. if current['G'] > 0:
  4639. kind[1] = 'S'
  4640. if current['G'] in [0, 1]: # line
  4641. path.append((x, y))
  4642. arcdir = [None, None, "cw", "ccw"]
  4643. if current['G'] in [2, 3]: # arc
  4644. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  4645. radius = np.sqrt(gobj['I'] ** 2 + gobj['J'] ** 2)
  4646. start = np.arctan2(-gobj['J'], -gobj['I'])
  4647. stop = np.arctan2(-center[1] + y, -center[0] + x)
  4648. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle))
  4649. current['X'] = x
  4650. current['Y'] = y
  4651. # Update current instruction
  4652. for code in gobj:
  4653. current[code] = gobj[code]
  4654. self.app.inform.emit('%s...' % _("Creating Geometry from the parsed GCode file. "))
  4655. # There might not be a change in height at the
  4656. # end, therefore, see here too if there is
  4657. # a final path.
  4658. if len(path) > 1:
  4659. geometry.append(
  4660. {
  4661. "geom": LineString(path),
  4662. "kind": kind
  4663. }
  4664. )
  4665. self.gcode_parsed = geometry
  4666. return geometry
  4667. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  4668. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  4669. # alpha={"T": 0.3, "C": 1.0}):
  4670. # """
  4671. # Creates a Matplotlib figure with a plot of the
  4672. # G-code job.
  4673. # """
  4674. # if tooldia is None:
  4675. # tooldia = self.tooldia
  4676. #
  4677. # fig = Figure(dpi=dpi)
  4678. # ax = fig.add_subplot(111)
  4679. # ax.set_aspect(1)
  4680. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  4681. # ax.set_xlim(xmin-margin, xmax+margin)
  4682. # ax.set_ylim(ymin-margin, ymax+margin)
  4683. #
  4684. # if tooldia == 0:
  4685. # for geo in self.gcode_parsed:
  4686. # linespec = '--'
  4687. # linecolor = color[geo['kind'][0]][1]
  4688. # if geo['kind'][0] == 'C':
  4689. # linespec = 'k-'
  4690. # x, y = geo['geom'].coords.xy
  4691. # ax.plot(x, y, linespec, color=linecolor)
  4692. # else:
  4693. # for geo in self.gcode_parsed:
  4694. # poly = geo['geom'].buffer(tooldia/2.0)
  4695. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  4696. # edgecolor=color[geo['kind'][0]][1],
  4697. # alpha=alpha[geo['kind'][0]], zorder=2)
  4698. # ax.add_patch(patch)
  4699. #
  4700. # return fig
  4701. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  4702. color=None, alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  4703. """
  4704. Plots the G-code job onto the given axes.
  4705. :param tooldia: Tool diameter.
  4706. :type tooldia: float
  4707. :param dpi: Not used!
  4708. :type dpi: float
  4709. :param margin: Not used!
  4710. :type margin: float
  4711. :param gcode_parsed: Parsed Gcode
  4712. :type gcode_parsed: str
  4713. :param color: Color specification.
  4714. :type color: str
  4715. :param alpha: Transparency specification.
  4716. :type alpha: dict
  4717. :param tool_tolerance: Tolerance when drawing the toolshape.
  4718. :type tool_tolerance: float
  4719. :param obj: The object for whih to plot
  4720. :type obj: class
  4721. :param visible: Visibility status
  4722. :type visible: bool
  4723. :param kind: Can be: "travel", "cut", "all"
  4724. :type kind: str
  4725. :return: None
  4726. :rtype:
  4727. """
  4728. # units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4729. if color is None:
  4730. color = {
  4731. "T": [self.app.defaults["cncjob_travel_fill"], self.app.defaults["cncjob_travel_line"]],
  4732. "C": [self.app.defaults["cncjob_plot_fill"], self.app.defaults["cncjob_plot_line"]]
  4733. }
  4734. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  4735. path_num = 0
  4736. if tooldia is None:
  4737. tooldia = self.tooldia
  4738. # this should be unlikely unless when upstream the tooldia is a tuple made by one dia and a comma like (2.4,)
  4739. if isinstance(tooldia, list):
  4740. tooldia = tooldia[0] if tooldia[0] is not None else self.tooldia
  4741. if tooldia == 0:
  4742. for geo in gcode_parsed:
  4743. if kind == 'all':
  4744. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  4745. elif kind == 'travel':
  4746. if geo['kind'][0] == 'T':
  4747. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  4748. elif kind == 'cut':
  4749. if geo['kind'][0] == 'C':
  4750. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  4751. else:
  4752. text = []
  4753. pos = []
  4754. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  4755. if self.coordinates_type == "G90":
  4756. # For Absolute coordinates type G90
  4757. for geo in gcode_parsed:
  4758. if geo['kind'][0] == 'T':
  4759. current_position = geo['geom'].coords[0]
  4760. if current_position not in pos:
  4761. pos.append(current_position)
  4762. path_num += 1
  4763. text.append(str(path_num))
  4764. current_position = geo['geom'].coords[-1]
  4765. if current_position not in pos:
  4766. pos.append(current_position)
  4767. path_num += 1
  4768. text.append(str(path_num))
  4769. # plot the geometry of Excellon objects
  4770. if self.origin_kind == 'excellon':
  4771. try:
  4772. if geo['kind'][0] == 'T':
  4773. # if the geos are travel lines it will enter into Exception
  4774. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999),
  4775. resolution=self.steps_per_circle)
  4776. else:
  4777. poly = Polygon(geo['geom'])
  4778. poly = poly.simplify(tool_tolerance)
  4779. except Exception:
  4780. # deal here with unexpected plot errors due of LineStrings not valid
  4781. continue
  4782. # try:
  4783. # poly = Polygon(geo['geom'])
  4784. # except ValueError:
  4785. # # if the geos are travel lines it will enter into Exception
  4786. # poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  4787. # poly = poly.simplify(tool_tolerance)
  4788. # except Exception:
  4789. # # deal here with unexpected plot errors due of LineStrings not valid
  4790. # continue
  4791. else:
  4792. # plot the geometry of any objects other than Excellon
  4793. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  4794. poly = poly.simplify(tool_tolerance)
  4795. if kind == 'all':
  4796. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  4797. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  4798. elif kind == 'travel':
  4799. if geo['kind'][0] == 'T':
  4800. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  4801. visible=visible, layer=2)
  4802. elif kind == 'cut':
  4803. if geo['kind'][0] == 'C':
  4804. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  4805. visible=visible, layer=1)
  4806. else:
  4807. # For Incremental coordinates type G91
  4808. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  4809. for geo in gcode_parsed:
  4810. if geo['kind'][0] == 'T':
  4811. current_position = geo['geom'].coords[0]
  4812. if current_position not in pos:
  4813. pos.append(current_position)
  4814. path_num += 1
  4815. text.append(str(path_num))
  4816. current_position = geo['geom'].coords[-1]
  4817. if current_position not in pos:
  4818. pos.append(current_position)
  4819. path_num += 1
  4820. text.append(str(path_num))
  4821. # plot the geometry of Excellon objects
  4822. if self.origin_kind == 'excellon':
  4823. try:
  4824. poly = Polygon(geo['geom'])
  4825. except ValueError:
  4826. # if the geos are travel lines it will enter into Exception
  4827. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  4828. poly = poly.simplify(tool_tolerance)
  4829. else:
  4830. # plot the geometry of any objects other than Excellon
  4831. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  4832. poly = poly.simplify(tool_tolerance)
  4833. if kind == 'all':
  4834. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  4835. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  4836. elif kind == 'travel':
  4837. if geo['kind'][0] == 'T':
  4838. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  4839. visible=visible, layer=2)
  4840. elif kind == 'cut':
  4841. if geo['kind'][0] == 'C':
  4842. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  4843. visible=visible, layer=1)
  4844. try:
  4845. if self.app.defaults['global_theme'] == 'white':
  4846. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  4847. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  4848. color=self.app.defaults["cncjob_annotation_fontcolor"])
  4849. else:
  4850. # invert the color
  4851. old_color = self.app.defaults["cncjob_annotation_fontcolor"].lower()
  4852. new_color = ''
  4853. code = {}
  4854. l1 = "#;0123456789abcdef"
  4855. l2 = "#;fedcba9876543210"
  4856. for i in range(len(l1)):
  4857. code[l1[i]] = l2[i]
  4858. for x in range(len(old_color)):
  4859. new_color += code[old_color[x]]
  4860. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  4861. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  4862. color=new_color)
  4863. except Exception as e:
  4864. log.debug("CNCJob.plot2() --> annotations --> %s" % str(e))
  4865. def create_geometry(self):
  4866. """
  4867. It is used by the Excellon objects. Will create the solid_geometry which will be an attribute of the
  4868. Excellon object class.
  4869. :return: List of Shapely geometry elements
  4870. :rtype: list
  4871. """
  4872. # TODO: This takes forever. Too much data?
  4873. # self.app.inform.emit('%s: %s' % (_("Unifying Geometry from parsed Geometry segments"),
  4874. # str(len(self.gcode_parsed))))
  4875. # self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  4876. # This is much faster but not so nice to look at as you can see different segments of the geometry
  4877. self.solid_geometry = [geo['geom'] for geo in self.gcode_parsed]
  4878. return self.solid_geometry
  4879. def segment(self, coords):
  4880. """
  4881. Break long linear lines to make it more auto level friendly.
  4882. Code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  4883. :param coords: List of coordinates tuples
  4884. :type coords: list
  4885. :return: A path; list with the multiple coordinates breaking a line.
  4886. :rtype: list
  4887. """
  4888. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  4889. return list(coords)
  4890. path = [coords[0]]
  4891. # break the line in either x or y dimension only
  4892. def linebreak_single(line, dim, dmax):
  4893. if dmax <= 0:
  4894. return None
  4895. if line[1][dim] > line[0][dim]:
  4896. sign = 1.0
  4897. d = line[1][dim] - line[0][dim]
  4898. else:
  4899. sign = -1.0
  4900. d = line[0][dim] - line[1][dim]
  4901. if d > dmax:
  4902. # make sure we don't make any new lines too short
  4903. if d > dmax * 2:
  4904. dd = dmax
  4905. else:
  4906. dd = d / 2
  4907. other = dim ^ 1
  4908. return (line[0][dim] + dd * sign, line[0][other] + \
  4909. dd * (line[1][other] - line[0][other]) / d)
  4910. return None
  4911. # recursively breaks down a given line until it is within the
  4912. # required step size
  4913. def linebreak(line):
  4914. pt_new = linebreak_single(line, 0, self.segx)
  4915. if pt_new is None:
  4916. pt_new2 = linebreak_single(line, 1, self.segy)
  4917. else:
  4918. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  4919. if pt_new2 is not None:
  4920. pt_new = pt_new2[::-1]
  4921. if pt_new is None:
  4922. path.append(line[1])
  4923. else:
  4924. path.append(pt_new)
  4925. linebreak((pt_new, line[1]))
  4926. for pt in coords[1:]:
  4927. linebreak((path[-1], pt))
  4928. return path
  4929. def linear2gcode(self, linear, dia, tolerance=0, down=True, up=True, z_cut=None, z_move=None, zdownrate=None,
  4930. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  4931. """
  4932. Generates G-code to cut along the linear feature.
  4933. :param linear: The path to cut along.
  4934. :type: Shapely.LinearRing or Shapely.Linear String
  4935. :param dia: The tool diameter that is going on the path
  4936. :type dia: float
  4937. :param tolerance: All points in the simplified object will be within the
  4938. tolerance distance of the original geometry.
  4939. :type tolerance: float
  4940. :param down:
  4941. :param up:
  4942. :param z_cut:
  4943. :param z_move:
  4944. :param zdownrate:
  4945. :param feedrate: speed for cut on X - Y plane
  4946. :param feedrate_z: speed for cut on Z plane
  4947. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  4948. :param cont:
  4949. :param old_point:
  4950. :return: G-code to cut along the linear feature.
  4951. """
  4952. if z_cut is None:
  4953. z_cut = self.z_cut
  4954. if z_move is None:
  4955. z_move = self.z_move
  4956. #
  4957. # if zdownrate is None:
  4958. # zdownrate = self.zdownrate
  4959. if feedrate is None:
  4960. feedrate = self.feedrate
  4961. if feedrate_z is None:
  4962. feedrate_z = self.z_feedrate
  4963. if feedrate_rapid is None:
  4964. feedrate_rapid = self.feedrate_rapid
  4965. # Simplify paths?
  4966. if tolerance > 0:
  4967. target_linear = linear.simplify(tolerance)
  4968. else:
  4969. target_linear = linear
  4970. gcode = ""
  4971. # path = list(target_linear.coords)
  4972. path = self.segment(target_linear.coords)
  4973. p = self.pp_geometry
  4974. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  4975. if self.coordinates_type == "G90":
  4976. # For Absolute coordinates type G90
  4977. first_x = path[0][0]
  4978. first_y = path[0][1]
  4979. else:
  4980. # For Incremental coordinates type G91
  4981. first_x = path[0][0] - old_point[0]
  4982. first_y = path[0][1] - old_point[1]
  4983. # Move fast to 1st point
  4984. if not cont:
  4985. current_tooldia = dia
  4986. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  4987. end_point=(first_x, first_y),
  4988. tooldia=current_tooldia)
  4989. prev_z = None
  4990. for travel in travels:
  4991. locx = travel[1][0]
  4992. locy = travel[1][1]
  4993. if travel[0] is not None:
  4994. # move to next point
  4995. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  4996. # raise to safe Z (travel[0]) each time because safe Z may be different
  4997. self.z_move = travel[0]
  4998. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  4999. # restore z_move
  5000. self.z_move = z_move
  5001. else:
  5002. if prev_z is not None:
  5003. # move to next point
  5004. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5005. # we assume that previously the z_move was altered therefore raise to
  5006. # the travel_z (z_move)
  5007. self.z_move = z_move
  5008. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5009. else:
  5010. # move to next point
  5011. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5012. # store prev_z
  5013. prev_z = travel[0]
  5014. # gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5015. # Move down to cutting depth
  5016. if down:
  5017. # Different feedrate for vertical cut?
  5018. gcode += self.doformat(p.z_feedrate_code)
  5019. # gcode += self.doformat(p.feedrate_code)
  5020. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  5021. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5022. # Cutting...
  5023. prev_x = first_x
  5024. prev_y = first_y
  5025. for pt in path[1:]:
  5026. if self.app.abort_flag:
  5027. # graceful abort requested by the user
  5028. raise grace
  5029. if self.coordinates_type == "G90":
  5030. # For Absolute coordinates type G90
  5031. next_x = pt[0]
  5032. next_y = pt[1]
  5033. else:
  5034. # For Incremental coordinates type G91
  5035. # next_x = pt[0] - prev_x
  5036. # next_y = pt[1] - prev_y
  5037. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  5038. next_x = pt[0]
  5039. next_y = pt[1]
  5040. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  5041. prev_x = pt[0]
  5042. prev_y = pt[1]
  5043. # Up to travelling height.
  5044. if up:
  5045. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # Stop cutting
  5046. return gcode
  5047. def linear2gcode_extra(self, linear, dia, extracut_length, tolerance=0, down=True, up=True,
  5048. z_cut=None, z_move=None, zdownrate=None,
  5049. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  5050. """
  5051. Generates G-code to cut along the linear feature.
  5052. :param linear: The path to cut along.
  5053. :type: Shapely.LinearRing or Shapely.Linear String
  5054. :param dia: The tool diameter that is going on the path
  5055. :type dia: float
  5056. :param extracut_length: how much to cut extra over the first point at the end of the path
  5057. :param tolerance: All points in the simplified object will be within the
  5058. tolerance distance of the original geometry.
  5059. :type tolerance: float
  5060. :param down:
  5061. :param up:
  5062. :param z_cut:
  5063. :param z_move:
  5064. :param zdownrate:
  5065. :param feedrate: speed for cut on X - Y plane
  5066. :param feedrate_z: speed for cut on Z plane
  5067. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5068. :param cont:
  5069. :param old_point:
  5070. :return: G-code to cut along the linear feature.
  5071. :rtype: str
  5072. """
  5073. if z_cut is None:
  5074. z_cut = self.z_cut
  5075. if z_move is None:
  5076. z_move = self.z_move
  5077. #
  5078. # if zdownrate is None:
  5079. # zdownrate = self.zdownrate
  5080. if feedrate is None:
  5081. feedrate = self.feedrate
  5082. if feedrate_z is None:
  5083. feedrate_z = self.z_feedrate
  5084. if feedrate_rapid is None:
  5085. feedrate_rapid = self.feedrate_rapid
  5086. # Simplify paths?
  5087. if tolerance > 0:
  5088. target_linear = linear.simplify(tolerance)
  5089. else:
  5090. target_linear = linear
  5091. gcode = ""
  5092. path = list(target_linear.coords)
  5093. p = self.pp_geometry
  5094. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5095. if self.coordinates_type == "G90":
  5096. # For Absolute coordinates type G90
  5097. first_x = path[0][0]
  5098. first_y = path[0][1]
  5099. else:
  5100. # For Incremental coordinates type G91
  5101. first_x = path[0][0] - old_point[0]
  5102. first_y = path[0][1] - old_point[1]
  5103. # Move fast to 1st point
  5104. if not cont:
  5105. current_tooldia = dia
  5106. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  5107. end_point=(first_x, first_y),
  5108. tooldia=current_tooldia)
  5109. prev_z = None
  5110. for travel in travels:
  5111. locx = travel[1][0]
  5112. locy = travel[1][1]
  5113. if travel[0] is not None:
  5114. # move to next point
  5115. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5116. # raise to safe Z (travel[0]) each time because safe Z may be different
  5117. self.z_move = travel[0]
  5118. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5119. # restore z_move
  5120. self.z_move = z_move
  5121. else:
  5122. if prev_z is not None:
  5123. # move to next point
  5124. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5125. # we assume that previously the z_move was altered therefore raise to
  5126. # the travel_z (z_move)
  5127. self.z_move = z_move
  5128. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5129. else:
  5130. # move to next point
  5131. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5132. # store prev_z
  5133. prev_z = travel[0]
  5134. # gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5135. # Move down to cutting depth
  5136. if down:
  5137. # Different feedrate for vertical cut?
  5138. if self.z_feedrate is not None:
  5139. gcode += self.doformat(p.z_feedrate_code)
  5140. # gcode += self.doformat(p.feedrate_code)
  5141. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  5142. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5143. else:
  5144. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut) # Start cutting
  5145. # Cutting...
  5146. prev_x = first_x
  5147. prev_y = first_y
  5148. for pt in path[1:]:
  5149. if self.app.abort_flag:
  5150. # graceful abort requested by the user
  5151. raise grace
  5152. if self.coordinates_type == "G90":
  5153. # For Absolute coordinates type G90
  5154. next_x = pt[0]
  5155. next_y = pt[1]
  5156. else:
  5157. # For Incremental coordinates type G91
  5158. # For Incremental coordinates type G91
  5159. # next_x = pt[0] - prev_x
  5160. # next_y = pt[1] - prev_y
  5161. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  5162. next_x = pt[0]
  5163. next_y = pt[1]
  5164. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  5165. prev_x = next_x
  5166. prev_y = next_y
  5167. # this line is added to create an extra cut over the first point in patch
  5168. # to make sure that we remove the copper leftovers
  5169. # Linear motion to the 1st point in the cut path
  5170. # if self.coordinates_type == "G90":
  5171. # # For Absolute coordinates type G90
  5172. # last_x = path[1][0]
  5173. # last_y = path[1][1]
  5174. # else:
  5175. # # For Incremental coordinates type G91
  5176. # last_x = path[1][0] - first_x
  5177. # last_y = path[1][1] - first_y
  5178. # gcode += self.doformat(p.linear_code, x=last_x, y=last_y)
  5179. # the first point for extracut is always mandatory if the extracut is enabled. But if the length of distance
  5180. # between point 0 and point 1 is more than the distance we set for the extra cut then make an interpolation
  5181. # along the path and find the point at the distance extracut_length
  5182. if extracut_length == 0.0:
  5183. extra_path = [path[-1], path[0], path[1]]
  5184. new_x = extra_path[0][0]
  5185. new_y = extra_path[0][1]
  5186. # this is an extra line therefore lift the milling bit
  5187. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # lift
  5188. # move fast to the new first point
  5189. gcode += self.doformat(p.rapid_code, x=new_x, y=new_y)
  5190. # lower the milling bit
  5191. # Different feedrate for vertical cut?
  5192. if self.z_feedrate is not None:
  5193. gcode += self.doformat(p.z_feedrate_code)
  5194. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut)
  5195. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5196. else:
  5197. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut) # Start cutting
  5198. # start cutting the extra line
  5199. last_pt = extra_path[0]
  5200. for pt in extra_path[1:]:
  5201. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5202. last_pt = pt
  5203. # go back to the original point
  5204. gcode += self.doformat(p.linear_code, x=path[0][0], y=path[0][1])
  5205. last_pt = path[0]
  5206. else:
  5207. # go to the point that is 5% in length before the end (therefore 95% length from start of the line),
  5208. # along the line to be cut
  5209. if extracut_length >= target_linear.length:
  5210. extracut_length = target_linear.length
  5211. # ---------------------------------------------
  5212. # first half
  5213. # ---------------------------------------------
  5214. start_length = target_linear.length - (extracut_length * 0.5)
  5215. extra_line = substring(target_linear, start_length, target_linear.length)
  5216. extra_path = list(extra_line.coords)
  5217. new_x = extra_path[0][0]
  5218. new_y = extra_path[0][1]
  5219. # this is an extra line therefore lift the milling bit
  5220. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # lift
  5221. # move fast to the new first point
  5222. gcode += self.doformat(p.rapid_code, x=new_x, y=new_y)
  5223. # lower the milling bit
  5224. # Different feedrate for vertical cut?
  5225. if self.z_feedrate is not None:
  5226. gcode += self.doformat(p.z_feedrate_code)
  5227. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut)
  5228. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5229. else:
  5230. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut) # Start cutting
  5231. # start cutting the extra line
  5232. for pt in extra_path[1:]:
  5233. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5234. # ---------------------------------------------
  5235. # second half
  5236. # ---------------------------------------------
  5237. extra_line = substring(target_linear, 0, (extracut_length * 0.5))
  5238. extra_path = list(extra_line.coords)
  5239. # start cutting the extra line
  5240. last_pt = extra_path[0]
  5241. for pt in extra_path[1:]:
  5242. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5243. last_pt = pt
  5244. # ---------------------------------------------
  5245. # back to original start point, cutting
  5246. # ---------------------------------------------
  5247. extra_line = substring(target_linear, 0, (extracut_length * 0.5))
  5248. extra_path = list(extra_line.coords)[::-1]
  5249. # start cutting the extra line
  5250. last_pt = extra_path[0]
  5251. for pt in extra_path[1:]:
  5252. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5253. last_pt = pt
  5254. # if extracut_length == 0.0:
  5255. # gcode += self.doformat(p.linear_code, x=path[1][0], y=path[1][1])
  5256. # last_pt = path[1]
  5257. # else:
  5258. # if abs(distance(path[1], path[0])) > extracut_length:
  5259. # i_point = LineString([path[0], path[1]]).interpolate(extracut_length)
  5260. # gcode += self.doformat(p.linear_code, x=i_point.x, y=i_point.y)
  5261. # last_pt = (i_point.x, i_point.y)
  5262. # else:
  5263. # last_pt = path[0]
  5264. # for pt in path[1:]:
  5265. # extracut_distance = abs(distance(pt, last_pt))
  5266. # if extracut_distance <= extracut_length:
  5267. # gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5268. # last_pt = pt
  5269. # else:
  5270. # break
  5271. # Up to travelling height.
  5272. if up:
  5273. gcode += self.doformat(p.lift_code, x=last_pt[0], y=last_pt[1], z_move=z_move) # Stop cutting
  5274. return gcode
  5275. def point2gcode(self, point, dia, z_move=None, old_point=(0, 0)):
  5276. """
  5277. :param point: A Shapely Point
  5278. :type point: Point
  5279. :param dia: The tool diameter that is going on the path
  5280. :type dia: float
  5281. :param z_move: Travel Z
  5282. :type z_move: float
  5283. :param old_point: Old point coordinates from which we moved to the 'point'
  5284. :type old_point: tuple
  5285. :return: G-code to cut on the Point feature.
  5286. :rtype: str
  5287. """
  5288. gcode = ""
  5289. if self.app.abort_flag:
  5290. # graceful abort requested by the user
  5291. raise grace
  5292. path = list(point.coords)
  5293. p = self.pp_geometry
  5294. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5295. if self.coordinates_type == "G90":
  5296. # For Absolute coordinates type G90
  5297. first_x = path[0][0]
  5298. first_y = path[0][1]
  5299. else:
  5300. # For Incremental coordinates type G91
  5301. # first_x = path[0][0] - old_point[0]
  5302. # first_y = path[0][1] - old_point[1]
  5303. self.app.inform.emit('[ERROR_NOTCL] %s' %
  5304. _('G91 coordinates not implemented ...'))
  5305. first_x = path[0][0]
  5306. first_y = path[0][1]
  5307. current_tooldia = dia
  5308. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  5309. end_point=(first_x, first_y),
  5310. tooldia=current_tooldia)
  5311. prev_z = None
  5312. for travel in travels:
  5313. locx = travel[1][0]
  5314. locy = travel[1][1]
  5315. if travel[0] is not None:
  5316. # move to next point
  5317. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5318. # raise to safe Z (travel[0]) each time because safe Z may be different
  5319. self.z_move = travel[0]
  5320. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5321. # restore z_move
  5322. self.z_move = z_move
  5323. else:
  5324. if prev_z is not None:
  5325. # move to next point
  5326. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5327. # we assume that previously the z_move was altered therefore raise to
  5328. # the travel_z (z_move)
  5329. self.z_move = z_move
  5330. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5331. else:
  5332. # move to next point
  5333. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5334. # store prev_z
  5335. prev_z = travel[0]
  5336. # gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  5337. if self.z_feedrate is not None:
  5338. gcode += self.doformat(p.z_feedrate_code)
  5339. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=self.z_cut)
  5340. gcode += self.doformat(p.feedrate_code)
  5341. else:
  5342. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=self.z_cut) # Start cutting
  5343. gcode += self.doformat(p.lift_code, x=first_x, y=first_y) # Stop cutting
  5344. return gcode
  5345. def export_svg(self, scale_stroke_factor=0.00):
  5346. """
  5347. Exports the CNC Job as a SVG Element
  5348. :param scale_stroke_factor: A factor to scale the SVG geometry
  5349. :type scale_stroke_factor: float
  5350. :return: SVG Element string
  5351. :rtype: str
  5352. """
  5353. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  5354. # If not specified then try and use the tool diameter
  5355. # This way what is on screen will match what is outputed for the svg
  5356. # This is quite a useful feature for svg's used with visicut
  5357. if scale_stroke_factor <= 0:
  5358. scale_stroke_factor = self.options['tooldia'] / 2
  5359. # If still 0 then default to 0.05
  5360. # This value appears to work for zooming, and getting the output svg line width
  5361. # to match that viewed on screen with FlatCam
  5362. if scale_stroke_factor == 0:
  5363. scale_stroke_factor = 0.01
  5364. # Separate the list of cuts and travels into 2 distinct lists
  5365. # This way we can add different formatting / colors to both
  5366. cuts = []
  5367. travels = []
  5368. cutsgeom = ''
  5369. travelsgeom = ''
  5370. for g in self.gcode_parsed:
  5371. if self.app.abort_flag:
  5372. # graceful abort requested by the user
  5373. raise grace
  5374. if g['kind'][0] == 'C':
  5375. cuts.append(g)
  5376. if g['kind'][0] == 'T':
  5377. travels.append(g)
  5378. # Used to determine the overall board size
  5379. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  5380. # Convert the cuts and travels into single geometry objects we can render as svg xml
  5381. if travels:
  5382. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  5383. if self.app.abort_flag:
  5384. # graceful abort requested by the user
  5385. raise grace
  5386. if cuts:
  5387. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  5388. # Render the SVG Xml
  5389. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  5390. # It's better to have the travels sitting underneath the cuts for visicut
  5391. svg_elem = ""
  5392. if travels:
  5393. svg_elem = travelsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#F0E24D")
  5394. if cuts:
  5395. svg_elem += cutsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#5E6CFF")
  5396. return svg_elem
  5397. def bounds(self, flatten=None):
  5398. """
  5399. Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  5400. :param flatten: Not used, it is here for compatibility with base class method
  5401. :type flatten: bool
  5402. :return: Bounding values in format (xmin, ymin, xmax, ymax)
  5403. :rtype: tuple
  5404. """
  5405. log.debug("camlib.CNCJob.bounds()")
  5406. def bounds_rec(obj):
  5407. if type(obj) is list:
  5408. cminx = np.Inf
  5409. cminy = np.Inf
  5410. cmaxx = -np.Inf
  5411. cmaxy = -np.Inf
  5412. for k in obj:
  5413. if type(k) is dict:
  5414. for key in k:
  5415. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  5416. cminx = min(cminx, minx_)
  5417. cminy = min(cminy, miny_)
  5418. cmaxx = max(cmaxx, maxx_)
  5419. cmaxy = max(cmaxy, maxy_)
  5420. else:
  5421. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  5422. cminx = min(cminx, minx_)
  5423. cminy = min(cminy, miny_)
  5424. cmaxx = max(cmaxx, maxx_)
  5425. cmaxy = max(cmaxy, maxy_)
  5426. return cminx, cminy, cmaxx, cmaxy
  5427. else:
  5428. # it's a Shapely object, return it's bounds
  5429. return obj.bounds
  5430. if self.multitool is False:
  5431. log.debug("CNCJob->bounds()")
  5432. if self.solid_geometry is None:
  5433. log.debug("solid_geometry is None")
  5434. return 0, 0, 0, 0
  5435. bounds_coords = bounds_rec(self.solid_geometry)
  5436. else:
  5437. minx = np.Inf
  5438. miny = np.Inf
  5439. maxx = -np.Inf
  5440. maxy = -np.Inf
  5441. for k, v in self.cnc_tools.items():
  5442. minx = np.Inf
  5443. miny = np.Inf
  5444. maxx = -np.Inf
  5445. maxy = -np.Inf
  5446. try:
  5447. for k in v['solid_geometry']:
  5448. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  5449. minx = min(minx, minx_)
  5450. miny = min(miny, miny_)
  5451. maxx = max(maxx, maxx_)
  5452. maxy = max(maxy, maxy_)
  5453. except TypeError:
  5454. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  5455. minx = min(minx, minx_)
  5456. miny = min(miny, miny_)
  5457. maxx = max(maxx, maxx_)
  5458. maxy = max(maxy, maxy_)
  5459. bounds_coords = minx, miny, maxx, maxy
  5460. return bounds_coords
  5461. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  5462. def scale(self, xfactor, yfactor=None, point=None):
  5463. """
  5464. Scales all the geometry on the XY plane in the object by the
  5465. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  5466. not altered.
  5467. :param factor: Number by which to scale the object.
  5468. :type factor: float
  5469. :param point: the (x,y) coords for the point of origin of scale
  5470. :type tuple of floats
  5471. :return: None
  5472. :rtype: None
  5473. """
  5474. log.debug("camlib.CNCJob.scale()")
  5475. if yfactor is None:
  5476. yfactor = xfactor
  5477. if point is None:
  5478. px = 0
  5479. py = 0
  5480. else:
  5481. px, py = point
  5482. def scale_g(g):
  5483. """
  5484. :param g: 'g' parameter it's a gcode string
  5485. :return: scaled gcode string
  5486. """
  5487. temp_gcode = ''
  5488. header_start = False
  5489. header_stop = False
  5490. units = self.app.defaults['units'].upper()
  5491. lines = StringIO(g)
  5492. for line in lines:
  5493. # this changes the GCODE header ---- UGLY HACK
  5494. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  5495. header_start = True
  5496. if "G20" in line or "G21" in line:
  5497. header_start = False
  5498. header_stop = True
  5499. if header_start is True:
  5500. header_stop = False
  5501. if "in" in line:
  5502. if units == 'MM':
  5503. line = line.replace("in", "mm")
  5504. if "mm" in line:
  5505. if units == 'IN':
  5506. line = line.replace("mm", "in")
  5507. # find any float number in header (even multiple on the same line) and convert it
  5508. numbers_in_header = re.findall(self.g_nr_re, line)
  5509. if numbers_in_header:
  5510. for nr in numbers_in_header:
  5511. new_nr = float(nr) * xfactor
  5512. # replace the updated string
  5513. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  5514. )
  5515. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  5516. if header_stop is True:
  5517. if "G20" in line:
  5518. if units == 'MM':
  5519. line = line.replace("G20", "G21")
  5520. if "G21" in line:
  5521. if units == 'IN':
  5522. line = line.replace("G21", "G20")
  5523. # find the X group
  5524. match_x = self.g_x_re.search(line)
  5525. if match_x:
  5526. if match_x.group(1) is not None:
  5527. new_x = float(match_x.group(1)[1:]) * xfactor
  5528. # replace the updated string
  5529. line = line.replace(
  5530. match_x.group(1),
  5531. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  5532. )
  5533. # find the Y group
  5534. match_y = self.g_y_re.search(line)
  5535. if match_y:
  5536. if match_y.group(1) is not None:
  5537. new_y = float(match_y.group(1)[1:]) * yfactor
  5538. line = line.replace(
  5539. match_y.group(1),
  5540. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  5541. )
  5542. # find the Z group
  5543. match_z = self.g_z_re.search(line)
  5544. if match_z:
  5545. if match_z.group(1) is not None:
  5546. new_z = float(match_z.group(1)[1:]) * xfactor
  5547. line = line.replace(
  5548. match_z.group(1),
  5549. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  5550. )
  5551. # find the F group
  5552. match_f = self.g_f_re.search(line)
  5553. if match_f:
  5554. if match_f.group(1) is not None:
  5555. new_f = float(match_f.group(1)[1:]) * xfactor
  5556. line = line.replace(
  5557. match_f.group(1),
  5558. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  5559. )
  5560. # find the T group (tool dia on toolchange)
  5561. match_t = self.g_t_re.search(line)
  5562. if match_t:
  5563. if match_t.group(1) is not None:
  5564. new_t = float(match_t.group(1)[1:]) * xfactor
  5565. line = line.replace(
  5566. match_t.group(1),
  5567. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  5568. )
  5569. temp_gcode += line
  5570. lines.close()
  5571. header_stop = False
  5572. return temp_gcode
  5573. if self.multitool is False:
  5574. # offset Gcode
  5575. self.gcode = scale_g(self.gcode)
  5576. # variables to display the percentage of work done
  5577. self.geo_len = 0
  5578. try:
  5579. self.geo_len = len(self.gcode_parsed)
  5580. except TypeError:
  5581. self.geo_len = 1
  5582. self.old_disp_number = 0
  5583. self.el_count = 0
  5584. # scale geometry
  5585. for g in self.gcode_parsed:
  5586. try:
  5587. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  5588. except AttributeError:
  5589. return g['geom']
  5590. self.el_count += 1
  5591. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5592. if self.old_disp_number < disp_number <= 100:
  5593. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5594. self.old_disp_number = disp_number
  5595. self.create_geometry()
  5596. else:
  5597. for k, v in self.cnc_tools.items():
  5598. # scale Gcode
  5599. v['gcode'] = scale_g(v['gcode'])
  5600. # variables to display the percentage of work done
  5601. self.geo_len = 0
  5602. try:
  5603. self.geo_len = len(v['gcode_parsed'])
  5604. except TypeError:
  5605. self.geo_len = 1
  5606. self.old_disp_number = 0
  5607. self.el_count = 0
  5608. # scale gcode_parsed
  5609. for g in v['gcode_parsed']:
  5610. try:
  5611. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  5612. except AttributeError:
  5613. return g['geom']
  5614. self.el_count += 1
  5615. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5616. if self.old_disp_number < disp_number <= 100:
  5617. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5618. self.old_disp_number = disp_number
  5619. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  5620. self.create_geometry()
  5621. self.app.proc_container.new_text = ''
  5622. def offset(self, vect):
  5623. """
  5624. Offsets all the geometry on the XY plane in the object by the
  5625. given vector.
  5626. Offsets all the GCODE on the XY plane in the object by the
  5627. given vector.
  5628. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  5629. :param vect: (x, y) offset vector.
  5630. :type vect: tuple
  5631. :return: None
  5632. """
  5633. log.debug("camlib.CNCJob.offset()")
  5634. dx, dy = vect
  5635. def offset_g(g):
  5636. """
  5637. :param g: 'g' parameter it's a gcode string
  5638. :return: offseted gcode string
  5639. """
  5640. temp_gcode = ''
  5641. lines = StringIO(g)
  5642. for line in lines:
  5643. # find the X group
  5644. match_x = self.g_x_re.search(line)
  5645. if match_x:
  5646. if match_x.group(1) is not None:
  5647. # get the coordinate and add X offset
  5648. new_x = float(match_x.group(1)[1:]) + dx
  5649. # replace the updated string
  5650. line = line.replace(
  5651. match_x.group(1),
  5652. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  5653. )
  5654. match_y = self.g_y_re.search(line)
  5655. if match_y:
  5656. if match_y.group(1) is not None:
  5657. new_y = float(match_y.group(1)[1:]) + dy
  5658. line = line.replace(
  5659. match_y.group(1),
  5660. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  5661. )
  5662. temp_gcode += line
  5663. lines.close()
  5664. return temp_gcode
  5665. if self.multitool is False:
  5666. # offset Gcode
  5667. self.gcode = offset_g(self.gcode)
  5668. # variables to display the percentage of work done
  5669. self.geo_len = 0
  5670. try:
  5671. self.geo_len = len(self.gcode_parsed)
  5672. except TypeError:
  5673. self.geo_len = 1
  5674. self.old_disp_number = 0
  5675. self.el_count = 0
  5676. # offset geometry
  5677. for g in self.gcode_parsed:
  5678. try:
  5679. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  5680. except AttributeError:
  5681. return g['geom']
  5682. self.el_count += 1
  5683. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5684. if self.old_disp_number < disp_number <= 100:
  5685. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5686. self.old_disp_number = disp_number
  5687. self.create_geometry()
  5688. else:
  5689. for k, v in self.cnc_tools.items():
  5690. # offset Gcode
  5691. v['gcode'] = offset_g(v['gcode'])
  5692. # variables to display the percentage of work done
  5693. self.geo_len = 0
  5694. try:
  5695. self.geo_len = len(v['gcode_parsed'])
  5696. except TypeError:
  5697. self.geo_len = 1
  5698. self.old_disp_number = 0
  5699. self.el_count = 0
  5700. # offset gcode_parsed
  5701. for g in v['gcode_parsed']:
  5702. try:
  5703. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  5704. except AttributeError:
  5705. return g['geom']
  5706. self.el_count += 1
  5707. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5708. if self.old_disp_number < disp_number <= 100:
  5709. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5710. self.old_disp_number = disp_number
  5711. # for the bounding box
  5712. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  5713. self.app.proc_container.new_text = ''
  5714. def mirror(self, axis, point):
  5715. """
  5716. Mirror the geometry of an object by an given axis around the coordinates of the 'point'
  5717. :param axis: Axis for Mirror
  5718. :param point: tuple of coordinates (x,y). Point of origin for Mirror
  5719. :return:
  5720. """
  5721. log.debug("camlib.CNCJob.mirror()")
  5722. px, py = point
  5723. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  5724. # variables to display the percentage of work done
  5725. self.geo_len = 0
  5726. try:
  5727. self.geo_len = len(self.gcode_parsed)
  5728. except TypeError:
  5729. self.geo_len = 1
  5730. self.old_disp_number = 0
  5731. self.el_count = 0
  5732. for g in self.gcode_parsed:
  5733. try:
  5734. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  5735. except AttributeError:
  5736. return g['geom']
  5737. self.el_count += 1
  5738. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5739. if self.old_disp_number < disp_number <= 100:
  5740. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5741. self.old_disp_number = disp_number
  5742. self.create_geometry()
  5743. self.app.proc_container.new_text = ''
  5744. def skew(self, angle_x, angle_y, point):
  5745. """
  5746. Shear/Skew the geometries of an object by angles along x and y dimensions.
  5747. :param angle_x:
  5748. :param angle_y:
  5749. angle_x, angle_y : float, float
  5750. The shear angle(s) for the x and y axes respectively. These can be
  5751. specified in either degrees (default) or radians by setting
  5752. use_radians=True.
  5753. :param point: tupple of coordinates (x,y)
  5754. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  5755. """
  5756. log.debug("camlib.CNCJob.skew()")
  5757. px, py = point
  5758. # variables to display the percentage of work done
  5759. self.geo_len = 0
  5760. try:
  5761. self.geo_len = len(self.gcode_parsed)
  5762. except TypeError:
  5763. self.geo_len = 1
  5764. self.old_disp_number = 0
  5765. self.el_count = 0
  5766. for g in self.gcode_parsed:
  5767. try:
  5768. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y, origin=(px, py))
  5769. except AttributeError:
  5770. return g['geom']
  5771. self.el_count += 1
  5772. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5773. if self.old_disp_number < disp_number <= 100:
  5774. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5775. self.old_disp_number = disp_number
  5776. self.create_geometry()
  5777. self.app.proc_container.new_text = ''
  5778. def rotate(self, angle, point):
  5779. """
  5780. Rotate the geometry of an object by an given angle around the coordinates of the 'point'
  5781. :param angle: Angle of Rotation
  5782. :param point: tuple of coordinates (x,y). Origin point for Rotation
  5783. :return:
  5784. """
  5785. log.debug("camlib.CNCJob.rotate()")
  5786. px, py = point
  5787. # variables to display the percentage of work done
  5788. self.geo_len = 0
  5789. try:
  5790. self.geo_len = len(self.gcode_parsed)
  5791. except TypeError:
  5792. self.geo_len = 1
  5793. self.old_disp_number = 0
  5794. self.el_count = 0
  5795. for g in self.gcode_parsed:
  5796. try:
  5797. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  5798. except AttributeError:
  5799. return g['geom']
  5800. self.el_count += 1
  5801. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5802. if self.old_disp_number < disp_number <= 100:
  5803. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5804. self.old_disp_number = disp_number
  5805. self.create_geometry()
  5806. self.app.proc_container.new_text = ''
  5807. def get_bounds(geometry_list):
  5808. """
  5809. Will return limit values for a list of geometries
  5810. :param geometry_list: List of geometries for which to calculate the bounds limits
  5811. :return:
  5812. """
  5813. xmin = np.Inf
  5814. ymin = np.Inf
  5815. xmax = -np.Inf
  5816. ymax = -np.Inf
  5817. for gs in geometry_list:
  5818. try:
  5819. gxmin, gymin, gxmax, gymax = gs.bounds()
  5820. xmin = min([xmin, gxmin])
  5821. ymin = min([ymin, gymin])
  5822. xmax = max([xmax, gxmax])
  5823. ymax = max([ymax, gymax])
  5824. except Exception:
  5825. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  5826. return [xmin, ymin, xmax, ymax]
  5827. def arc(center, radius, start, stop, direction, steps_per_circ):
  5828. """
  5829. Creates a list of point along the specified arc.
  5830. :param center: Coordinates of the center [x, y]
  5831. :type center: list
  5832. :param radius: Radius of the arc.
  5833. :type radius: float
  5834. :param start: Starting angle in radians
  5835. :type start: float
  5836. :param stop: End angle in radians
  5837. :type stop: float
  5838. :param direction: Orientation of the arc, "CW" or "CCW"
  5839. :type direction: string
  5840. :param steps_per_circ: Number of straight line segments to
  5841. represent a circle.
  5842. :type steps_per_circ: int
  5843. :return: The desired arc, as list of tuples
  5844. :rtype: list
  5845. """
  5846. # TODO: Resolution should be established by maximum error from the exact arc.
  5847. da_sign = {"cw": -1.0, "ccw": 1.0}
  5848. points = []
  5849. if direction == "ccw" and stop <= start:
  5850. stop += 2 * np.pi
  5851. if direction == "cw" and stop >= start:
  5852. stop -= 2 * np.pi
  5853. angle = abs(stop - start)
  5854. # angle = stop-start
  5855. steps = max([int(np.ceil(angle / (2 * np.pi) * steps_per_circ)), 2])
  5856. delta_angle = da_sign[direction] * angle * 1.0 / steps
  5857. for i in range(steps + 1):
  5858. theta = start + delta_angle * i
  5859. points.append((center[0] + radius * np.cos(theta), center[1] + radius * np.sin(theta)))
  5860. return points
  5861. def arc2(p1, p2, center, direction, steps_per_circ):
  5862. r = np.sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  5863. start = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  5864. stop = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  5865. return arc(center, r, start, stop, direction, steps_per_circ)
  5866. def arc_angle(start, stop, direction):
  5867. if direction == "ccw" and stop <= start:
  5868. stop += 2 * np.pi
  5869. if direction == "cw" and stop >= start:
  5870. stop -= 2 * np.pi
  5871. angle = abs(stop - start)
  5872. return angle
  5873. # def find_polygon(poly, point):
  5874. # """
  5875. # Find an object that object.contains(Point(point)) in
  5876. # poly, which can can be iterable, contain iterable of, or
  5877. # be itself an implementer of .contains().
  5878. #
  5879. # :param poly: See description
  5880. # :return: Polygon containing point or None.
  5881. # """
  5882. #
  5883. # if poly is None:
  5884. # return None
  5885. #
  5886. # try:
  5887. # for sub_poly in poly:
  5888. # p = find_polygon(sub_poly, point)
  5889. # if p is not None:
  5890. # return p
  5891. # except TypeError:
  5892. # try:
  5893. # if poly.contains(Point(point)):
  5894. # return poly
  5895. # except AttributeError:
  5896. # return None
  5897. #
  5898. # return None
  5899. def to_dict(obj):
  5900. """
  5901. Makes the following types into serializable form:
  5902. * ApertureMacro
  5903. * BaseGeometry
  5904. :param obj: Shapely geometry.
  5905. :type obj: BaseGeometry
  5906. :return: Dictionary with serializable form if ``obj`` was
  5907. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  5908. """
  5909. if isinstance(obj, ApertureMacro):
  5910. return {
  5911. "__class__": "ApertureMacro",
  5912. "__inst__": obj.to_dict()
  5913. }
  5914. if isinstance(obj, BaseGeometry):
  5915. return {
  5916. "__class__": "Shply",
  5917. "__inst__": sdumps(obj)
  5918. }
  5919. return obj
  5920. def dict2obj(d):
  5921. """
  5922. Default deserializer.
  5923. :param d: Serializable dictionary representation of an object
  5924. to be reconstructed.
  5925. :return: Reconstructed object.
  5926. """
  5927. if '__class__' in d and '__inst__' in d:
  5928. if d['__class__'] == "Shply":
  5929. return sloads(d['__inst__'])
  5930. if d['__class__'] == "ApertureMacro":
  5931. am = ApertureMacro()
  5932. am.from_dict(d['__inst__'])
  5933. return am
  5934. return d
  5935. else:
  5936. return d
  5937. # def plotg(geo, solid_poly=False, color="black"):
  5938. # try:
  5939. # __ = iter(geo)
  5940. # except:
  5941. # geo = [geo]
  5942. #
  5943. # for g in geo:
  5944. # if type(g) == Polygon:
  5945. # if solid_poly:
  5946. # patch = PolygonPatch(g,
  5947. # facecolor="#BBF268",
  5948. # edgecolor="#006E20",
  5949. # alpha=0.75,
  5950. # zorder=2)
  5951. # ax = subplot(111)
  5952. # ax.add_patch(patch)
  5953. # else:
  5954. # x, y = g.exterior.coords.xy
  5955. # plot(x, y, color=color)
  5956. # for ints in g.interiors:
  5957. # x, y = ints.coords.xy
  5958. # plot(x, y, color=color)
  5959. # continue
  5960. #
  5961. # if type(g) == LineString or type(g) == LinearRing:
  5962. # x, y = g.coords.xy
  5963. # plot(x, y, color=color)
  5964. # continue
  5965. #
  5966. # if type(g) == Point:
  5967. # x, y = g.coords.xy
  5968. # plot(x, y, 'o')
  5969. # continue
  5970. #
  5971. # try:
  5972. # __ = iter(g)
  5973. # plotg(g, color=color)
  5974. # except:
  5975. # log.error("Cannot plot: " + str(type(g)))
  5976. # continue
  5977. # def alpha_shape(points, alpha):
  5978. # """
  5979. # Compute the alpha shape (concave hull) of a set of points.
  5980. #
  5981. # @param points: Iterable container of points.
  5982. # @param alpha: alpha value to influence the gooeyness of the border. Smaller
  5983. # numbers don't fall inward as much as larger numbers. Too large,
  5984. # and you lose everything!
  5985. # """
  5986. # if len(points) < 4:
  5987. # # When you have a triangle, there is no sense in computing an alpha
  5988. # # shape.
  5989. # return MultiPoint(list(points)).convex_hull
  5990. #
  5991. # def add_edge(edges, edge_points, coords, i, j):
  5992. # """Add a line between the i-th and j-th points, if not in the list already"""
  5993. # if (i, j) in edges or (j, i) in edges:
  5994. # # already added
  5995. # return
  5996. # edges.add( (i, j) )
  5997. # edge_points.append(coords[ [i, j] ])
  5998. #
  5999. # coords = np.array([point.coords[0] for point in points])
  6000. #
  6001. # tri = Delaunay(coords)
  6002. # edges = set()
  6003. # edge_points = []
  6004. # # loop over triangles:
  6005. # # ia, ib, ic = indices of corner points of the triangle
  6006. # for ia, ib, ic in tri.vertices:
  6007. # pa = coords[ia]
  6008. # pb = coords[ib]
  6009. # pc = coords[ic]
  6010. #
  6011. # # Lengths of sides of triangle
  6012. # a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  6013. # b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  6014. # c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  6015. #
  6016. # # Semiperimeter of triangle
  6017. # s = (a + b + c)/2.0
  6018. #
  6019. # # Area of triangle by Heron's formula
  6020. # area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  6021. # circum_r = a*b*c/(4.0*area)
  6022. #
  6023. # # Here's the radius filter.
  6024. # #print circum_r
  6025. # if circum_r < 1.0/alpha:
  6026. # add_edge(edges, edge_points, coords, ia, ib)
  6027. # add_edge(edges, edge_points, coords, ib, ic)
  6028. # add_edge(edges, edge_points, coords, ic, ia)
  6029. #
  6030. # m = MultiLineString(edge_points)
  6031. # triangles = list(polygonize(m))
  6032. # return cascaded_union(triangles), edge_points
  6033. # def voronoi(P):
  6034. # """
  6035. # Returns a list of all edges of the voronoi diagram for the given input points.
  6036. # """
  6037. # delauny = Delaunay(P)
  6038. # triangles = delauny.points[delauny.vertices]
  6039. #
  6040. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  6041. # long_lines_endpoints = []
  6042. #
  6043. # lineIndices = []
  6044. # for i, triangle in enumerate(triangles):
  6045. # circum_center = circum_centers[i]
  6046. # for j, neighbor in enumerate(delauny.neighbors[i]):
  6047. # if neighbor != -1:
  6048. # lineIndices.append((i, neighbor))
  6049. # else:
  6050. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  6051. # ps = np.array((ps[1], -ps[0]))
  6052. #
  6053. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  6054. # di = middle - triangle[j]
  6055. #
  6056. # ps /= np.linalg.norm(ps)
  6057. # di /= np.linalg.norm(di)
  6058. #
  6059. # if np.dot(di, ps) < 0.0:
  6060. # ps *= -1000.0
  6061. # else:
  6062. # ps *= 1000.0
  6063. #
  6064. # long_lines_endpoints.append(circum_center + ps)
  6065. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  6066. #
  6067. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  6068. #
  6069. # # filter out any duplicate lines
  6070. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  6071. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  6072. # lineIndicesUnique = np.unique(lineIndicesTupled)
  6073. #
  6074. # return vertices, lineIndicesUnique
  6075. #
  6076. #
  6077. # def triangle_csc(pts):
  6078. # rows, cols = pts.shape
  6079. #
  6080. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  6081. # [np.ones((1, rows)), np.zeros((1, 1))]])
  6082. #
  6083. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  6084. # x = np.linalg.solve(A,b)
  6085. # bary_coords = x[:-1]
  6086. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  6087. #
  6088. #
  6089. # def voronoi_cell_lines(points, vertices, lineIndices):
  6090. # """
  6091. # Returns a mapping from a voronoi cell to its edges.
  6092. #
  6093. # :param points: shape (m,2)
  6094. # :param vertices: shape (n,2)
  6095. # :param lineIndices: shape (o,2)
  6096. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  6097. # """
  6098. # kd = KDTree(points)
  6099. #
  6100. # cells = collections.defaultdict(list)
  6101. # for i1, i2 in lineIndices:
  6102. # v1, v2 = vertices[i1], vertices[i2]
  6103. # mid = (v1+v2)/2
  6104. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  6105. # cells[p1Idx].append((i1, i2))
  6106. # cells[p2Idx].append((i1, i2))
  6107. #
  6108. # return cells
  6109. #
  6110. #
  6111. # def voronoi_edges2polygons(cells):
  6112. # """
  6113. # Transforms cell edges into polygons.
  6114. #
  6115. # :param cells: as returned from voronoi_cell_lines
  6116. # :rtype: dict point index -> list of vertex indices which form a polygon
  6117. # """
  6118. #
  6119. # # first, close the outer cells
  6120. # for pIdx, lineIndices_ in cells.items():
  6121. # dangling_lines = []
  6122. # for i1, i2 in lineIndices_:
  6123. # p = (i1, i2)
  6124. # connections = filter(lambda k: p != k and
  6125. # (p[0] == k[0] or p[0] == k[1] or p[1] == k[0] or p[1] == k[1]), lineIndices_)
  6126. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and
  6127. # (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  6128. # assert 1 <= len(connections) <= 2
  6129. # if len(connections) == 1:
  6130. # dangling_lines.append((i1, i2))
  6131. # assert len(dangling_lines) in [0, 2]
  6132. # if len(dangling_lines) == 2:
  6133. # (i11, i12), (i21, i22) = dangling_lines
  6134. # s = (i11, i12)
  6135. # t = (i21, i22)
  6136. #
  6137. # # determine which line ends are unconnected
  6138. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  6139. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  6140. # i11Unconnected = len(connected) == 0
  6141. #
  6142. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  6143. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  6144. # i21Unconnected = len(connected) == 0
  6145. #
  6146. # startIdx = i11 if i11Unconnected else i12
  6147. # endIdx = i21 if i21Unconnected else i22
  6148. #
  6149. # cells[pIdx].append((startIdx, endIdx))
  6150. #
  6151. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  6152. # polys = {}
  6153. # for pIdx, lineIndices_ in cells.items():
  6154. # # get a directed graph which contains both directions and arbitrarily follow one of both
  6155. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  6156. # directedGraphMap = collections.defaultdict(list)
  6157. # for (i1, i2) in directedGraph:
  6158. # directedGraphMap[i1].append(i2)
  6159. # orderedEdges = []
  6160. # currentEdge = directedGraph[0]
  6161. # while len(orderedEdges) < len(lineIndices_):
  6162. # i1 = currentEdge[1]
  6163. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  6164. # nextEdge = (i1, i2)
  6165. # orderedEdges.append(nextEdge)
  6166. # currentEdge = nextEdge
  6167. #
  6168. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  6169. #
  6170. # return polys
  6171. #
  6172. #
  6173. # def voronoi_polygons(points):
  6174. # """
  6175. # Returns the voronoi polygon for each input point.
  6176. #
  6177. # :param points: shape (n,2)
  6178. # :rtype: list of n polygons where each polygon is an array of vertices
  6179. # """
  6180. # vertices, lineIndices = voronoi(points)
  6181. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  6182. # polys = voronoi_edges2polygons(cells)
  6183. # polylist = []
  6184. # for i in range(len(points)):
  6185. # poly = vertices[np.asarray(polys[i])]
  6186. # polylist.append(poly)
  6187. # return polylist
  6188. #
  6189. #
  6190. # class Zprofile:
  6191. # def __init__(self):
  6192. #
  6193. # # data contains lists of [x, y, z]
  6194. # self.data = []
  6195. #
  6196. # # Computed voronoi polygons (shapely)
  6197. # self.polygons = []
  6198. # pass
  6199. #
  6200. # # def plot_polygons(self):
  6201. # # axes = plt.subplot(1, 1, 1)
  6202. # #
  6203. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  6204. # #
  6205. # # for poly in self.polygons:
  6206. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  6207. # # axes.add_patch(p)
  6208. #
  6209. # def init_from_csv(self, filename):
  6210. # pass
  6211. #
  6212. # def init_from_string(self, zpstring):
  6213. # pass
  6214. #
  6215. # def init_from_list(self, zplist):
  6216. # self.data = zplist
  6217. #
  6218. # def generate_polygons(self):
  6219. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  6220. #
  6221. # def normalize(self, origin):
  6222. # pass
  6223. #
  6224. # def paste(self, path):
  6225. # """
  6226. # Return a list of dictionaries containing the parts of the original
  6227. # path and their z-axis offset.
  6228. # """
  6229. #
  6230. # # At most one region/polygon will contain the path
  6231. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  6232. #
  6233. # if len(containing) > 0:
  6234. # return [{"path": path, "z": self.data[containing[0]][2]}]
  6235. #
  6236. # # All region indexes that intersect with the path
  6237. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  6238. #
  6239. # return [{"path": path.intersection(self.polygons[i]),
  6240. # "z": self.data[i][2]} for i in crossing]
  6241. def autolist(obj):
  6242. try:
  6243. __ = iter(obj)
  6244. return obj
  6245. except TypeError:
  6246. return [obj]
  6247. def three_point_circle(p1, p2, p3):
  6248. """
  6249. Computes the center and radius of a circle from
  6250. 3 points on its circumference.
  6251. :param p1: Point 1
  6252. :param p2: Point 2
  6253. :param p3: Point 3
  6254. :return: center, radius
  6255. """
  6256. # Midpoints
  6257. a1 = (p1 + p2) / 2.0
  6258. a2 = (p2 + p3) / 2.0
  6259. # Normals
  6260. b1 = np.dot((p2 - p1), np.array([[0, -1], [1, 0]], dtype=np.float32))
  6261. b2 = np.dot((p3 - p2), np.array([[0, 1], [-1, 0]], dtype=np.float32))
  6262. # Params
  6263. try:
  6264. T = solve(np.transpose(np.array([-b1, b2])), a1 - a2)
  6265. except Exception as e:
  6266. log.debug("camlib.three_point_circle() --> %s" % str(e))
  6267. return
  6268. # Center
  6269. center = a1 + b1 * T[0]
  6270. # Radius
  6271. radius = np.linalg.norm(center - p1)
  6272. return center, radius, T[0]
  6273. def distance(pt1, pt2):
  6274. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  6275. def distance_euclidian(x1, y1, x2, y2):
  6276. return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  6277. class FlatCAMRTree(object):
  6278. """
  6279. Indexes geometry (Any object with "cooords" property containing
  6280. a list of tuples with x, y values). Objects are indexed by
  6281. all their points by default. To index by arbitrary points,
  6282. override self.points2obj.
  6283. """
  6284. def __init__(self):
  6285. # Python RTree Index
  6286. self.rti = rtindex.Index()
  6287. # ## Track object-point relationship
  6288. # Each is list of points in object.
  6289. self.obj2points = []
  6290. # Index is index in rtree, value is index of
  6291. # object in obj2points.
  6292. self.points2obj = []
  6293. self.get_points = lambda go: go.coords
  6294. def grow_obj2points(self, idx):
  6295. """
  6296. Increases the size of self.obj2points to fit
  6297. idx + 1 items.
  6298. :param idx: Index to fit into list.
  6299. :return: None
  6300. """
  6301. if len(self.obj2points) > idx:
  6302. # len == 2, idx == 1, ok.
  6303. return
  6304. else:
  6305. # len == 2, idx == 2, need 1 more.
  6306. # range(2, 3)
  6307. for i in range(len(self.obj2points), idx + 1):
  6308. self.obj2points.append([])
  6309. def insert(self, objid, obj):
  6310. self.grow_obj2points(objid)
  6311. self.obj2points[objid] = []
  6312. for pt in self.get_points(obj):
  6313. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  6314. self.obj2points[objid].append(len(self.points2obj))
  6315. self.points2obj.append(objid)
  6316. def remove_obj(self, objid, obj):
  6317. # Use all ptids to delete from index
  6318. for i, pt in enumerate(self.get_points(obj)):
  6319. try:
  6320. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  6321. except IndexError:
  6322. pass
  6323. def nearest(self, pt):
  6324. """
  6325. Will raise StopIteration if no items are found.
  6326. :param pt:
  6327. :return:
  6328. """
  6329. return next(self.rti.nearest(pt, objects=True))
  6330. class FlatCAMRTreeStorage(FlatCAMRTree):
  6331. """
  6332. Just like FlatCAMRTree it indexes geometry, but also serves
  6333. as storage for the geometry.
  6334. """
  6335. def __init__(self):
  6336. # super(FlatCAMRTreeStorage, self).__init__()
  6337. super().__init__()
  6338. self.objects = []
  6339. # Optimization attempt!
  6340. self.indexes = {}
  6341. def insert(self, obj):
  6342. self.objects.append(obj)
  6343. idx = len(self.objects) - 1
  6344. # Note: Shapely objects are not hashable any more, although
  6345. # there seem to be plans to re-introduce the feature in
  6346. # version 2.0. For now, we will index using the object's id,
  6347. # but it's important to remember that shapely geometry is
  6348. # mutable, ie. it can be modified to a totally different shape
  6349. # and continue to have the same id.
  6350. # self.indexes[obj] = idx
  6351. self.indexes[id(obj)] = idx
  6352. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  6353. super().insert(idx, obj)
  6354. # @profile
  6355. def remove(self, obj):
  6356. # See note about self.indexes in insert().
  6357. # objidx = self.indexes[obj]
  6358. objidx = self.indexes[id(obj)]
  6359. # Remove from list
  6360. self.objects[objidx] = None
  6361. # Remove from index
  6362. self.remove_obj(objidx, obj)
  6363. def get_objects(self):
  6364. return (o for o in self.objects if o is not None)
  6365. def nearest(self, pt):
  6366. """
  6367. Returns the nearest matching points and the object
  6368. it belongs to.
  6369. :param pt: Query point.
  6370. :return: (match_x, match_y), Object owner of
  6371. matching point.
  6372. :rtype: tuple
  6373. """
  6374. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  6375. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  6376. # class myO:
  6377. # def __init__(self, coords):
  6378. # self.coords = coords
  6379. #
  6380. #
  6381. # def test_rti():
  6382. #
  6383. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  6384. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  6385. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  6386. #
  6387. # os = [o1, o2]
  6388. #
  6389. # idx = FlatCAMRTree()
  6390. #
  6391. # for o in range(len(os)):
  6392. # idx.insert(o, os[o])
  6393. #
  6394. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6395. #
  6396. # idx.remove_obj(0, o1)
  6397. #
  6398. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6399. #
  6400. # idx.remove_obj(1, o2)
  6401. #
  6402. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6403. #
  6404. #
  6405. # def test_rtis():
  6406. #
  6407. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  6408. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  6409. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  6410. #
  6411. # os = [o1, o2]
  6412. #
  6413. # idx = FlatCAMRTreeStorage()
  6414. #
  6415. # for o in range(len(os)):
  6416. # idx.insert(os[o])
  6417. #
  6418. # #os = None
  6419. # #o1 = None
  6420. # #o2 = None
  6421. #
  6422. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6423. #
  6424. # idx.remove(idx.nearest((2,0))[1])
  6425. #
  6426. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6427. #
  6428. # idx.remove(idx.nearest((0,0))[1])
  6429. #
  6430. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]