camlib.py 282 KB

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