camlib.py 235 KB

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