camlib.py 352 KB

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