camlib.py 353 KB

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