camlib.py 227 KB

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