camlib.py 260 KB

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