camlib.py 227 KB

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