camlib.py 228 KB

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