camlib.py 242 KB

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