camlib.py 356 KB

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