camlib.py 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233
  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 __future__ import division
  9. #from scipy import optimize
  10. #import traceback
  11. from io import StringIO
  12. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, dot, float32, \
  13. transpose
  14. from numpy.linalg import solve, norm
  15. from matplotlib.figure import Figure
  16. import re
  17. import sys
  18. import traceback
  19. from decimal import Decimal
  20. import collections
  21. import numpy as np
  22. import matplotlib
  23. #import matplotlib.pyplot as plt
  24. #from scipy.spatial import Delaunay, KDTree
  25. from rtree import index as rtindex
  26. # See: http://toblerity.org/shapely/manual.html
  27. from shapely.geometry import Polygon, LineString, Point, LinearRing
  28. from shapely.geometry import MultiPoint, MultiPolygon
  29. from shapely.geometry import box as shply_box
  30. from shapely.ops import cascaded_union, unary_union
  31. import shapely.affinity as affinity
  32. from shapely.wkt import loads as sloads
  33. from shapely.wkt import dumps as sdumps
  34. from shapely.geometry.base import BaseGeometry
  35. # Used for solid polygons in Matplotlib
  36. from descartes.patch import PolygonPatch
  37. import simplejson as json
  38. # TODO: Commented for FlatCAM packaging with cx_freeze
  39. #from matplotlib.pyplot import plot, subplot
  40. import xml.etree.ElementTree as ET
  41. from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier, parse_path
  42. import itertools
  43. import xml.etree.ElementTree as ET
  44. from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier, parse_path
  45. from svgparse import *
  46. import logging
  47. log = logging.getLogger('base2')
  48. log.setLevel(logging.DEBUG)
  49. # log.setLevel(logging.WARNING)
  50. # log.setLevel(logging.INFO)
  51. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  52. handler = logging.StreamHandler()
  53. handler.setFormatter(formatter)
  54. log.addHandler(handler)
  55. class ParseError(Exception):
  56. pass
  57. class Geometry(object):
  58. """
  59. Base geometry class.
  60. """
  61. defaults = {
  62. "init_units": 'in'
  63. }
  64. def __init__(self):
  65. # Units (in or mm)
  66. self.units = Geometry.defaults["init_units"]
  67. # Final geometry: MultiPolygon or list (of geometry constructs)
  68. self.solid_geometry = None
  69. # Attributes to be included in serialization
  70. self.ser_attrs = ['units', 'solid_geometry']
  71. # Flattened geometry (list of paths only)
  72. self.flat_geometry = []
  73. # Index
  74. self.index = None
  75. def make_index(self):
  76. self.flatten()
  77. self.index = FlatCAMRTree()
  78. for i, g in enumerate(self.flat_geometry):
  79. self.index.insert(i, g)
  80. def add_circle(self, origin, radius):
  81. """
  82. Adds a circle to the object.
  83. :param origin: Center of the circle.
  84. :param radius: Radius of the circle.
  85. :return: None
  86. """
  87. # TODO: Decide what solid_geometry is supposed to be and how we append to it.
  88. if self.solid_geometry is None:
  89. self.solid_geometry = []
  90. if type(self.solid_geometry) is list:
  91. self.solid_geometry.append(Point(origin).buffer(radius))
  92. return
  93. try:
  94. self.solid_geometry = self.solid_geometry.union(Point(origin).buffer(radius))
  95. except:
  96. #print "Failed to run union on polygons."
  97. log.error("Failed to run union on polygons.")
  98. raise
  99. def add_polygon(self, points):
  100. """
  101. Adds a polygon to the object (by union)
  102. :param points: The vertices of the polygon.
  103. :return: None
  104. """
  105. if self.solid_geometry is None:
  106. self.solid_geometry = []
  107. if type(self.solid_geometry) is list:
  108. self.solid_geometry.append(Polygon(points))
  109. return
  110. try:
  111. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  112. except:
  113. #print "Failed to run union on polygons."
  114. log.error("Failed to run union on polygons.")
  115. raise
  116. def add_polyline(self, points):
  117. """
  118. Adds a polyline to the object (by union)
  119. :param points: The vertices of the polyline.
  120. :return: None
  121. """
  122. if self.solid_geometry is None:
  123. self.solid_geometry = []
  124. if type(self.solid_geometry) is list:
  125. self.solid_geometry.append(LineString(points))
  126. return
  127. try:
  128. self.solid_geometry = self.solid_geometry.union(LineString(points))
  129. except:
  130. #print "Failed to run union on polygons."
  131. log.error("Failed to run union on polylines.")
  132. raise
  133. def is_empty(self):
  134. if isinstance(self.solid_geometry, BaseGeometry):
  135. return self.solid_geometry.is_empty
  136. if isinstance(self.solid_geometry, list):
  137. return len(self.solid_geometry) == 0
  138. raise Exception("self.solid_geometry is neither BaseGeometry or list.")
  139. def subtract_polygon(self, points):
  140. """
  141. Subtract polygon from the given object. This only operates on the paths in the original geometry, i.e. it converts polygons into paths.
  142. :param points: The vertices of the polygon.
  143. :return: none
  144. """
  145. if self.solid_geometry is None:
  146. self.solid_geometry = []
  147. #pathonly should be allways True, otherwise polygons are not subtracted
  148. flat_geometry = self.flatten(pathonly=True)
  149. log.debug("%d paths" % len(flat_geometry))
  150. polygon=Polygon(points)
  151. toolgeo=cascaded_union(polygon)
  152. diffs=[]
  153. for target in flat_geometry:
  154. if type(target) == LineString or type(target) == LinearRing:
  155. diffs.append(target.difference(toolgeo))
  156. else:
  157. log.warning("Not implemented.")
  158. self.solid_geometry=cascaded_union(diffs)
  159. def bounds(self):
  160. """
  161. Returns coordinates of rectangular bounds
  162. of geometry: (xmin, ymin, xmax, ymax).
  163. """
  164. log.debug("Geometry->bounds()")
  165. if self.solid_geometry is None:
  166. log.debug("solid_geometry is None")
  167. return 0, 0, 0, 0
  168. if type(self.solid_geometry) is list:
  169. # TODO: This can be done faster. See comment from Shapely mailing lists.
  170. if len(self.solid_geometry) == 0:
  171. log.debug('solid_geometry is empty []')
  172. return 0, 0, 0, 0
  173. return cascaded_union(self.solid_geometry).bounds
  174. else:
  175. return self.solid_geometry.bounds
  176. def find_polygon(self, point, geoset=None):
  177. """
  178. Find an object that object.contains(Point(point)) in
  179. geoset, which can can be iterable, contain iterables of, or
  180. be itself an implementer of .contains().
  181. Note:
  182. * Shapely Polygons will work as expected here. Linearrings
  183. will only yield true if the point is in the perimeter.
  184. :param point: See description
  185. :param geoset: Set to search. If none, the defaults to
  186. self.solid_geometry.
  187. :return: Polygon containing point or None.
  188. """
  189. if geoset is None:
  190. geoset = self.solid_geometry
  191. try: # Iterable
  192. for sub_geo in geoset:
  193. p = self.find_polygon(point, geoset=sub_geo)
  194. if p is not None:
  195. return p
  196. except TypeError: # Non-iterable
  197. try: # Implements .contains()
  198. if geoset.contains(Point(point)):
  199. return geoset
  200. except AttributeError: # Does not implement .contains()
  201. return None
  202. return None
  203. def get_interiors(self, geometry=None):
  204. interiors = []
  205. if geometry is None:
  206. geometry = self.solid_geometry
  207. ## If iterable, expand recursively.
  208. try:
  209. for geo in geometry:
  210. interiors.extend(self.get_interiors(geometry=geo))
  211. ## Not iterable, get the exterior if polygon.
  212. except TypeError:
  213. if type(geometry) == Polygon:
  214. interiors.extend(geometry.interiors)
  215. return interiors
  216. def get_exteriors(self, geometry=None):
  217. """
  218. Returns all exteriors of polygons in geometry. Uses
  219. ``self.solid_geometry`` if geometry is not provided.
  220. :param geometry: Shapely type or list or list of list of such.
  221. :return: List of paths constituting the exteriors
  222. of polygons in geometry.
  223. """
  224. exteriors = []
  225. if geometry is None:
  226. geometry = self.solid_geometry
  227. ## If iterable, expand recursively.
  228. try:
  229. for geo in geometry:
  230. exteriors.extend(self.get_exteriors(geometry=geo))
  231. ## Not iterable, get the exterior if polygon.
  232. except TypeError:
  233. if type(geometry) == Polygon:
  234. exteriors.append(geometry.exterior)
  235. return exteriors
  236. def flatten(self, geometry=None, reset=True, pathonly=False):
  237. """
  238. Creates a list of non-iterable linear geometry objects.
  239. Polygons are expanded into its exterior and interiors if specified.
  240. Results are placed in self.flat_geoemtry
  241. :param geometry: Shapely type or list or list of list of such.
  242. :param reset: Clears the contents of self.flat_geometry.
  243. :param pathonly: Expands polygons into linear elements.
  244. """
  245. if geometry is None:
  246. geometry = self.solid_geometry
  247. if reset:
  248. self.flat_geometry = []
  249. ## If iterable, expand recursively.
  250. try:
  251. for geo in geometry:
  252. self.flatten(geometry=geo,
  253. reset=False,
  254. pathonly=pathonly)
  255. ## Not iterable, do the actual indexing and add.
  256. except TypeError:
  257. if pathonly and type(geometry) == Polygon:
  258. self.flat_geometry.append(geometry.exterior)
  259. self.flatten(geometry=geometry.interiors,
  260. reset=False,
  261. pathonly=True)
  262. else:
  263. self.flat_geometry.append(geometry)
  264. return self.flat_geometry
  265. # def make2Dstorage(self):
  266. #
  267. # self.flatten()
  268. #
  269. # def get_pts(o):
  270. # pts = []
  271. # if type(o) == Polygon:
  272. # g = o.exterior
  273. # pts += list(g.coords)
  274. # for i in o.interiors:
  275. # pts += list(i.coords)
  276. # else:
  277. # pts += list(o.coords)
  278. # return pts
  279. #
  280. # storage = FlatCAMRTreeStorage()
  281. # storage.get_points = get_pts
  282. # for shape in self.flat_geometry:
  283. # storage.insert(shape)
  284. # return storage
  285. # def flatten_to_paths(self, geometry=None, reset=True):
  286. # """
  287. # Creates a list of non-iterable linear geometry elements and
  288. # indexes them in rtree.
  289. #
  290. # :param geometry: Iterable geometry
  291. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  292. # :return: self.flat_geometry, self.flat_geometry_rtree
  293. # """
  294. #
  295. # if geometry is None:
  296. # geometry = self.solid_geometry
  297. #
  298. # if reset:
  299. # self.flat_geometry = []
  300. #
  301. # ## If iterable, expand recursively.
  302. # try:
  303. # for geo in geometry:
  304. # self.flatten_to_paths(geometry=geo, reset=False)
  305. #
  306. # ## Not iterable, do the actual indexing and add.
  307. # except TypeError:
  308. # if type(geometry) == Polygon:
  309. # g = geometry.exterior
  310. # self.flat_geometry.append(g)
  311. #
  312. # ## Add first and last points of the path to the index.
  313. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  314. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  315. #
  316. # for interior in geometry.interiors:
  317. # g = interior
  318. # self.flat_geometry.append(g)
  319. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  320. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  321. # else:
  322. # g = geometry
  323. # self.flat_geometry.append(g)
  324. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  325. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  326. #
  327. # return self.flat_geometry, self.flat_geometry_rtree
  328. def isolation_geometry(self, offset):
  329. """
  330. Creates contours around geometry at a given
  331. offset distance.
  332. :param offset: Offset distance.
  333. :type offset: float
  334. :return: The buffered geometry.
  335. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  336. """
  337. return self.solid_geometry.buffer(offset)
  338. def import_svg(self, filename, flip=True):
  339. """
  340. Imports shapes from an SVG file into the object's geometry.
  341. :param filename: Path to the SVG file.
  342. :type filename: str
  343. :param flip: Flip the vertically.
  344. :type flip: bool
  345. :return: None
  346. """
  347. # Parse into list of shapely objects
  348. svg_tree = ET.parse(filename)
  349. svg_root = svg_tree.getroot()
  350. # Change origin to bottom left
  351. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  352. geos = getsvggeo(svg_root)
  353. if flip:
  354. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  355. # Add to object
  356. if self.solid_geometry is None:
  357. self.solid_geometry = []
  358. if type(self.solid_geometry) is list:
  359. # self.solid_geometry.append(cascaded_union(geos))
  360. if type(geos) is list:
  361. self.solid_geometry += geos
  362. else:
  363. self.solid_geometry.append(geos)
  364. else: # It's shapely geometry
  365. # self.solid_geometry = cascaded_union([self.solid_geometry,
  366. # cascaded_union(geos)])
  367. self.solid_geometry = [self.solid_geometry, geos]
  368. def size(self):
  369. """
  370. Returns (width, height) of rectangular
  371. bounds of geometry.
  372. """
  373. if self.solid_geometry is None:
  374. log.warning("Solid_geometry not computed yet.")
  375. return 0
  376. bounds = self.bounds()
  377. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  378. def get_empty_area(self, boundary=None):
  379. """
  380. Returns the complement of self.solid_geometry within
  381. the given boundary polygon. If not specified, it defaults to
  382. the rectangular bounding box of self.solid_geometry.
  383. """
  384. if boundary is None:
  385. boundary = self.solid_geometry.envelope
  386. return boundary.difference(self.solid_geometry)
  387. @staticmethod
  388. def clear_polygon(polygon, tooldia, overlap=0.15, connect=True,
  389. contour=True):
  390. """
  391. Creates geometry inside a polygon for a tool to cover
  392. the whole area.
  393. This algorithm shrinks the edges of the polygon and takes
  394. the resulting edges as toolpaths.
  395. :param polygon: Polygon to clear.
  396. :param tooldia: Diameter of the tool.
  397. :param overlap: Overlap of toolpasses.
  398. :param connect: Draw lines between disjoint segments to
  399. minimize tool lifts.
  400. :param contour: Paint around the edges. Inconsequential in
  401. this painting method.
  402. :return:
  403. """
  404. log.debug("camlib.clear_polygon()")
  405. assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
  406. "Expected a Polygon or MultiPolygon, got %s" % type(polygon)
  407. ## The toolpaths
  408. # Index first and last points in paths
  409. def get_pts(o):
  410. return [o.coords[0], o.coords[-1]]
  411. geoms = FlatCAMRTreeStorage()
  412. geoms.get_points = get_pts
  413. # Can only result in a Polygon or MultiPolygon
  414. # NOTE: The resulting polygon can be "empty".
  415. current = polygon.buffer(-tooldia / 2.0)
  416. if current.area == 0:
  417. # Otherwise, trying to to insert current.exterior == None
  418. # into the FlatCAMStorage will fail.
  419. return None
  420. # current can be a MultiPolygon
  421. try:
  422. for p in current:
  423. geoms.insert(p.exterior)
  424. for i in p.interiors:
  425. geoms.insert(i)
  426. # Not a Multipolygon. Must be a Polygon
  427. except TypeError:
  428. geoms.insert(current.exterior)
  429. for i in current.interiors:
  430. geoms.insert(i)
  431. while True:
  432. # Can only result in a Polygon or MultiPolygon
  433. current = current.buffer(-tooldia * (1 - overlap))
  434. if current.area > 0:
  435. # current can be a MultiPolygon
  436. try:
  437. for p in current:
  438. geoms.insert(p.exterior)
  439. for i in p.interiors:
  440. geoms.insert(i)
  441. # Not a Multipolygon. Must be a Polygon
  442. except TypeError:
  443. geoms.insert(current.exterior)
  444. for i in current.interiors:
  445. geoms.insert(i)
  446. else:
  447. break
  448. # Optimization: Reduce lifts
  449. if connect:
  450. log.debug("Reducing tool lifts...")
  451. geoms = Geometry.paint_connect(geoms, polygon, tooldia)
  452. return geoms
  453. @staticmethod
  454. def clear_polygon2(polygon, tooldia, seedpoint=None, overlap=0.15,
  455. connect=True, contour=True):
  456. """
  457. Creates geometry inside a polygon for a tool to cover
  458. the whole area.
  459. This algorithm starts with a seed point inside the polygon
  460. and draws circles around it. Arcs inside the polygons are
  461. valid cuts. Finalizes by cutting around the inside edge of
  462. the polygon.
  463. :param polygon: Shapely.geometry.Polygon
  464. :param tooldia: Diameter of the tool
  465. :param seedpoint: Shapely.geometry.Point or None
  466. :param overlap: Tool fraction overlap bewteen passes
  467. :param connect: Connect disjoint segment to minumize tool lifts
  468. :param contour: Cut countour inside the polygon.
  469. :return: List of toolpaths covering polygon.
  470. :rtype: FlatCAMRTreeStorage | None
  471. """
  472. log.debug("camlib.clear_polygon2()")
  473. # Current buffer radius
  474. radius = tooldia / 2 * (1 - overlap)
  475. ## The toolpaths
  476. # Index first and last points in paths
  477. def get_pts(o):
  478. return [o.coords[0], o.coords[-1]]
  479. geoms = FlatCAMRTreeStorage()
  480. geoms.get_points = get_pts
  481. # Path margin
  482. path_margin = polygon.buffer(-tooldia / 2)
  483. # Estimate good seedpoint if not provided.
  484. if seedpoint is None:
  485. seedpoint = path_margin.representative_point()
  486. # Grow from seed until outside the box. The polygons will
  487. # never have an interior, so take the exterior LinearRing.
  488. while 1:
  489. path = Point(seedpoint).buffer(radius).exterior
  490. path = path.intersection(path_margin)
  491. # Touches polygon?
  492. if path.is_empty:
  493. break
  494. else:
  495. #geoms.append(path)
  496. #geoms.insert(path)
  497. # path can be a collection of paths.
  498. try:
  499. for p in path:
  500. geoms.insert(p)
  501. except TypeError:
  502. geoms.insert(path)
  503. radius += tooldia * (1 - overlap)
  504. # Clean inside edges (contours) of the original polygon
  505. if contour:
  506. outer_edges = [x.exterior for x in autolist(polygon.buffer(-tooldia / 2))]
  507. inner_edges = []
  508. for x in autolist(polygon.buffer(-tooldia / 2)): # Over resulting polygons
  509. for y in x.interiors: # Over interiors of each polygon
  510. inner_edges.append(y)
  511. #geoms += outer_edges + inner_edges
  512. for g in outer_edges + inner_edges:
  513. geoms.insert(g)
  514. # Optimization connect touching paths
  515. # log.debug("Connecting paths...")
  516. # geoms = Geometry.path_connect(geoms)
  517. # Optimization: Reduce lifts
  518. if connect:
  519. log.debug("Reducing tool lifts...")
  520. geoms = Geometry.paint_connect(geoms, polygon, tooldia)
  521. return geoms
  522. @staticmethod
  523. def clear_polygon3(polygon, tooldia, overlap=0.15, connect=True,
  524. contour=True):
  525. """
  526. Creates geometry inside a polygon for a tool to cover
  527. the whole area.
  528. This algorithm draws horizontal lines inside the polygon.
  529. :param polygon: The polygon being painted.
  530. :type polygon: shapely.geometry.Polygon
  531. :param tooldia: Tool diameter.
  532. :param overlap: Tool path overlap percentage.
  533. :param connect: Connect lines to avoid tool lifts.
  534. :param contour: Paint around the edges.
  535. :return:
  536. """
  537. log.debug("camlib.clear_polygon3()")
  538. ## The toolpaths
  539. # Index first and last points in paths
  540. def get_pts(o):
  541. return [o.coords[0], o.coords[-1]]
  542. geoms = FlatCAMRTreeStorage()
  543. geoms.get_points = get_pts
  544. lines = []
  545. # Bounding box
  546. left, bot, right, top = polygon.bounds
  547. # First line
  548. y = top - tooldia / 2
  549. while y > bot + tooldia / 2:
  550. line = LineString([(left, y), (right, y)])
  551. lines.append(line)
  552. y -= tooldia * (1 - overlap)
  553. # Last line
  554. y = bot + tooldia / 2
  555. line = LineString([(left, y), (right, y)])
  556. lines.append(line)
  557. # Combine
  558. linesgeo = unary_union(lines)
  559. # Trim to the polygon
  560. margin_poly = polygon.buffer(-tooldia / 2)
  561. lines_trimmed = linesgeo.intersection(margin_poly)
  562. # Add lines to storage
  563. for line in lines_trimmed:
  564. geoms.insert(line)
  565. # Add margin (contour) to storage
  566. if contour:
  567. geoms.insert(margin_poly.exterior)
  568. for ints in margin_poly.interiors:
  569. geoms.insert(ints)
  570. # Optimization: Reduce lifts
  571. if connect:
  572. log.debug("Reducing tool lifts...")
  573. geoms = Geometry.paint_connect(geoms, polygon, tooldia)
  574. return geoms
  575. def scale(self, factor):
  576. """
  577. Scales all of the object's geometry by a given factor. Override
  578. this method.
  579. :param factor: Number by which to scale.
  580. :type factor: float
  581. :return: None
  582. :rtype: None
  583. """
  584. return
  585. def offset(self, vect):
  586. """
  587. Offset the geometry by the given vector. Override this method.
  588. :param vect: (x, y) vector by which to offset the object.
  589. :type vect: tuple
  590. :return: None
  591. """
  592. return
  593. @staticmethod
  594. def paint_connect(storage, boundary, tooldia, max_walk=None):
  595. """
  596. Connects paths that results in a connection segment that is
  597. within the paint area. This avoids unnecessary tool lifting.
  598. :param storage: Geometry to be optimized.
  599. :type storage: FlatCAMRTreeStorage
  600. :param boundary: Polygon defining the limits of the paintable area.
  601. :type boundary: Polygon
  602. :param tooldia: Tool diameter.
  603. :rtype tooldia: float
  604. :param max_walk: Maximum allowable distance without lifting tool.
  605. :type max_walk: float or None
  606. :return: Optimized geometry.
  607. :rtype: FlatCAMRTreeStorage
  608. """
  609. # If max_walk is not specified, the maximum allowed is
  610. # 10 times the tool diameter
  611. max_walk = max_walk or 10 * tooldia
  612. # Assuming geolist is a flat list of flat elements
  613. ## Index first and last points in paths
  614. def get_pts(o):
  615. return [o.coords[0], o.coords[-1]]
  616. # storage = FlatCAMRTreeStorage()
  617. # storage.get_points = get_pts
  618. #
  619. # for shape in geolist:
  620. # if shape is not None: # TODO: This shouldn't have happened.
  621. # # Make LlinearRings into linestrings otherwise
  622. # # When chaining the coordinates path is messed up.
  623. # storage.insert(LineString(shape))
  624. # #storage.insert(shape)
  625. ## Iterate over geometry paths getting the nearest each time.
  626. #optimized_paths = []
  627. optimized_paths = FlatCAMRTreeStorage()
  628. optimized_paths.get_points = get_pts
  629. path_count = 0
  630. current_pt = (0, 0)
  631. pt, geo = storage.nearest(current_pt)
  632. storage.remove(geo)
  633. geo = LineString(geo)
  634. current_pt = geo.coords[-1]
  635. try:
  636. while True:
  637. path_count += 1
  638. #log.debug("Path %d" % path_count)
  639. pt, candidate = storage.nearest(current_pt)
  640. storage.remove(candidate)
  641. candidate = LineString(candidate)
  642. # If last point in geometry is the nearest
  643. # then reverse coordinates.
  644. # but prefer the first one if last == first
  645. if pt != candidate.coords[0] and pt == candidate.coords[-1]:
  646. candidate.coords = list(candidate.coords)[::-1]
  647. # Straight line from current_pt to pt.
  648. # Is the toolpath inside the geometry?
  649. walk_path = LineString([current_pt, pt])
  650. walk_cut = walk_path.buffer(tooldia / 2)
  651. if walk_cut.within(boundary) and walk_path.length < max_walk:
  652. #log.debug("Walk to path #%d is inside. Joining." % path_count)
  653. # Completely inside. Append...
  654. geo.coords = list(geo.coords) + list(candidate.coords)
  655. # try:
  656. # last = optimized_paths[-1]
  657. # last.coords = list(last.coords) + list(geo.coords)
  658. # except IndexError:
  659. # optimized_paths.append(geo)
  660. else:
  661. # Have to lift tool. End path.
  662. #log.debug("Path #%d not within boundary. Next." % path_count)
  663. #optimized_paths.append(geo)
  664. optimized_paths.insert(geo)
  665. geo = candidate
  666. current_pt = geo.coords[-1]
  667. # Next
  668. #pt, geo = storage.nearest(current_pt)
  669. except StopIteration: # Nothing left in storage.
  670. #pass
  671. optimized_paths.insert(geo)
  672. return optimized_paths
  673. @staticmethod
  674. def path_connect(storage, origin=(0, 0)):
  675. """
  676. Simplifies paths in the FlatCAMRTreeStorage storage by
  677. connecting paths that touch on their enpoints.
  678. :param storage: Storage containing the initial paths.
  679. :rtype storage: FlatCAMRTreeStorage
  680. :return: Simplified storage.
  681. :rtype: FlatCAMRTreeStorage
  682. """
  683. log.debug("path_connect()")
  684. ## Index first and last points in paths
  685. def get_pts(o):
  686. return [o.coords[0], o.coords[-1]]
  687. #
  688. # storage = FlatCAMRTreeStorage()
  689. # storage.get_points = get_pts
  690. #
  691. # for shape in pathlist:
  692. # if shape is not None: # TODO: This shouldn't have happened.
  693. # storage.insert(shape)
  694. path_count = 0
  695. pt, geo = storage.nearest(origin)
  696. storage.remove(geo)
  697. #optimized_geometry = [geo]
  698. optimized_geometry = FlatCAMRTreeStorage()
  699. optimized_geometry.get_points = get_pts
  700. #optimized_geometry.insert(geo)
  701. try:
  702. while True:
  703. path_count += 1
  704. #print "geo is", geo
  705. _, left = storage.nearest(geo.coords[0])
  706. #print "left is", left
  707. # If left touches geo, remove left from original
  708. # storage and append to geo.
  709. if type(left) == LineString:
  710. if left.coords[0] == geo.coords[0]:
  711. storage.remove(left)
  712. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  713. continue
  714. if left.coords[-1] == geo.coords[0]:
  715. storage.remove(left)
  716. geo.coords = list(left.coords) + list(geo.coords)
  717. continue
  718. if left.coords[0] == geo.coords[-1]:
  719. storage.remove(left)
  720. geo.coords = list(geo.coords) + list(left.coords)
  721. continue
  722. if left.coords[-1] == geo.coords[-1]:
  723. storage.remove(left)
  724. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  725. continue
  726. _, right = storage.nearest(geo.coords[-1])
  727. #print "right is", right
  728. # If right touches geo, remove left from original
  729. # storage and append to geo.
  730. if type(right) == LineString:
  731. if right.coords[0] == geo.coords[-1]:
  732. storage.remove(right)
  733. geo.coords = list(geo.coords) + list(right.coords)
  734. continue
  735. if right.coords[-1] == geo.coords[-1]:
  736. storage.remove(right)
  737. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  738. continue
  739. if right.coords[0] == geo.coords[0]:
  740. storage.remove(right)
  741. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  742. continue
  743. if right.coords[-1] == geo.coords[0]:
  744. storage.remove(right)
  745. geo.coords = list(left.coords) + list(geo.coords)
  746. continue
  747. # right is either a LinearRing or it does not connect
  748. # to geo (nothing left to connect to geo), so we continue
  749. # with right as geo.
  750. storage.remove(right)
  751. if type(right) == LinearRing:
  752. optimized_geometry.insert(right)
  753. else:
  754. # Cannot exteng geo any further. Put it away.
  755. optimized_geometry.insert(geo)
  756. # Continue with right.
  757. geo = right
  758. except StopIteration: # Nothing found in storage.
  759. optimized_geometry.insert(geo)
  760. #print path_count
  761. log.debug("path_count = %d" % path_count)
  762. return optimized_geometry
  763. def convert_units(self, units):
  764. """
  765. Converts the units of the object to ``units`` by scaling all
  766. the geometry appropriately. This call ``scale()``. Don't call
  767. it again in descendents.
  768. :param units: "IN" or "MM"
  769. :type units: str
  770. :return: Scaling factor resulting from unit change.
  771. :rtype: float
  772. """
  773. log.debug("Geometry.convert_units()")
  774. if units.upper() == self.units.upper():
  775. return 1.0
  776. if units.upper() == "MM":
  777. factor = 25.4
  778. elif units.upper() == "IN":
  779. factor = 1 / 25.4
  780. else:
  781. log.error("Unsupported units: %s" % str(units))
  782. return 1.0
  783. self.units = units
  784. self.scale(factor)
  785. return factor
  786. def to_dict(self):
  787. """
  788. Returns a respresentation of the object as a dictionary.
  789. Attributes to include are listed in ``self.ser_attrs``.
  790. :return: A dictionary-encoded copy of the object.
  791. :rtype: dict
  792. """
  793. d = {}
  794. for attr in self.ser_attrs:
  795. d[attr] = getattr(self, attr)
  796. return d
  797. def from_dict(self, d):
  798. """
  799. Sets object's attributes from a dictionary.
  800. Attributes to include are listed in ``self.ser_attrs``.
  801. This method will look only for only and all the
  802. attributes in ``self.ser_attrs``. They must all
  803. be present. Use only for deserializing saved
  804. objects.
  805. :param d: Dictionary of attributes to set in the object.
  806. :type d: dict
  807. :return: None
  808. """
  809. for attr in self.ser_attrs:
  810. setattr(self, attr, d[attr])
  811. def union(self):
  812. """
  813. Runs a cascaded union on the list of objects in
  814. solid_geometry.
  815. :return: None
  816. """
  817. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  818. def export_svg(self, scale_factor=0.00):
  819. """
  820. Exports the Geometry Object as a SVG Element
  821. :return: SVG Element
  822. """
  823. # Make sure we see a Shapely Geometry class and not a list
  824. geom = cascaded_union(self.flatten())
  825. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  826. # If 0 or less which is invalid then default to 0.05
  827. # This value appears to work for zooming, and getting the output svg line width
  828. # to match that viewed on screen with FlatCam
  829. if scale_factor <= 0:
  830. scale_factor = 0.05
  831. # Convert to a SVG
  832. svg_elem = geom.svg(scale_factor=scale_factor)
  833. return svg_elem
  834. def mirror(self, axis, point):
  835. """
  836. Mirrors the object around a specified axis passign through
  837. the given point.
  838. :param axis: "X" or "Y" indicates around which axis to mirror.
  839. :type axis: str
  840. :param point: [x, y] point belonging to the mirror axis.
  841. :type point: list
  842. :return: None
  843. """
  844. px, py = point
  845. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  846. def mirror_geom(obj):
  847. if type(obj) is list:
  848. new_obj = []
  849. for g in obj:
  850. new_obj.append(mirror_geom(g))
  851. return new_obj
  852. else:
  853. return affinity.scale(obj, xscale, yscale, origin=(px,py))
  854. self.solid_geometry = mirror_geom(self.solid_geometry)
  855. class ApertureMacro:
  856. """
  857. Syntax of aperture macros.
  858. <AM command>: AM<Aperture macro name>*<Macro content>
  859. <Macro content>: {{<Variable definition>*}{<Primitive>*}}
  860. <Variable definition>: $K=<Arithmetic expression>
  861. <Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
  862. <Modifier>: $M|< Arithmetic expression>
  863. <Comment>: 0 <Text>
  864. """
  865. ## Regular expressions
  866. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  867. am2_re = re.compile(r'(.*)%$')
  868. amcomm_re = re.compile(r'^0(.*)')
  869. amprim_re = re.compile(r'^[1-9].*')
  870. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  871. def __init__(self, name=None):
  872. self.name = name
  873. self.raw = ""
  874. ## These below are recomputed for every aperture
  875. ## definition, in other words, are temporary variables.
  876. self.primitives = []
  877. self.locvars = {}
  878. self.geometry = None
  879. def to_dict(self):
  880. """
  881. Returns the object in a serializable form. Only the name and
  882. raw are required.
  883. :return: Dictionary representing the object. JSON ready.
  884. :rtype: dict
  885. """
  886. return {
  887. 'name': self.name,
  888. 'raw': self.raw
  889. }
  890. def from_dict(self, d):
  891. """
  892. Populates the object from a serial representation created
  893. with ``self.to_dict()``.
  894. :param d: Serial representation of an ApertureMacro object.
  895. :return: None
  896. """
  897. for attr in ['name', 'raw']:
  898. setattr(self, attr, d[attr])
  899. def parse_content(self):
  900. """
  901. Creates numerical lists for all primitives in the aperture
  902. macro (in ``self.raw``) by replacing all variables by their
  903. values iteratively and evaluating expressions. Results
  904. are stored in ``self.primitives``.
  905. :return: None
  906. """
  907. # Cleanup
  908. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  909. self.primitives = []
  910. # Separate parts
  911. parts = self.raw.split('*')
  912. #### Every part in the macro ####
  913. for part in parts:
  914. ### Comments. Ignored.
  915. match = ApertureMacro.amcomm_re.search(part)
  916. if match:
  917. continue
  918. ### Variables
  919. # These are variables defined locally inside the macro. They can be
  920. # numerical constant or defind in terms of previously define
  921. # variables, which can be defined locally or in an aperture
  922. # definition. All replacements ocurr here.
  923. match = ApertureMacro.amvar_re.search(part)
  924. if match:
  925. var = match.group(1)
  926. val = match.group(2)
  927. # Replace variables in value
  928. for v in self.locvars:
  929. val = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), val)
  930. # Make all others 0
  931. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  932. # Change x with *
  933. val = re.sub(r'[xX]', "*", val)
  934. # Eval() and store.
  935. self.locvars[var] = eval(val)
  936. continue
  937. ### Primitives
  938. # Each is an array. The first identifies the primitive, while the
  939. # rest depend on the primitive. All are strings representing a
  940. # number and may contain variable definition. The values of these
  941. # variables are defined in an aperture definition.
  942. match = ApertureMacro.amprim_re.search(part)
  943. if match:
  944. ## Replace all variables
  945. for v in self.locvars:
  946. part = re.sub(r'\$' + str(v) + r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  947. # Make all others 0
  948. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  949. # Change x with *
  950. part = re.sub(r'[xX]', "*", part)
  951. ## Store
  952. elements = part.split(",")
  953. self.primitives.append([eval(x) for x in elements])
  954. continue
  955. log.warning("Unknown syntax of aperture macro part: %s" % str(part))
  956. def append(self, data):
  957. """
  958. Appends a string to the raw macro.
  959. :param data: Part of the macro.
  960. :type data: str
  961. :return: None
  962. """
  963. self.raw += data
  964. @staticmethod
  965. def default2zero(n, mods):
  966. """
  967. Pads the ``mods`` list with zeros resulting in an
  968. list of length n.
  969. :param n: Length of the resulting list.
  970. :type n: int
  971. :param mods: List to be padded.
  972. :type mods: list
  973. :return: Zero-padded list.
  974. :rtype: list
  975. """
  976. x = [0.0] * n
  977. na = len(mods)
  978. x[0:na] = mods
  979. return x
  980. @staticmethod
  981. def make_circle(mods):
  982. """
  983. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  984. :return:
  985. """
  986. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  987. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  988. @staticmethod
  989. def make_vectorline(mods):
  990. """
  991. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  992. rotation angle around origin in degrees)
  993. :return:
  994. """
  995. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  996. line = LineString([(xs, ys), (xe, ye)])
  997. box = line.buffer(width/2, cap_style=2)
  998. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  999. return {"pol": int(pol), "geometry": box_rotated}
  1000. @staticmethod
  1001. def make_centerline(mods):
  1002. """
  1003. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  1004. rotation angle around origin in degrees)
  1005. :return:
  1006. """
  1007. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  1008. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  1009. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  1010. return {"pol": int(pol), "geometry": box_rotated}
  1011. @staticmethod
  1012. def make_lowerleftline(mods):
  1013. """
  1014. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  1015. rotation angle around origin in degrees)
  1016. :return:
  1017. """
  1018. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  1019. box = shply_box(x, y, x+width, y+height)
  1020. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  1021. return {"pol": int(pol), "geometry": box_rotated}
  1022. @staticmethod
  1023. def make_outline(mods):
  1024. """
  1025. :param mods:
  1026. :return:
  1027. """
  1028. pol = mods[0]
  1029. n = mods[1]
  1030. points = [(0, 0)]*(n+1)
  1031. for i in range(n+1):
  1032. points[i] = mods[2*i + 2:2*i + 4]
  1033. angle = mods[2*n + 4]
  1034. poly = Polygon(points)
  1035. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  1036. return {"pol": int(pol), "geometry": poly_rotated}
  1037. @staticmethod
  1038. def make_polygon(mods):
  1039. """
  1040. Note: Specs indicate that rotation is only allowed if the center
  1041. (x, y) == (0, 0). I will tolerate breaking this rule.
  1042. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  1043. diameter of circumscribed circle >=0, rotation angle around origin)
  1044. :return:
  1045. """
  1046. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  1047. points = [(0, 0)]*nverts
  1048. for i in range(nverts):
  1049. points[i] = (x + 0.5 * dia * cos(2*pi * i/nverts),
  1050. y + 0.5 * dia * sin(2*pi * i/nverts))
  1051. poly = Polygon(points)
  1052. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  1053. return {"pol": int(pol), "geometry": poly_rotated}
  1054. @staticmethod
  1055. def make_moire(mods):
  1056. """
  1057. Note: Specs indicate that rotation is only allowed if the center
  1058. (x, y) == (0, 0). I will tolerate breaking this rule.
  1059. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  1060. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  1061. angle around origin in degrees)
  1062. :return:
  1063. """
  1064. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  1065. r = dia/2 - thickness/2
  1066. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  1067. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  1068. i = 1 # Number of rings created so far
  1069. ## If the ring does not have an interior it means that it is
  1070. ## a disk. Then stop.
  1071. while len(ring.interiors) > 0 and i < nrings:
  1072. r -= thickness + gap
  1073. if r <= 0:
  1074. break
  1075. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  1076. result = cascaded_union([result, ring])
  1077. i += 1
  1078. ## Crosshair
  1079. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  1080. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  1081. result = cascaded_union([result, hor, ver])
  1082. return {"pol": 1, "geometry": result}
  1083. @staticmethod
  1084. def make_thermal(mods):
  1085. """
  1086. Note: Specs indicate that rotation is only allowed if the center
  1087. (x, y) == (0, 0). I will tolerate breaking this rule.
  1088. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  1089. gap-thickness, rotation angle around origin]
  1090. :return:
  1091. """
  1092. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  1093. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  1094. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  1095. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  1096. thermal = ring.difference(hline.union(vline))
  1097. return {"pol": 1, "geometry": thermal}
  1098. def make_geometry(self, modifiers):
  1099. """
  1100. Runs the macro for the given modifiers and generates
  1101. the corresponding geometry.
  1102. :param modifiers: Modifiers (parameters) for this macro
  1103. :type modifiers: list
  1104. :return: Shapely geometry
  1105. :rtype: shapely.geometry.polygon
  1106. """
  1107. ## Primitive makers
  1108. makers = {
  1109. "1": ApertureMacro.make_circle,
  1110. "2": ApertureMacro.make_vectorline,
  1111. "20": ApertureMacro.make_vectorline,
  1112. "21": ApertureMacro.make_centerline,
  1113. "22": ApertureMacro.make_lowerleftline,
  1114. "4": ApertureMacro.make_outline,
  1115. "5": ApertureMacro.make_polygon,
  1116. "6": ApertureMacro.make_moire,
  1117. "7": ApertureMacro.make_thermal
  1118. }
  1119. ## Store modifiers as local variables
  1120. modifiers = modifiers or []
  1121. modifiers = [float(m) for m in modifiers]
  1122. self.locvars = {}
  1123. for i in range(0, len(modifiers)):
  1124. self.locvars[str(i + 1)] = modifiers[i]
  1125. ## Parse
  1126. self.primitives = [] # Cleanup
  1127. self.geometry = Polygon()
  1128. self.parse_content()
  1129. ## Make the geometry
  1130. for primitive in self.primitives:
  1131. # Make the primitive
  1132. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  1133. # Add it (according to polarity)
  1134. # if self.geometry is None and prim_geo['pol'] == 1:
  1135. # self.geometry = prim_geo['geometry']
  1136. # continue
  1137. if prim_geo['pol'] == 1:
  1138. self.geometry = self.geometry.union(prim_geo['geometry'])
  1139. continue
  1140. if prim_geo['pol'] == 0:
  1141. self.geometry = self.geometry.difference(prim_geo['geometry'])
  1142. continue
  1143. return self.geometry
  1144. class Gerber (Geometry):
  1145. """
  1146. **ATTRIBUTES**
  1147. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  1148. The values are dictionaries key/value pairs which describe the aperture. The
  1149. type key is always present and the rest depend on the key:
  1150. +-----------+-----------------------------------+
  1151. | Key | Value |
  1152. +===========+===================================+
  1153. | type | (str) "C", "R", "O", "P", or "AP" |
  1154. +-----------+-----------------------------------+
  1155. | others | Depend on ``type`` |
  1156. +-----------+-----------------------------------+
  1157. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  1158. that can be instanciated with different parameters in an aperture
  1159. definition. See ``apertures`` above. The key is the name of the macro,
  1160. and the macro itself, the value, is a ``Aperture_Macro`` object.
  1161. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  1162. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  1163. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  1164. *buffering* (or thickening) the ``paths`` with the aperture. These are
  1165. generated from ``paths`` in ``buffer_paths()``.
  1166. **USAGE**::
  1167. g = Gerber()
  1168. g.parse_file(filename)
  1169. g.create_geometry()
  1170. do_something(s.solid_geometry)
  1171. """
  1172. defaults = {
  1173. "steps_per_circle": 40,
  1174. "use_buffer_for_union": True
  1175. }
  1176. def __init__(self, steps_per_circle=None):
  1177. """
  1178. The constructor takes no parameters. Use ``gerber.parse_files()``
  1179. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  1180. :return: Gerber object
  1181. :rtype: Gerber
  1182. """
  1183. # Initialize parent
  1184. Geometry.__init__(self)
  1185. self.solid_geometry = Polygon()
  1186. # Number format
  1187. self.int_digits = 3
  1188. """Number of integer digits in Gerber numbers. Used during parsing."""
  1189. self.frac_digits = 4
  1190. """Number of fraction digits in Gerber numbers. Used during parsing."""
  1191. ## Gerber elements ##
  1192. # Apertures {'id':{'type':chr,
  1193. # ['size':float], ['width':float],
  1194. # ['height':float]}, ...}
  1195. self.apertures = {}
  1196. # Aperture Macros
  1197. self.aperture_macros = {}
  1198. # Attributes to be included in serialization
  1199. # Always append to it because it carries contents
  1200. # from Geometry.
  1201. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures',
  1202. 'aperture_macros', 'solid_geometry']
  1203. #### Parser patterns ####
  1204. # FS - Format Specification
  1205. # The format of X and Y must be the same!
  1206. # L-omit leading zeros, T-omit trailing zeros
  1207. # A-absolute notation, I-incremental notation
  1208. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  1209. # Mode (IN/MM)
  1210. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  1211. # Comment G04|G4
  1212. self.comm_re = re.compile(r'^G0?4(.*)$')
  1213. # AD - Aperture definition
  1214. # Aperture Macro names: Name = [a-zA-Z_.$]{[a-zA-Z_.0-9]+}
  1215. # NOTE: Adding "-" to support output from Upverter.
  1216. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z_$\.][a-zA-Z0-9_$\.\-]*)(?:,(.*))?\*%$')
  1217. # AM - Aperture Macro
  1218. # Beginning of macro (Ends with *%):
  1219. #self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  1220. # Tool change
  1221. # May begin with G54 but that is deprecated
  1222. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  1223. # G01... - Linear interpolation plus flashes with coordinates
  1224. # Operation code (D0x) missing is deprecated... oh well I will support it.
  1225. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  1226. # Operation code alone, usually just D03 (Flash)
  1227. self.opcode_re = re.compile(r'^D0?([123])\*$')
  1228. # G02/3... - Circular interpolation with coordinates
  1229. # 2-clockwise, 3-counterclockwise
  1230. # Operation code (D0x) missing is deprecated... oh well I will support it.
  1231. # Optional start with G02 or G03, optional end with D01 or D02 with
  1232. # optional coordinates but at least one in any order.
  1233. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))' +
  1234. '?(?=.*I([\+-]?\d+))?(?=.*J([\+-]?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  1235. # G01/2/3 Occurring without coordinates
  1236. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  1237. # Single D74 or multi D75 quadrant for circular interpolation
  1238. self.quad_re = re.compile(r'^G7([45])\*$')
  1239. # Region mode on
  1240. # In region mode, D01 starts a region
  1241. # and D02 ends it. A new region can be started again
  1242. # with D01. All contours must be closed before
  1243. # D02 or G37.
  1244. self.regionon_re = re.compile(r'^G36\*$')
  1245. # Region mode off
  1246. # Will end a region and come off region mode.
  1247. # All contours must be closed before D02 or G37.
  1248. self.regionoff_re = re.compile(r'^G37\*$')
  1249. # End of file
  1250. self.eof_re = re.compile(r'^M02\*')
  1251. # IP - Image polarity
  1252. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  1253. # LP - Level polarity
  1254. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  1255. # Units (OBSOLETE)
  1256. self.units_re = re.compile(r'^G7([01])\*$')
  1257. # Absolute/Relative G90/1 (OBSOLETE)
  1258. self.absrel_re = re.compile(r'^G9([01])\*$')
  1259. # Aperture macros
  1260. self.am1_re = re.compile(r'^%AM([^\*]+)\*([^%]+)?(%)?$')
  1261. self.am2_re = re.compile(r'(.*)%$')
  1262. # How to discretize a circle.
  1263. self.steps_per_circ = steps_per_circle or Gerber.defaults['steps_per_circle']
  1264. self.use_buffer_for_union = self.defaults["use_buffer_for_union"]
  1265. def scale(self, factor):
  1266. """
  1267. Scales the objects' geometry on the XY plane by a given factor.
  1268. These are:
  1269. * ``buffered_paths``
  1270. * ``flash_geometry``
  1271. * ``solid_geometry``
  1272. * ``regions``
  1273. NOTE:
  1274. Does not modify the data used to create these elements. If these
  1275. are recreated, the scaling will be lost. This behavior was modified
  1276. because of the complexity reached in this class.
  1277. :param factor: Number by which to scale.
  1278. :type factor: float
  1279. :rtype : None
  1280. """
  1281. ## solid_geometry ???
  1282. # It's a cascaded union of objects.
  1283. self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  1284. factor, origin=(0, 0))
  1285. # # Now buffered_paths, flash_geometry and solid_geometry
  1286. # self.create_geometry()
  1287. def offset(self, vect):
  1288. """
  1289. Offsets the objects' geometry on the XY plane by a given vector.
  1290. These are:
  1291. * ``buffered_paths``
  1292. * ``flash_geometry``
  1293. * ``solid_geometry``
  1294. * ``regions``
  1295. NOTE:
  1296. Does not modify the data used to create these elements. If these
  1297. are recreated, the scaling will be lost. This behavior was modified
  1298. because of the complexity reached in this class.
  1299. :param vect: (x, y) offset vector.
  1300. :type vect: tuple
  1301. :return: None
  1302. """
  1303. dx, dy = vect
  1304. ## Solid geometry
  1305. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  1306. # def mirror(self, axis, point):
  1307. # """
  1308. # Mirrors the object around a specified axis passign through
  1309. # the given point. What is affected:
  1310. #
  1311. # * ``buffered_paths``
  1312. # * ``flash_geometry``
  1313. # * ``solid_geometry``
  1314. # * ``regions``
  1315. #
  1316. # NOTE:
  1317. # Does not modify the data used to create these elements. If these
  1318. # are recreated, the scaling will be lost. This behavior was modified
  1319. # because of the complexity reached in this class.
  1320. #
  1321. # :param axis: "X" or "Y" indicates around which axis to mirror.
  1322. # :type axis: str
  1323. # :param point: [x, y] point belonging to the mirror axis.
  1324. # :type point: list
  1325. # :return: None
  1326. # """
  1327. #
  1328. # px, py = point
  1329. # xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1330. #
  1331. # ## solid_geometry ???
  1332. # # It's a cascaded union of objects.
  1333. # self.solid_geometry = affinity.scale(self.solid_geometry,
  1334. # xscale, yscale, origin=(px, py))
  1335. def aperture_parse(self, apertureId, apertureType, apParameters):
  1336. """
  1337. Parse gerber aperture definition into dictionary of apertures.
  1338. The following kinds and their attributes are supported:
  1339. * *Circular (C)*: size (float)
  1340. * *Rectangle (R)*: width (float), height (float)
  1341. * *Obround (O)*: width (float), height (float).
  1342. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  1343. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  1344. :param apertureId: Id of the aperture being defined.
  1345. :param apertureType: Type of the aperture.
  1346. :param apParameters: Parameters of the aperture.
  1347. :type apertureId: str
  1348. :type apertureType: str
  1349. :type apParameters: str
  1350. :return: Identifier of the aperture.
  1351. :rtype: str
  1352. """
  1353. # Found some Gerber with a leading zero in the aperture id and the
  1354. # referenced it without the zero, so this is a hack to handle that.
  1355. apid = str(int(apertureId))
  1356. try: # Could be empty for aperture macros
  1357. paramList = apParameters.split('X')
  1358. except:
  1359. paramList = None
  1360. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  1361. self.apertures[apid] = {"type": "C",
  1362. "size": float(paramList[0])}
  1363. return apid
  1364. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  1365. self.apertures[apid] = {"type": "R",
  1366. "width": float(paramList[0]),
  1367. "height": float(paramList[1]),
  1368. "size": sqrt(float(paramList[0])**2 + float(paramList[1])**2)} # Hack
  1369. return apid
  1370. if apertureType == "O": # Obround
  1371. self.apertures[apid] = {"type": "O",
  1372. "width": float(paramList[0]),
  1373. "height": float(paramList[1]),
  1374. "size": sqrt(float(paramList[0])**2 + float(paramList[1])**2)} # Hack
  1375. return apid
  1376. if apertureType == "P": # Polygon (regular)
  1377. self.apertures[apid] = {"type": "P",
  1378. "diam": float(paramList[0]),
  1379. "nVertices": int(paramList[1]),
  1380. "size": float(paramList[0])} # Hack
  1381. if len(paramList) >= 3:
  1382. self.apertures[apid]["rotation"] = float(paramList[2])
  1383. return apid
  1384. if apertureType in self.aperture_macros:
  1385. self.apertures[apid] = {"type": "AM",
  1386. "macro": self.aperture_macros[apertureType],
  1387. "modifiers": paramList}
  1388. return apid
  1389. log.warning("Aperture not implemented: %s" % str(apertureType))
  1390. return None
  1391. def parse_file(self, filename, follow=False):
  1392. """
  1393. Calls Gerber.parse_lines() with generator of lines
  1394. read from the given file. Will split the lines if multiple
  1395. statements are found in a single original line.
  1396. The following line is split into two::
  1397. G54D11*G36*
  1398. First is ``G54D11*`` and seconds is ``G36*``.
  1399. :param filename: Gerber file to parse.
  1400. :type filename: str
  1401. :param follow: If true, will not create polygons, just lines
  1402. following the gerber path.
  1403. :type follow: bool
  1404. :return: None
  1405. """
  1406. with open(filename, 'r') as gfile:
  1407. def line_generator():
  1408. for line in gfile:
  1409. line = line.strip(' \r\n')
  1410. while len(line) > 0:
  1411. # If ends with '%' leave as is.
  1412. if line[-1] == '%':
  1413. yield line
  1414. break
  1415. # Split after '*' if any.
  1416. starpos = line.find('*')
  1417. if starpos > -1:
  1418. cleanline = line[:starpos + 1]
  1419. yield cleanline
  1420. line = line[starpos + 1:]
  1421. # Otherwise leave as is.
  1422. else:
  1423. # yield cleanline
  1424. yield line
  1425. break
  1426. self.parse_lines(line_generator(), follow=follow)
  1427. #@profile
  1428. def parse_lines(self, glines, follow=False):
  1429. """
  1430. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  1431. ``self.flashes``, ``self.regions`` and ``self.units``.
  1432. :param glines: Gerber code as list of strings, each element being
  1433. one line of the source file.
  1434. :type glines: list
  1435. :param follow: If true, will not create polygons, just lines
  1436. following the gerber path.
  1437. :type follow: bool
  1438. :return: None
  1439. :rtype: None
  1440. """
  1441. # Coordinates of the current path, each is [x, y]
  1442. path = []
  1443. # Polygons are stored here until there is a change in polarity.
  1444. # Only then they are combined via cascaded_union and added or
  1445. # subtracted from solid_geometry. This is ~100 times faster than
  1446. # applyng a union for every new polygon.
  1447. poly_buffer = []
  1448. last_path_aperture = None
  1449. current_aperture = None
  1450. # 1,2 or 3 from "G01", "G02" or "G03"
  1451. current_interpolation_mode = None
  1452. # 1 or 2 from "D01" or "D02"
  1453. # Note this is to support deprecated Gerber not putting
  1454. # an operation code at the end of every coordinate line.
  1455. current_operation_code = None
  1456. # Current coordinates
  1457. current_x = None
  1458. current_y = None
  1459. # Absolute or Relative/Incremental coordinates
  1460. # Not implemented
  1461. absolute = True
  1462. # How to interpret circular interpolation: SINGLE or MULTI
  1463. quadrant_mode = None
  1464. # Indicates we are parsing an aperture macro
  1465. current_macro = None
  1466. # Indicates the current polarity: D-Dark, C-Clear
  1467. current_polarity = 'D'
  1468. # If a region is being defined
  1469. making_region = False
  1470. #### Parsing starts here ####
  1471. line_num = 0
  1472. gline = ""
  1473. try:
  1474. for gline in glines:
  1475. line_num += 1
  1476. ### Cleanup
  1477. gline = gline.strip(' \r\n')
  1478. #log.debug("%3s %s" % (line_num, gline))
  1479. ### Aperture Macros
  1480. # Having this at the beginning will slow things down
  1481. # but macros can have complicated statements than could
  1482. # be caught by other patterns.
  1483. if current_macro is None: # No macro started yet
  1484. match = self.am1_re.search(gline)
  1485. # Start macro if match, else not an AM, carry on.
  1486. if match:
  1487. log.debug("Starting macro. Line %d: %s" % (line_num, gline))
  1488. current_macro = match.group(1)
  1489. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  1490. if match.group(2): # Append
  1491. self.aperture_macros[current_macro].append(match.group(2))
  1492. if match.group(3): # Finish macro
  1493. #self.aperture_macros[current_macro].parse_content()
  1494. current_macro = None
  1495. log.debug("Macro complete in 1 line.")
  1496. continue
  1497. else: # Continue macro
  1498. log.debug("Continuing macro. Line %d." % line_num)
  1499. match = self.am2_re.search(gline)
  1500. if match: # Finish macro
  1501. log.debug("End of macro. Line %d." % line_num)
  1502. self.aperture_macros[current_macro].append(match.group(1))
  1503. #self.aperture_macros[current_macro].parse_content()
  1504. current_macro = None
  1505. else: # Append
  1506. self.aperture_macros[current_macro].append(gline)
  1507. continue
  1508. ### G01 - Linear interpolation plus flashes
  1509. # Operation code (D0x) missing is deprecated... oh well I will support it.
  1510. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  1511. match = self.lin_re.search(gline)
  1512. if match:
  1513. # Dxx alone?
  1514. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  1515. # try:
  1516. # current_operation_code = int(match.group(4))
  1517. # except:
  1518. # pass # A line with just * will match too.
  1519. # continue
  1520. # NOTE: Letting it continue allows it to react to the
  1521. # operation code.
  1522. # Parse coordinates
  1523. if match.group(2) is not None:
  1524. current_x = parse_gerber_number(match.group(2), self.frac_digits)
  1525. if match.group(3) is not None:
  1526. current_y = parse_gerber_number(match.group(3), self.frac_digits)
  1527. # Parse operation code
  1528. if match.group(4) is not None:
  1529. current_operation_code = int(match.group(4))
  1530. # Pen down: add segment
  1531. if current_operation_code == 1:
  1532. path.append([current_x, current_y])
  1533. last_path_aperture = current_aperture
  1534. elif current_operation_code == 2:
  1535. if len(path) > 1:
  1536. ## --- BUFFERED ---
  1537. if making_region:
  1538. if follow:
  1539. geo = Polygon()
  1540. else:
  1541. geo = Polygon(path)
  1542. else:
  1543. if last_path_aperture is None:
  1544. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1545. width = self.apertures[last_path_aperture]["size"] # TODO: WARNING this should fail!
  1546. #log.debug("Line %d: Setting aperture to %s before buffering." % (line_num, last_path_aperture))
  1547. if follow:
  1548. geo = LineString(path)
  1549. else:
  1550. geo = LineString(path).buffer(width / 2)
  1551. if not geo.is_empty:
  1552. poly_buffer.append(geo)
  1553. path = [[current_x, current_y]] # Start new path
  1554. # Flash
  1555. # Not allowed in region mode.
  1556. elif current_operation_code == 3:
  1557. # Create path draw so far.
  1558. if len(path) > 1:
  1559. # --- Buffered ----
  1560. width = self.apertures[last_path_aperture]["size"]
  1561. if follow:
  1562. geo = LineString(path)
  1563. else:
  1564. geo = LineString(path).buffer(width / 2)
  1565. if not geo.is_empty:
  1566. poly_buffer.append(geo)
  1567. # Reset path starting point
  1568. path = [[current_x, current_y]]
  1569. # --- BUFFERED ---
  1570. # Draw the flash
  1571. if follow:
  1572. continue
  1573. flash = Gerber.create_flash_geometry(Point([current_x, current_y]),
  1574. self.apertures[current_aperture])
  1575. if not flash.is_empty:
  1576. poly_buffer.append(flash)
  1577. continue
  1578. ### G02/3 - Circular interpolation
  1579. # 2-clockwise, 3-counterclockwise
  1580. match = self.circ_re.search(gline)
  1581. if match:
  1582. arcdir = [None, None, "cw", "ccw"]
  1583. mode, x, y, i, j, d = match.groups()
  1584. try:
  1585. x = parse_gerber_number(x, self.frac_digits)
  1586. except:
  1587. x = current_x
  1588. try:
  1589. y = parse_gerber_number(y, self.frac_digits)
  1590. except:
  1591. y = current_y
  1592. try:
  1593. i = parse_gerber_number(i, self.frac_digits)
  1594. except:
  1595. i = 0
  1596. try:
  1597. j = parse_gerber_number(j, self.frac_digits)
  1598. except:
  1599. j = 0
  1600. if quadrant_mode is None:
  1601. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  1602. log.error(gline)
  1603. continue
  1604. if mode is None and current_interpolation_mode not in [2, 3]:
  1605. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  1606. log.error(gline)
  1607. continue
  1608. elif mode is not None:
  1609. current_interpolation_mode = int(mode)
  1610. # Set operation code if provided
  1611. if d is not None:
  1612. current_operation_code = int(d)
  1613. # Nothing created! Pen Up.
  1614. if current_operation_code == 2:
  1615. log.warning("Arc with D2. (%d)" % line_num)
  1616. if len(path) > 1:
  1617. if last_path_aperture is None:
  1618. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1619. # --- BUFFERED ---
  1620. width = self.apertures[last_path_aperture]["size"]
  1621. if follow:
  1622. buffered = LineString(path)
  1623. else:
  1624. buffered = LineString(path).buffer(width / 2)
  1625. if not buffered.is_empty:
  1626. poly_buffer.append(buffered)
  1627. current_x = x
  1628. current_y = y
  1629. path = [[current_x, current_y]] # Start new path
  1630. continue
  1631. # Flash should not happen here
  1632. if current_operation_code == 3:
  1633. log.error("Trying to flash within arc. (%d)" % line_num)
  1634. continue
  1635. if quadrant_mode == 'MULTI':
  1636. center = [i + current_x, j + current_y]
  1637. radius = sqrt(i ** 2 + j ** 2)
  1638. start = arctan2(-j, -i) # Start angle
  1639. # Numerical errors might prevent start == stop therefore
  1640. # we check ahead of time. This should result in a
  1641. # 360 degree arc.
  1642. if current_x == x and current_y == y:
  1643. stop = start
  1644. else:
  1645. stop = arctan2(-center[1] + y, -center[0] + x) # Stop angle
  1646. this_arc = arc(center, radius, start, stop,
  1647. arcdir[current_interpolation_mode],
  1648. self.steps_per_circ)
  1649. # The last point in the computed arc can have
  1650. # numerical errors. The exact final point is the
  1651. # specified (x, y). Replace.
  1652. this_arc[-1] = (x, y)
  1653. # Last point in path is current point
  1654. # current_x = this_arc[-1][0]
  1655. # current_y = this_arc[-1][1]
  1656. current_x, current_y = x, y
  1657. # Append
  1658. path += this_arc
  1659. last_path_aperture = current_aperture
  1660. continue
  1661. if quadrant_mode == 'SINGLE':
  1662. center_candidates = [
  1663. [i + current_x, j + current_y],
  1664. [-i + current_x, j + current_y],
  1665. [i + current_x, -j + current_y],
  1666. [-i + current_x, -j + current_y]
  1667. ]
  1668. valid = False
  1669. log.debug("I: %f J: %f" % (i, j))
  1670. for center in center_candidates:
  1671. radius = sqrt(i ** 2 + j ** 2)
  1672. # Make sure radius to start is the same as radius to end.
  1673. radius2 = sqrt((center[0] - x) ** 2 + (center[1] - y) ** 2)
  1674. if radius2 < radius * 0.95 or radius2 > radius * 1.05:
  1675. continue # Not a valid center.
  1676. # Correct i and j and continue as with multi-quadrant.
  1677. i = center[0] - current_x
  1678. j = center[1] - current_y
  1679. start = arctan2(-j, -i) # Start angle
  1680. stop = arctan2(-center[1] + y, -center[0] + x) # Stop angle
  1681. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  1682. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  1683. (current_x, current_y, center[0], center[1], x, y))
  1684. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  1685. (start * 180 / pi, stop * 180 / pi, arcdir[current_interpolation_mode],
  1686. angle * 180 / pi, pi / 2 * 180 / pi, angle <= (pi + 1e-6) / 2))
  1687. if angle <= (pi + 1e-6) / 2:
  1688. log.debug("########## ACCEPTING ARC ############")
  1689. this_arc = arc(center, radius, start, stop,
  1690. arcdir[current_interpolation_mode],
  1691. self.steps_per_circ)
  1692. # Replace with exact values
  1693. this_arc[-1] = (x, y)
  1694. # current_x = this_arc[-1][0]
  1695. # current_y = this_arc[-1][1]
  1696. current_x, current_y = x, y
  1697. path += this_arc
  1698. last_path_aperture = current_aperture
  1699. valid = True
  1700. break
  1701. if valid:
  1702. continue
  1703. else:
  1704. log.warning("Invalid arc in line %d." % line_num)
  1705. ### Operation code alone
  1706. # Operation code alone, usually just D03 (Flash)
  1707. # self.opcode_re = re.compile(r'^D0?([123])\*$')
  1708. match = self.opcode_re.search(gline)
  1709. if match:
  1710. current_operation_code = int(match.group(1))
  1711. if current_operation_code == 3:
  1712. ## --- Buffered ---
  1713. try:
  1714. log.debug("Bare op-code %d." % current_operation_code)
  1715. # flash = Gerber.create_flash_geometry(Point(path[-1]),
  1716. # self.apertures[current_aperture])
  1717. if follow:
  1718. continue
  1719. flash = Gerber.create_flash_geometry(Point(current_x, current_y),
  1720. self.apertures[current_aperture])
  1721. if not flash.is_empty:
  1722. poly_buffer.append(flash)
  1723. except IndexError:
  1724. log.warning("Line %d: %s -> Nothing there to flash!" % (line_num, gline))
  1725. continue
  1726. ### G74/75* - Single or multiple quadrant arcs
  1727. match = self.quad_re.search(gline)
  1728. if match:
  1729. if match.group(1) == '4':
  1730. quadrant_mode = 'SINGLE'
  1731. else:
  1732. quadrant_mode = 'MULTI'
  1733. continue
  1734. ### G36* - Begin region
  1735. if self.regionon_re.search(gline):
  1736. if len(path) > 1:
  1737. # Take care of what is left in the path
  1738. ## --- Buffered ---
  1739. width = self.apertures[last_path_aperture]["size"]
  1740. if follow:
  1741. geo = LineString(path)
  1742. else:
  1743. geo = LineString(path).buffer(width/2)
  1744. if not geo.is_empty:
  1745. poly_buffer.append(geo)
  1746. path = [path[-1]]
  1747. making_region = True
  1748. continue
  1749. ### G37* - End region
  1750. if self.regionoff_re.search(gline):
  1751. making_region = False
  1752. # Only one path defines region?
  1753. # This can happen if D02 happened before G37 and
  1754. # is not and error.
  1755. if len(path) < 3:
  1756. # print "ERROR: Path contains less than 3 points:"
  1757. # print path
  1758. # print "Line (%d): " % line_num, gline
  1759. # path = []
  1760. #path = [[current_x, current_y]]
  1761. continue
  1762. # For regions we may ignore an aperture that is None
  1763. # self.regions.append({"polygon": Polygon(path),
  1764. # "aperture": last_path_aperture})
  1765. # --- Buffered ---
  1766. if follow:
  1767. region = Polygon()
  1768. else:
  1769. region = Polygon(path)
  1770. if not region.is_valid:
  1771. if not follow:
  1772. region = region.buffer(0)
  1773. if not region.is_empty:
  1774. poly_buffer.append(region)
  1775. path = [[current_x, current_y]] # Start new path
  1776. continue
  1777. ### Aperture definitions %ADD...
  1778. match = self.ad_re.search(gline)
  1779. if match:
  1780. log.info("Found aperture definition. Line %d: %s" % (line_num, gline))
  1781. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  1782. continue
  1783. ### G01/2/3* - Interpolation mode change
  1784. # Can occur along with coordinates and operation code but
  1785. # sometimes by itself (handled here).
  1786. # Example: G01*
  1787. match = self.interp_re.search(gline)
  1788. if match:
  1789. current_interpolation_mode = int(match.group(1))
  1790. continue
  1791. ### Tool/aperture change
  1792. # Example: D12*
  1793. match = self.tool_re.search(gline)
  1794. if match:
  1795. current_aperture = match.group(1)
  1796. log.debug("Line %d: Aperture change to (%s)" % (line_num, match.group(1)))
  1797. log.debug(self.apertures[current_aperture])
  1798. # If the aperture value is zero then make it something quite small but with a non-zero value
  1799. # so it can be processed by FlatCAM.
  1800. # But first test to see if the aperture type is "aperture macro". In that case
  1801. # we should not test for "size" key as it does not exist in this case.
  1802. if self.apertures[current_aperture]["type"] is not "AM":
  1803. if self.apertures[current_aperture]["size"] == 0:
  1804. self.apertures[current_aperture]["size"] = 0.0000001
  1805. log.debug(self.apertures[current_aperture])
  1806. # Take care of the current path with the previous tool
  1807. if len(path) > 1:
  1808. # --- Buffered ----
  1809. width = self.apertures[last_path_aperture]["size"]
  1810. if follow:
  1811. geo = LineString(path)
  1812. else:
  1813. geo = LineString(path).buffer(width / 2)
  1814. if not geo.is_empty:
  1815. poly_buffer.append(geo)
  1816. path = [path[-1]]
  1817. continue
  1818. ### Polarity change
  1819. # Example: %LPD*% or %LPC*%
  1820. # If polarity changes, creates geometry from current
  1821. # buffer, then adds or subtracts accordingly.
  1822. match = self.lpol_re.search(gline)
  1823. if match:
  1824. if len(path) > 1 and current_polarity != match.group(1):
  1825. # --- Buffered ----
  1826. width = self.apertures[last_path_aperture]["size"]
  1827. if follow:
  1828. geo = LineString(path)
  1829. else:
  1830. geo = LineString(path).buffer(width / 2)
  1831. if not geo.is_empty:
  1832. poly_buffer.append(geo)
  1833. path = [path[-1]]
  1834. # --- Apply buffer ---
  1835. # If added for testing of bug #83
  1836. # TODO: Remove when bug fixed
  1837. if len(poly_buffer) > 0:
  1838. if current_polarity == 'D':
  1839. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1840. else:
  1841. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1842. poly_buffer = []
  1843. current_polarity = match.group(1)
  1844. continue
  1845. ### Number format
  1846. # Example: %FSLAX24Y24*%
  1847. # TODO: This is ignoring most of the format. Implement the rest.
  1848. match = self.fmt_re.search(gline)
  1849. if match:
  1850. absolute = {'A': True, 'I': False}
  1851. self.int_digits = int(match.group(3))
  1852. self.frac_digits = int(match.group(4))
  1853. continue
  1854. ### Mode (IN/MM)
  1855. # Example: %MOIN*%
  1856. match = self.mode_re.search(gline)
  1857. if match:
  1858. #self.units = match.group(1)
  1859. # Changed for issue #80
  1860. self.convert_units(match.group(1))
  1861. continue
  1862. ### Units (G70/1) OBSOLETE
  1863. match = self.units_re.search(gline)
  1864. if match:
  1865. #self.units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  1866. # Changed for issue #80
  1867. self.convert_units({'0': 'IN', '1': 'MM'}[match.group(1)])
  1868. continue
  1869. ### Absolute/relative coordinates G90/1 OBSOLETE
  1870. match = self.absrel_re.search(gline)
  1871. if match:
  1872. absolute = {'0': True, '1': False}[match.group(1)]
  1873. continue
  1874. #### Ignored lines
  1875. ## Comments
  1876. match = self.comm_re.search(gline)
  1877. if match:
  1878. continue
  1879. ## EOF
  1880. match = self.eof_re.search(gline)
  1881. if match:
  1882. continue
  1883. ### Line did not match any pattern. Warn user.
  1884. log.warning("Line ignored (%d): %s" % (line_num, gline))
  1885. if len(path) > 1:
  1886. # EOF, create shapely LineString if something still in path
  1887. ## --- Buffered ---
  1888. width = self.apertures[last_path_aperture]["size"]
  1889. if follow:
  1890. geo = LineString(path)
  1891. else:
  1892. geo = LineString(path).buffer(width / 2)
  1893. if not geo.is_empty:
  1894. poly_buffer.append(geo)
  1895. # --- Apply buffer ---
  1896. if follow:
  1897. self.solid_geometry = poly_buffer
  1898. return
  1899. log.warn("Joining %d polygons." % len(poly_buffer))
  1900. if self.use_buffer_for_union:
  1901. log.debug("Union by buffer...")
  1902. new_poly = MultiPolygon(poly_buffer)
  1903. new_poly = new_poly.buffer(0.00000001)
  1904. new_poly = new_poly.buffer(-0.00000001)
  1905. log.warn("Union(buffer) done.")
  1906. else:
  1907. log.debug("Union by union()...")
  1908. new_poly = cascaded_union(poly_buffer)
  1909. new_poly = new_poly.buffer(0)
  1910. log.warn("Union done.")
  1911. if current_polarity == 'D':
  1912. self.solid_geometry = self.solid_geometry.union(new_poly)
  1913. else:
  1914. self.solid_geometry = self.solid_geometry.difference(new_poly)
  1915. except Exception as err:
  1916. ex_type, ex, tb = sys.exc_info()
  1917. traceback.print_tb(tb)
  1918. #print traceback.format_exc()
  1919. log.error("PARSING FAILED. Line %d: %s" % (line_num, gline))
  1920. raise ParseError("Line %d: %s" % (line_num, gline), repr(err))
  1921. @staticmethod
  1922. def create_flash_geometry(location, aperture):
  1923. log.debug('Flashing @%s, Aperture: %s' % (location, aperture))
  1924. if type(location) == list:
  1925. location = Point(location)
  1926. if aperture['type'] == 'C': # Circles
  1927. return location.buffer(aperture['size'] / 2)
  1928. if aperture['type'] == 'R': # Rectangles
  1929. loc = location.coords[0]
  1930. width = aperture['width']
  1931. height = aperture['height']
  1932. minx = loc[0] - width / 2
  1933. maxx = loc[0] + width / 2
  1934. miny = loc[1] - height / 2
  1935. maxy = loc[1] + height / 2
  1936. return shply_box(minx, miny, maxx, maxy)
  1937. if aperture['type'] == 'O': # Obround
  1938. loc = location.coords[0]
  1939. width = aperture['width']
  1940. height = aperture['height']
  1941. if width > height:
  1942. p1 = Point(loc[0] + 0.5 * (width - height), loc[1])
  1943. p2 = Point(loc[0] - 0.5 * (width - height), loc[1])
  1944. c1 = p1.buffer(height * 0.5)
  1945. c2 = p2.buffer(height * 0.5)
  1946. else:
  1947. p1 = Point(loc[0], loc[1] + 0.5 * (height - width))
  1948. p2 = Point(loc[0], loc[1] - 0.5 * (height - width))
  1949. c1 = p1.buffer(width * 0.5)
  1950. c2 = p2.buffer(width * 0.5)
  1951. return cascaded_union([c1, c2]).convex_hull
  1952. if aperture['type'] == 'P': # Regular polygon
  1953. loc = location.coords[0]
  1954. diam = aperture['diam']
  1955. n_vertices = aperture['nVertices']
  1956. points = []
  1957. for i in range(0, n_vertices):
  1958. x = loc[0] + 0.5 * diam * (cos(2 * pi * i / n_vertices))
  1959. y = loc[1] + 0.5 * diam * (sin(2 * pi * i / n_vertices))
  1960. points.append((x, y))
  1961. ply = Polygon(points)
  1962. if 'rotation' in aperture:
  1963. ply = affinity.rotate(ply, aperture['rotation'])
  1964. return ply
  1965. if aperture['type'] == 'AM': # Aperture Macro
  1966. loc = location.coords[0]
  1967. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1968. if flash_geo.is_empty:
  1969. log.warning("Empty geometry for Aperture Macro: %s" % str(aperture['macro'].name))
  1970. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1971. log.warning("Unknown aperture type: %s" % aperture['type'])
  1972. return None
  1973. def create_geometry(self):
  1974. """
  1975. Geometry from a Gerber file is made up entirely of polygons.
  1976. Every stroke (linear or circular) has an aperture which gives
  1977. it thickness. Additionally, aperture strokes have non-zero area,
  1978. and regions naturally do as well.
  1979. :rtype : None
  1980. :return: None
  1981. """
  1982. # self.buffer_paths()
  1983. #
  1984. # self.fix_regions()
  1985. #
  1986. # self.do_flashes()
  1987. #
  1988. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1989. # [poly['polygon'] for poly in self.regions] +
  1990. # self.flash_geometry)
  1991. def get_bounding_box(self, margin=0.0, rounded=False):
  1992. """
  1993. Creates and returns a rectangular polygon bounding at a distance of
  1994. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1995. can optionally have rounded corners of radius equal to margin.
  1996. :param margin: Distance to enlarge the rectangular bounding
  1997. box in both positive and negative, x and y axes.
  1998. :type margin: float
  1999. :param rounded: Wether or not to have rounded corners.
  2000. :type rounded: bool
  2001. :return: The bounding box.
  2002. :rtype: Shapely.Polygon
  2003. """
  2004. bbox = self.solid_geometry.envelope.buffer(margin)
  2005. if not rounded:
  2006. bbox = bbox.envelope
  2007. return bbox
  2008. class Excellon(Geometry):
  2009. """
  2010. *ATTRIBUTES*
  2011. * ``tools`` (dict): The key is the tool name and the value is
  2012. a dictionary specifying the tool:
  2013. ================ ====================================
  2014. Key Value
  2015. ================ ====================================
  2016. C Diameter of the tool
  2017. Others Not supported (Ignored).
  2018. ================ ====================================
  2019. * ``drills`` (list): Each is a dictionary:
  2020. ================ ====================================
  2021. Key Value
  2022. ================ ====================================
  2023. point (Shapely.Point) Where to drill
  2024. tool (str) A key in ``tools``
  2025. ================ ====================================
  2026. """
  2027. defaults = {
  2028. "zeros": "L"
  2029. }
  2030. def __init__(self, zeros=None):
  2031. """
  2032. The constructor takes no parameters.
  2033. :return: Excellon object.
  2034. :rtype: Excellon
  2035. """
  2036. Geometry.__init__(self)
  2037. # self.tools[name] = {"C": diameter<float>}
  2038. self.tools = {}
  2039. self.drills = []
  2040. ## IN|MM -> Units are inherited from Geometry
  2041. #self.units = units
  2042. # Trailing "T" or leading "L" (default)
  2043. #self.zeros = "T"
  2044. self.zeros = zeros or self.defaults["zeros"]
  2045. # Attributes to be included in serialization
  2046. # Always append to it because it carries contents
  2047. # from Geometry.
  2048. self.ser_attrs += ['tools', 'drills', 'zeros']
  2049. #### Patterns ####
  2050. # Regex basics:
  2051. # ^ - beginning
  2052. # $ - end
  2053. # *: 0 or more, +: 1 or more, ?: 0 or 1
  2054. # M48 - Beggining of Part Program Header
  2055. self.hbegin_re = re.compile(r'^M48$')
  2056. # M95 or % - End of Part Program Header
  2057. # NOTE: % has different meaning in the body
  2058. self.hend_re = re.compile(r'^(?:M95|%)$')
  2059. # FMAT Excellon format
  2060. # Ignored in the parser
  2061. #self.fmat_re = re.compile(r'^FMAT,([12])$')
  2062. # Number format and units
  2063. # INCH uses 6 digits
  2064. # METRIC uses 5/6
  2065. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  2066. # Tool definition/parameters (?= is look-ahead
  2067. # NOTE: This might be an overkill!
  2068. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  2069. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  2070. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  2071. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  2072. self.toolset_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))?' +
  2073. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  2074. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  2075. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  2076. # Tool select
  2077. # Can have additional data after tool number but
  2078. # is ignored if present in the header.
  2079. # Warning: This will match toolset_re too.
  2080. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  2081. self.toolsel_re = re.compile(r'^T(\d+)')
  2082. # Comment
  2083. self.comm_re = re.compile(r'^;(.*)$')
  2084. # Absolute/Incremental G90/G91
  2085. self.absinc_re = re.compile(r'^G9([01])$')
  2086. # Modes of operation
  2087. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  2088. self.modes_re = re.compile(r'^G0([012345])')
  2089. # Measuring mode
  2090. # 1-metric, 2-inch
  2091. self.meas_re = re.compile(r'^M7([12])$')
  2092. # Coordinates
  2093. #self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  2094. #self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  2095. self.coordsperiod_re = re.compile(r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]')
  2096. self.coordsnoperiod_re = re.compile(r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]')
  2097. # R - Repeat hole (# times, X offset, Y offset)
  2098. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  2099. # Various stop/pause commands
  2100. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  2101. # Parse coordinates
  2102. self.leadingzeros_re = re.compile(r'^[-\+]?(0*)(\d*)')
  2103. def parse_file(self, filename):
  2104. """
  2105. Reads the specified file as array of lines as
  2106. passes it to ``parse_lines()``.
  2107. :param filename: The file to be read and parsed.
  2108. :type filename: str
  2109. :return: None
  2110. """
  2111. efile = open(filename, 'r')
  2112. estr = efile.readlines()
  2113. efile.close()
  2114. self.parse_lines(estr)
  2115. def parse_lines(self, elines):
  2116. """
  2117. Main Excellon parser.
  2118. :param elines: List of strings, each being a line of Excellon code.
  2119. :type elines: list
  2120. :return: None
  2121. """
  2122. # State variables
  2123. current_tool = ""
  2124. in_header = False
  2125. current_x = None
  2126. current_y = None
  2127. #### Parsing starts here ####
  2128. line_num = 0 # Line number
  2129. eline = ""
  2130. try:
  2131. for eline in elines:
  2132. line_num += 1
  2133. #log.debug("%3d %s" % (line_num, str(eline)))
  2134. ### Cleanup lines
  2135. eline = eline.strip(' \r\n')
  2136. ## Header Begin (M48) ##
  2137. if self.hbegin_re.search(eline):
  2138. in_header = True
  2139. continue
  2140. ## Header End ##
  2141. if self.hend_re.search(eline):
  2142. in_header = False
  2143. continue
  2144. ## Alternative units format M71/M72
  2145. # Supposed to be just in the body (yes, the body)
  2146. # but some put it in the header (PADS for example).
  2147. # Will detect anywhere. Occurrence will change the
  2148. # object's units.
  2149. match = self.meas_re.match(eline)
  2150. if match:
  2151. #self.units = {"1": "MM", "2": "IN"}[match.group(1)]
  2152. # Modified for issue #80
  2153. self.convert_units({"1": "MM", "2": "IN"}[match.group(1)])
  2154. log.debug(" Units: %s" % self.units)
  2155. continue
  2156. #### Body ####
  2157. if not in_header:
  2158. ## Tool change ##
  2159. match = self.toolsel_re.search(eline)
  2160. if match:
  2161. current_tool = str(int(match.group(1)))
  2162. log.debug("Tool change: %s" % current_tool)
  2163. continue
  2164. ## Coordinates without period ##
  2165. match = self.coordsnoperiod_re.search(eline)
  2166. if match:
  2167. try:
  2168. #x = float(match.group(1))/10000
  2169. x = self.parse_number(match.group(1))
  2170. current_x = x
  2171. except TypeError:
  2172. x = current_x
  2173. try:
  2174. #y = float(match.group(2))/10000
  2175. y = self.parse_number(match.group(2))
  2176. current_y = y
  2177. except TypeError:
  2178. y = current_y
  2179. if x is None or y is None:
  2180. log.error("Missing coordinates")
  2181. continue
  2182. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  2183. log.debug("{:15} {:8} {:8}".format(eline, x, y))
  2184. continue
  2185. ## Coordinates with period: Use literally. ##
  2186. match = self.coordsperiod_re.search(eline)
  2187. if match:
  2188. try:
  2189. x = float(match.group(1))
  2190. current_x = x
  2191. except TypeError:
  2192. x = current_x
  2193. try:
  2194. y = float(match.group(2))
  2195. current_y = y
  2196. except TypeError:
  2197. y = current_y
  2198. if x is None or y is None:
  2199. log.error("Missing coordinates")
  2200. continue
  2201. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  2202. log.debug("{:15} {:8} {:8}".format(eline, x, y))
  2203. continue
  2204. #### Header ####
  2205. if in_header:
  2206. ## Tool definitions ##
  2207. match = self.toolset_re.search(eline)
  2208. if match:
  2209. name = str(int(match.group(1)))
  2210. spec = {
  2211. "C": float(match.group(2)),
  2212. # "F": float(match.group(3)),
  2213. # "S": float(match.group(4)),
  2214. # "B": float(match.group(5)),
  2215. # "H": float(match.group(6)),
  2216. # "Z": float(match.group(7))
  2217. }
  2218. self.tools[name] = spec
  2219. log.debug(" Tool definition: %s %s" % (name, spec))
  2220. continue
  2221. ## Units and number format ##
  2222. match = self.units_re.match(eline)
  2223. if match:
  2224. self.zeros = match.group(2) or self.zeros # "T" or "L". Might be empty
  2225. #self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  2226. # Modified for issue #80
  2227. self.convert_units({"INCH": "IN", "METRIC": "MM"}[match.group(1)])
  2228. log.debug(" Units/Format: %s %s" % (self.units, self.zeros))
  2229. continue
  2230. log.warning("Line ignored: %s" % eline)
  2231. log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
  2232. except Exception as e:
  2233. log.error("PARSING FAILED. Line %d: %s" % (line_num, eline))
  2234. raise
  2235. def parse_number(self, number_str):
  2236. """
  2237. Parses coordinate numbers without period.
  2238. :param number_str: String representing the numerical value.
  2239. :type number_str: str
  2240. :return: Floating point representation of the number
  2241. :rtype: foat
  2242. """
  2243. if self.zeros == "L":
  2244. # With leading zeros, when you type in a coordinate,
  2245. # the leading zeros must always be included. Trailing zeros
  2246. # are unneeded and may be left off. The CNC-7 will automatically add them.
  2247. # r'^[-\+]?(0*)(\d*)'
  2248. # 6 digits are divided by 10^4
  2249. # If less than size digits, they are automatically added,
  2250. # 5 digits then are divided by 10^3 and so on.
  2251. match = self.leadingzeros_re.search(number_str)
  2252. if self.units.lower() == "in":
  2253. return float(number_str) / \
  2254. (10 ** (len(match.group(1)) + len(match.group(2)) - 2))
  2255. else:
  2256. return float(number_str) / \
  2257. (10 ** (len(match.group(1)) + len(match.group(2)) - 3))
  2258. else: # Trailing
  2259. # You must show all zeros to the right of the number and can omit
  2260. # all zeros to the left of the number. The CNC-7 will count the number
  2261. # of digits you typed and automatically fill in the missing zeros.
  2262. if self.units.lower() == "in": # Inches is 00.0000
  2263. return float(number_str) / 10000
  2264. else:
  2265. return float(number_str) / 1000 # Metric is 000.000
  2266. def create_geometry(self):
  2267. """
  2268. Creates circles of the tool diameter at every point
  2269. specified in ``self.drills``.
  2270. :return: None
  2271. """
  2272. self.solid_geometry = []
  2273. for drill in self.drills:
  2274. # poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  2275. tooldia = self.tools[drill['tool']]['C']
  2276. poly = drill['point'].buffer(tooldia / 2.0)
  2277. self.solid_geometry.append(poly)
  2278. def scale(self, factor):
  2279. """
  2280. Scales geometry on the XY plane in the object by a given factor.
  2281. Tool sizes, feedrates an Z-plane dimensions are untouched.
  2282. :param factor: Number by which to scale the object.
  2283. :type factor: float
  2284. :return: None
  2285. :rtype: NOne
  2286. """
  2287. # Drills
  2288. for drill in self.drills:
  2289. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  2290. self.create_geometry()
  2291. def offset(self, vect):
  2292. """
  2293. Offsets geometry on the XY plane in the object by a given vector.
  2294. :param vect: (x, y) offset vector.
  2295. :type vect: tuple
  2296. :return: None
  2297. """
  2298. dx, dy = vect
  2299. # Drills
  2300. for drill in self.drills:
  2301. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  2302. # Recreate geometry
  2303. self.create_geometry()
  2304. def mirror(self, axis, point):
  2305. """
  2306. :param axis: "X" or "Y" indicates around which axis to mirror.
  2307. :type axis: str
  2308. :param point: [x, y] point belonging to the mirror axis.
  2309. :type point: list
  2310. :return: None
  2311. """
  2312. px, py = point
  2313. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  2314. # Modify data
  2315. for drill in self.drills:
  2316. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  2317. # Recreate geometry
  2318. self.create_geometry()
  2319. def convert_units(self, units):
  2320. factor = Geometry.convert_units(self, units)
  2321. # Tools
  2322. for tname in self.tools:
  2323. self.tools[tname]["C"] *= factor
  2324. self.create_geometry()
  2325. return factor
  2326. class CNCjob(Geometry):
  2327. """
  2328. Represents work to be done by a CNC machine.
  2329. *ATTRIBUTES*
  2330. * ``gcode_parsed`` (list): Each is a dictionary:
  2331. ===================== =========================================
  2332. Key Value
  2333. ===================== =========================================
  2334. geom (Shapely.LineString) Tool path (XY plane)
  2335. kind (string) "AB", A is "T" (travel) or
  2336. "C" (cut). B is "F" (fast) or "S" (slow).
  2337. ===================== =========================================
  2338. """
  2339. defaults = {
  2340. "zdownrate": None,
  2341. "coordinate_format": "X%.4fY%.4f"
  2342. }
  2343. def __init__(self,
  2344. units="in",
  2345. kind="generic",
  2346. z_move=0.1,
  2347. feedrate=3.0,
  2348. z_cut=-0.002,
  2349. tooldia=0.0,
  2350. zdownrate=None,
  2351. spindlespeed=None):
  2352. Geometry.__init__(self)
  2353. self.kind = kind
  2354. self.units = units
  2355. self.z_cut = z_cut
  2356. self.z_move = z_move
  2357. self.feedrate = feedrate
  2358. self.tooldia = tooldia
  2359. self.unitcode = {"IN": "G20", "MM": "G21"}
  2360. # TODO: G04 Does not exist. It's G4 and now we are handling in postprocessing.
  2361. #self.pausecode = "G04 P1"
  2362. self.feedminutecode = "G94"
  2363. self.absolutecode = "G90"
  2364. self.gcode = ""
  2365. self.input_geometry_bounds = None
  2366. self.gcode_parsed = None
  2367. self.steps_per_circ = 20 # Used when parsing G-code arcs
  2368. if zdownrate is not None:
  2369. self.zdownrate = float(zdownrate)
  2370. elif CNCjob.defaults["zdownrate"] is not None:
  2371. self.zdownrate = float(CNCjob.defaults["zdownrate"])
  2372. else:
  2373. self.zdownrate = None
  2374. self.spindlespeed = spindlespeed
  2375. # Attributes to be included in serialization
  2376. # Always append to it because it carries contents
  2377. # from Geometry.
  2378. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  2379. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  2380. 'steps_per_circ']
  2381. def convert_units(self, units):
  2382. factor = Geometry.convert_units(self, units)
  2383. log.debug("CNCjob.convert_units()")
  2384. self.z_cut *= factor
  2385. self.z_move *= factor
  2386. self.feedrate *= factor
  2387. self.tooldia *= factor
  2388. return factor
  2389. def generate_from_excellon_by_tool(self, exobj, tools="all",
  2390. toolchange=False, toolchangez=0.1):
  2391. """
  2392. Creates gcode for this object from an Excellon object
  2393. for the specified tools.
  2394. :param exobj: Excellon object to process
  2395. :type exobj: Excellon
  2396. :param tools: Comma separated tool names
  2397. :type: tools: str
  2398. :param toolchange: Use tool change sequence between tools.
  2399. :type toolchange: bool
  2400. :param toolchangez: Height at which to perform the tool change.
  2401. :type toolchangez: float
  2402. :return: None
  2403. :rtype: None
  2404. """
  2405. log.debug("Creating CNC Job from Excellon...")
  2406. # Tools
  2407. # Sort tools by diameter. items() -> [('name', diameter), ...]
  2408. #sorted_tools = sorted(list(exobj.tools.items()), key=lambda tl: tl[1])
  2409. sort = []
  2410. for k, v in exobj.tools.items():
  2411. sort.append((k, v.get('C')))
  2412. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2413. if tools == "all":
  2414. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  2415. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  2416. else:
  2417. selected_tools = [x.strip() for x in tools.split(",")]
  2418. selected_tools = [tl for tl in selected_tools if tl in selected_tools]
  2419. # Create a sorted list of selected tools from the sorted_tools list
  2420. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  2421. log.debug("Tools selected and sorted are: %s" % str(tools))
  2422. # Points (Group by tool)
  2423. points = {}
  2424. for drill in exobj.drills:
  2425. if drill['tool'] in tools:
  2426. try:
  2427. points[drill['tool']].append(drill['point'])
  2428. except KeyError:
  2429. points[drill['tool']] = [drill['point']]
  2430. # log.debug("Found %d drills." % len(points))
  2431. self.gcode = []
  2432. # Basic G-Code macros
  2433. t = "G00 " + CNCjob.defaults["coordinate_format"] + "\n"
  2434. down = "G01 Z%.4f\n" % self.z_cut
  2435. up = "G00 Z%.4f\n" % self.z_move
  2436. up_to_zero = "G01 Z0\n"
  2437. # Initialization
  2438. gcode = self.unitcode[self.units.upper()] + "\n"
  2439. gcode += self.absolutecode + "\n"
  2440. gcode += self.feedminutecode + "\n"
  2441. gcode += "F%.2f\n" % self.feedrate
  2442. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  2443. if self.spindlespeed is not None:
  2444. # Spindle start with configured speed
  2445. gcode += "M03 S%d\n" % int(self.spindlespeed)
  2446. else:
  2447. gcode += "M03\n" # Spindle start
  2448. # gcode += self.pausecode + "\n"
  2449. for tool in tools:
  2450. # Only if tool has points.
  2451. if tool in points:
  2452. # Tool change sequence (optional)
  2453. if toolchange:
  2454. gcode += "G00 Z%.4f\n" % toolchangez
  2455. gcode += "T%d\n" % int(tool) # Indicate tool slot (for automatic tool changer)
  2456. gcode += "M5\n" # Spindle Stop
  2457. gcode += "M6\n" # Tool change
  2458. gcode += "(MSG, Change to tool dia=%.4f)\n" % exobj.tools[tool]["C"]
  2459. gcode += "M0\n" # Temporary machine stop
  2460. if self.spindlespeed is not None:
  2461. # Spindle start with configured speed
  2462. gcode += "M03 S%d\n" % int(self.spindlespeed)
  2463. else:
  2464. gcode += "M03\n" # Spindle start
  2465. # Drillling!
  2466. for point in points[tool]:
  2467. x, y = point.coords.xy
  2468. gcode += t % (x[0], y[0])
  2469. gcode += down + up_to_zero + up
  2470. gcode += t % (0, 0)
  2471. gcode += "M05\n" # Spindle stop
  2472. self.gcode = gcode
  2473. def generate_from_geometry_2(self,
  2474. geometry,
  2475. append=True,
  2476. tooldia=None,
  2477. tolerance=0,
  2478. multidepth=False,
  2479. depthpercut=None):
  2480. """
  2481. Second algorithm to generate from Geometry.
  2482. ALgorithm description:
  2483. ----------------------
  2484. Uses RTree to find the nearest path to follow.
  2485. :param geometry:
  2486. :param append:
  2487. :param tooldia:
  2488. :param tolerance:
  2489. :param multidepth: If True, use multiple passes to reach
  2490. the desired depth.
  2491. :param depthpercut: Maximum depth in each pass.
  2492. :return: None
  2493. """
  2494. assert isinstance(geometry, Geometry), \
  2495. "Expected a Geometry, got %s" % type(geometry)
  2496. log.debug("generate_from_geometry_2()")
  2497. ## Flatten the geometry
  2498. # Only linear elements (no polygons) remain.
  2499. flat_geometry = geometry.flatten(pathonly=True)
  2500. log.debug("%d paths" % len(flat_geometry))
  2501. ## Index first and last points in paths
  2502. # What points to index.
  2503. def get_pts(o):
  2504. return [o.coords[0], o.coords[-1]]
  2505. # Create the indexed storage.
  2506. storage = FlatCAMRTreeStorage()
  2507. storage.get_points = get_pts
  2508. # Store the geometry
  2509. log.debug("Indexing geometry before generating G-Code...")
  2510. for shape in flat_geometry:
  2511. if shape is not None: # TODO: This shouldn't have happened.
  2512. storage.insert(shape)
  2513. if tooldia is not None:
  2514. self.tooldia = tooldia
  2515. # self.input_geometry_bounds = geometry.bounds()
  2516. if not append:
  2517. self.gcode = ""
  2518. # Initial G-Code
  2519. self.gcode = self.unitcode[self.units.upper()] + "\n"
  2520. self.gcode += self.absolutecode + "\n"
  2521. self.gcode += self.feedminutecode + "\n"
  2522. self.gcode += "F%.2f\n" % self.feedrate
  2523. self.gcode += "G00 Z%.4f\n" % self.z_move # Move (up) to travel height
  2524. if self.spindlespeed is not None:
  2525. self.gcode += "M03 S%d\n" % int(self.spindlespeed) # Spindle start with configured speed
  2526. else:
  2527. self.gcode += "M03\n" # Spindle start
  2528. #self.gcode += self.pausecode + "\n"
  2529. ## Iterate over geometry paths getting the nearest each time.
  2530. log.debug("Starting G-Code...")
  2531. path_count = 0
  2532. current_pt = (0, 0)
  2533. pt, geo = storage.nearest(current_pt)
  2534. try:
  2535. while True:
  2536. path_count += 1
  2537. #print "Current: ", "(%.3f, %.3f)" % current_pt
  2538. # Remove before modifying, otherwise
  2539. # deletion will fail.
  2540. storage.remove(geo)
  2541. # If last point in geometry is the nearest
  2542. # but prefer the first one if last point == first point
  2543. # then reverse coordinates.
  2544. if pt != geo.coords[0] and pt == geo.coords[-1]:
  2545. geo.coords = list(geo.coords)[::-1]
  2546. #---------- Single depth/pass --------
  2547. if not multidepth:
  2548. # G-code
  2549. # Note: self.linear2gcode() and self.point2gcode() will
  2550. # lower and raise the tool every time.
  2551. if type(geo) == LineString or type(geo) == LinearRing:
  2552. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  2553. elif type(geo) == Point:
  2554. self.gcode += self.point2gcode(geo)
  2555. else:
  2556. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  2557. #--------- Multi-pass ---------
  2558. else:
  2559. if isinstance(self.z_cut, Decimal):
  2560. z_cut = self.z_cut
  2561. else:
  2562. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  2563. if depthpercut is None:
  2564. depthpercut = z_cut
  2565. elif not isinstance(depthpercut, Decimal):
  2566. depthpercut = Decimal(depthpercut).quantize(Decimal('0.000000001'))
  2567. depth = 0
  2568. reverse = False
  2569. while depth > z_cut:
  2570. # Increase depth. Limit to z_cut.
  2571. depth -= depthpercut
  2572. if depth < z_cut:
  2573. depth = z_cut
  2574. # Cut at specific depth and do not lift the tool.
  2575. # Note: linear2gcode() will use G00 to move to the
  2576. # first point in the path, but it should be already
  2577. # at the first point if the tool is down (in the material).
  2578. # So, an extra G00 should show up but is inconsequential.
  2579. if type(geo) == LineString or type(geo) == LinearRing:
  2580. self.gcode += self.linear2gcode(geo, tolerance=tolerance,
  2581. zcut=depth,
  2582. up=False)
  2583. # Ignore multi-pass for points.
  2584. elif type(geo) == Point:
  2585. self.gcode += self.point2gcode(geo)
  2586. break # Ignoring ...
  2587. else:
  2588. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  2589. # Reverse coordinates if not a loop so we can continue
  2590. # cutting without returning to the beginning.
  2591. if type(geo) == LineString:
  2592. geo.coords = list(geo.coords)[::-1]
  2593. reverse = True
  2594. # If geometry is reversed, revert.
  2595. if reverse:
  2596. if type(geo) == LineString:
  2597. geo.coords = list(geo.coords)[::-1]
  2598. # Lift the tool
  2599. self.gcode += "G00 Z%.4f\n" % self.z_move
  2600. # self.gcode += "( End of path. )\n"
  2601. # Did deletion at the beginning.
  2602. # Delete from index, update current location and continue.
  2603. #rti.delete(hits[0], geo.coords[0])
  2604. #rti.delete(hits[0], geo.coords[-1])
  2605. current_pt = geo.coords[-1]
  2606. # Next
  2607. pt, geo = storage.nearest(current_pt)
  2608. except StopIteration: # Nothing found in storage.
  2609. pass
  2610. log.debug("%s paths traced." % path_count)
  2611. # Finish
  2612. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2613. self.gcode += "G00 X0Y0\n"
  2614. self.gcode += "M05\n" # Spindle stop
  2615. @staticmethod
  2616. def codes_split(gline):
  2617. """
  2618. Parses a line of G-Code such as "G01 X1234 Y987" into
  2619. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  2620. :param gline: G-Code line string
  2621. :return: Dictionary with parsed line.
  2622. """
  2623. command = {}
  2624. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  2625. while match:
  2626. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  2627. gline = gline[match.end():]
  2628. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  2629. return command
  2630. def gcode_parse(self):
  2631. """
  2632. G-Code parser (from self.gcode). Generates dictionary with
  2633. single-segment LineString's and "kind" indicating cut or travel,
  2634. fast or feedrate speed.
  2635. """
  2636. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  2637. # Results go here
  2638. geometry = []
  2639. # Last known instruction
  2640. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  2641. # Current path: temporary storage until tool is
  2642. # lifted or lowered.
  2643. path = [(0, 0)]
  2644. # Process every instruction
  2645. for line in StringIO(self.gcode):
  2646. gobj = self.codes_split(line)
  2647. ## Units
  2648. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  2649. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  2650. continue
  2651. ## Changing height
  2652. if 'Z' in gobj:
  2653. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  2654. log.warning("Non-orthogonal motion: From %s" % str(current))
  2655. log.warning(" To: %s" % str(gobj))
  2656. current['Z'] = gobj['Z']
  2657. # Store the path into geometry and reset path
  2658. if len(path) > 1:
  2659. geometry.append({"geom": LineString(path),
  2660. "kind": kind})
  2661. path = [path[-1]] # Start with the last point of last path.
  2662. if 'G' in gobj:
  2663. current['G'] = int(gobj['G'])
  2664. if 'X' in gobj or 'Y' in gobj:
  2665. if 'X' in gobj:
  2666. x = gobj['X']
  2667. else:
  2668. x = current['X']
  2669. if 'Y' in gobj:
  2670. y = gobj['Y']
  2671. else:
  2672. y = current['Y']
  2673. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  2674. if current['Z'] > 0:
  2675. kind[0] = 'T'
  2676. if current['G'] > 0:
  2677. kind[1] = 'S'
  2678. arcdir = [None, None, "cw", "ccw"]
  2679. if current['G'] in [0, 1]: # line
  2680. path.append((x, y))
  2681. if current['G'] in [2, 3]: # arc
  2682. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  2683. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  2684. start = arctan2(-gobj['J'], -gobj['I'])
  2685. stop = arctan2(-center[1] + y, -center[0] + x)
  2686. path += arc(center, radius, start, stop,
  2687. arcdir[current['G']],
  2688. self.steps_per_circ)
  2689. # Update current instruction
  2690. for code in gobj:
  2691. current[code] = gobj[code]
  2692. # There might not be a change in height at the
  2693. # end, therefore, see here too if there is
  2694. # a final path.
  2695. if len(path) > 1:
  2696. geometry.append({"geom": LineString(path),
  2697. "kind": kind})
  2698. self.gcode_parsed = geometry
  2699. return geometry
  2700. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  2701. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  2702. # alpha={"T": 0.3, "C": 1.0}):
  2703. # """
  2704. # Creates a Matplotlib figure with a plot of the
  2705. # G-code job.
  2706. # """
  2707. # if tooldia is None:
  2708. # tooldia = self.tooldia
  2709. #
  2710. # fig = Figure(dpi=dpi)
  2711. # ax = fig.add_subplot(111)
  2712. # ax.set_aspect(1)
  2713. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  2714. # ax.set_xlim(xmin-margin, xmax+margin)
  2715. # ax.set_ylim(ymin-margin, ymax+margin)
  2716. #
  2717. # if tooldia == 0:
  2718. # for geo in self.gcode_parsed:
  2719. # linespec = '--'
  2720. # linecolor = color[geo['kind'][0]][1]
  2721. # if geo['kind'][0] == 'C':
  2722. # linespec = 'k-'
  2723. # x, y = geo['geom'].coords.xy
  2724. # ax.plot(x, y, linespec, color=linecolor)
  2725. # else:
  2726. # for geo in self.gcode_parsed:
  2727. # poly = geo['geom'].buffer(tooldia/2.0)
  2728. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  2729. # edgecolor=color[geo['kind'][0]][1],
  2730. # alpha=alpha[geo['kind'][0]], zorder=2)
  2731. # ax.add_patch(patch)
  2732. #
  2733. # return fig
  2734. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  2735. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  2736. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005):
  2737. """
  2738. Plots the G-code job onto the given axes.
  2739. :param axes: Matplotlib axes on which to plot.
  2740. :param tooldia: Tool diameter.
  2741. :param dpi: Not used!
  2742. :param margin: Not used!
  2743. :param color: Color specification.
  2744. :param alpha: Transparency specification.
  2745. :param tool_tolerance: Tolerance when drawing the toolshape.
  2746. :return: None
  2747. """
  2748. path_num = 0
  2749. if tooldia is None:
  2750. tooldia = self.tooldia
  2751. if tooldia == 0:
  2752. for geo in self.gcode_parsed:
  2753. linespec = '--'
  2754. linecolor = color[geo['kind'][0]][1]
  2755. if geo['kind'][0] == 'C':
  2756. linespec = 'k-'
  2757. x, y = geo['geom'].coords.xy
  2758. axes.plot(x, y, linespec, color=linecolor)
  2759. else:
  2760. for geo in self.gcode_parsed:
  2761. path_num += 1
  2762. axes.annotate(str(path_num), xy=geo['geom'].coords[0],
  2763. xycoords='data')
  2764. poly = geo['geom'].buffer(tooldia / 2.0).simplify(tool_tolerance)
  2765. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  2766. edgecolor=color[geo['kind'][0]][1],
  2767. alpha=alpha[geo['kind'][0]], zorder=2)
  2768. axes.add_patch(patch)
  2769. def create_geometry(self):
  2770. # TODO: This takes forever. Too much data?
  2771. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  2772. def linear2gcode(self, linear, tolerance=0, down=True, up=True,
  2773. zcut=None, ztravel=None, downrate=None,
  2774. feedrate=None, cont=False):
  2775. """
  2776. Generates G-code to cut along the linear feature.
  2777. :param linear: The path to cut along.
  2778. :type: Shapely.LinearRing or Shapely.Linear String
  2779. :param tolerance: All points in the simplified object will be within the
  2780. tolerance distance of the original geometry.
  2781. :type tolerance: float
  2782. :return: G-code to cut along the linear feature.
  2783. :rtype: str
  2784. """
  2785. if zcut is None:
  2786. zcut = self.z_cut
  2787. if ztravel is None:
  2788. ztravel = self.z_move
  2789. if downrate is None:
  2790. downrate = self.zdownrate
  2791. if feedrate is None:
  2792. feedrate = self.feedrate
  2793. t = "G0%d " + CNCjob.defaults["coordinate_format"] + "\n"
  2794. # Simplify paths?
  2795. if tolerance > 0:
  2796. target_linear = linear.simplify(tolerance)
  2797. else:
  2798. target_linear = linear
  2799. gcode = ""
  2800. path = list(target_linear.coords)
  2801. # Move fast to 1st point
  2802. if not cont:
  2803. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2804. # Move down to cutting depth
  2805. if down:
  2806. # Different feedrate for vertical cut?
  2807. if self.zdownrate is not None:
  2808. gcode += "F%.2f\n" % downrate
  2809. gcode += "G01 Z%.4f\n" % zcut # Start cutting
  2810. gcode += "F%.2f\n" % feedrate # Restore feedrate
  2811. else:
  2812. gcode += "G01 Z%.4f\n" % zcut # Start cutting
  2813. # Cutting...
  2814. for pt in path[1:]:
  2815. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  2816. # Up to travelling height.
  2817. if up:
  2818. gcode += "G00 Z%.4f\n" % ztravel # Stop cutting
  2819. return gcode
  2820. def point2gcode(self, point):
  2821. gcode = ""
  2822. #t = "G0%d X%.4fY%.4f\n"
  2823. t = "G0%d " + CNCjob.defaults["coordinate_format"] + "\n"
  2824. path = list(point.coords)
  2825. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2826. if self.zdownrate is not None:
  2827. gcode += "F%.2f\n" % self.zdownrate
  2828. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2829. gcode += "F%.2f\n" % self.feedrate
  2830. else:
  2831. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2832. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2833. return gcode
  2834. def scale(self, factor):
  2835. """
  2836. Scales all the geometry on the XY plane in the object by the
  2837. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  2838. not altered.
  2839. :param factor: Number by which to scale the object.
  2840. :type factor: float
  2841. :return: None
  2842. :rtype: None
  2843. """
  2844. for g in self.gcode_parsed:
  2845. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  2846. self.create_geometry()
  2847. def offset(self, vect):
  2848. """
  2849. Offsets all the geometry on the XY plane in the object by the
  2850. given vector.
  2851. :param vect: (x, y) offset vector.
  2852. :type vect: tuple
  2853. :return: None
  2854. """
  2855. dx, dy = vect
  2856. for g in self.gcode_parsed:
  2857. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  2858. self.create_geometry()
  2859. def export_svg(self, scale_factor=0.00):
  2860. """
  2861. Exports the CNC Job as a SVG Element
  2862. :scale_factor: float
  2863. :return: SVG Element string
  2864. """
  2865. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  2866. # If not specified then try and use the tool diameter
  2867. # This way what is on screen will match what is outputed for the svg
  2868. # This is quite a useful feature for svg's used with visicut
  2869. if scale_factor <= 0:
  2870. scale_factor = self.options['tooldia'] / 2
  2871. # If still 0 then defailt to 0.05
  2872. # This value appears to work for zooming, and getting the output svg line width
  2873. # to match that viewed on screen with FlatCam
  2874. if scale_factor == 0:
  2875. scale_factor = 0.05
  2876. # Seperate the list of cuts and travels into 2 distinct lists
  2877. # This way we can add different formatting / colors to both
  2878. cuts = []
  2879. travels = []
  2880. for g in self.gcode_parsed:
  2881. if g['kind'][0] == 'C': cuts.append(g)
  2882. if g['kind'][0] == 'T': travels.append(g)
  2883. # Used to determine the overall board size
  2884. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  2885. # Convert the cuts and travels into single geometry objects we can render as svg xml
  2886. if travels:
  2887. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  2888. if cuts:
  2889. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  2890. # Render the SVG Xml
  2891. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  2892. # It's better to have the travels sitting underneath the cuts for visicut
  2893. svg_elem = ""
  2894. if travels:
  2895. svg_elem = travelsgeom.svg(scale_factor=scale_factor, stroke_color="#F0E24D")
  2896. if cuts:
  2897. svg_elem += cutsgeom.svg(scale_factor=scale_factor, stroke_color="#5E6CFF")
  2898. return svg_elem
  2899. # def get_bounds(geometry_set):
  2900. # xmin = Inf
  2901. # ymin = Inf
  2902. # xmax = -Inf
  2903. # ymax = -Inf
  2904. #
  2905. # #print "Getting bounds of:", str(geometry_set)
  2906. # for gs in geometry_set:
  2907. # try:
  2908. # gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  2909. # xmin = min([xmin, gxmin])
  2910. # ymin = min([ymin, gymin])
  2911. # xmax = max([xmax, gxmax])
  2912. # ymax = max([ymax, gymax])
  2913. # except:
  2914. # print "DEV WARNING: Tried to get bounds of empty geometry."
  2915. #
  2916. # return [xmin, ymin, xmax, ymax]
  2917. def get_bounds(geometry_list):
  2918. xmin = Inf
  2919. ymin = Inf
  2920. xmax = -Inf
  2921. ymax = -Inf
  2922. #print "Getting bounds of:", str(geometry_set)
  2923. for gs in geometry_list:
  2924. try:
  2925. gxmin, gymin, gxmax, gymax = gs.bounds()
  2926. xmin = min([xmin, gxmin])
  2927. ymin = min([ymin, gymin])
  2928. xmax = max([xmax, gxmax])
  2929. ymax = max([ymax, gymax])
  2930. except:
  2931. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  2932. return [xmin, ymin, xmax, ymax]
  2933. def arc(center, radius, start, stop, direction, steps_per_circ):
  2934. """
  2935. Creates a list of point along the specified arc.
  2936. :param center: Coordinates of the center [x, y]
  2937. :type center: list
  2938. :param radius: Radius of the arc.
  2939. :type radius: float
  2940. :param start: Starting angle in radians
  2941. :type start: float
  2942. :param stop: End angle in radians
  2943. :type stop: float
  2944. :param direction: Orientation of the arc, "CW" or "CCW"
  2945. :type direction: string
  2946. :param steps_per_circ: Number of straight line segments to
  2947. represent a circle.
  2948. :type steps_per_circ: int
  2949. :return: The desired arc, as list of tuples
  2950. :rtype: list
  2951. """
  2952. # TODO: Resolution should be established by maximum error from the exact arc.
  2953. da_sign = {"cw": -1.0, "ccw": 1.0}
  2954. points = []
  2955. if direction == "ccw" and stop <= start:
  2956. stop += 2 * pi
  2957. if direction == "cw" and stop >= start:
  2958. stop -= 2 * pi
  2959. angle = abs(stop - start)
  2960. #angle = stop-start
  2961. steps = max([int(ceil(angle / (2 * pi) * steps_per_circ)), 2])
  2962. delta_angle = da_sign[direction] * angle * 1.0 / steps
  2963. for i in range(steps + 1):
  2964. theta = start + delta_angle * i
  2965. points.append((center[0] + radius * cos(theta), center[1] + radius * sin(theta)))
  2966. return points
  2967. def arc2(p1, p2, center, direction, steps_per_circ):
  2968. r = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  2969. start = arctan2(p1[1] - center[1], p1[0] - center[0])
  2970. stop = arctan2(p2[1] - center[1], p2[0] - center[0])
  2971. return arc(center, r, start, stop, direction, steps_per_circ)
  2972. def arc_angle(start, stop, direction):
  2973. if direction == "ccw" and stop <= start:
  2974. stop += 2 * pi
  2975. if direction == "cw" and stop >= start:
  2976. stop -= 2 * pi
  2977. angle = abs(stop - start)
  2978. return angle
  2979. # def find_polygon(poly, point):
  2980. # """
  2981. # Find an object that object.contains(Point(point)) in
  2982. # poly, which can can be iterable, contain iterable of, or
  2983. # be itself an implementer of .contains().
  2984. #
  2985. # :param poly: See description
  2986. # :return: Polygon containing point or None.
  2987. # """
  2988. #
  2989. # if poly is None:
  2990. # return None
  2991. #
  2992. # try:
  2993. # for sub_poly in poly:
  2994. # p = find_polygon(sub_poly, point)
  2995. # if p is not None:
  2996. # return p
  2997. # except TypeError:
  2998. # try:
  2999. # if poly.contains(Point(point)):
  3000. # return poly
  3001. # except AttributeError:
  3002. # return None
  3003. #
  3004. # return None
  3005. def to_dict(obj):
  3006. """
  3007. Makes the following types into serializable form:
  3008. * ApertureMacro
  3009. * BaseGeometry
  3010. :param obj: Shapely geometry.
  3011. :type obj: BaseGeometry
  3012. :return: Dictionary with serializable form if ``obj`` was
  3013. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  3014. """
  3015. if isinstance(obj, ApertureMacro):
  3016. return {
  3017. "__class__": "ApertureMacro",
  3018. "__inst__": obj.to_dict()
  3019. }
  3020. if isinstance(obj, BaseGeometry):
  3021. return {
  3022. "__class__": "Shply",
  3023. "__inst__": sdumps(obj)
  3024. }
  3025. return obj
  3026. def dict2obj(d):
  3027. """
  3028. Default deserializer.
  3029. :param d: Serializable dictionary representation of an object
  3030. to be reconstructed.
  3031. :return: Reconstructed object.
  3032. """
  3033. if '__class__' in d and '__inst__' in d:
  3034. if d['__class__'] == "Shply":
  3035. return sloads(d['__inst__'])
  3036. if d['__class__'] == "ApertureMacro":
  3037. am = ApertureMacro()
  3038. am.from_dict(d['__inst__'])
  3039. return am
  3040. return d
  3041. else:
  3042. return d
  3043. def plotg(geo, solid_poly=False, color="black"):
  3044. try:
  3045. _ = iter(geo)
  3046. except:
  3047. geo = [geo]
  3048. for g in geo:
  3049. if type(g) == Polygon:
  3050. if solid_poly:
  3051. patch = PolygonPatch(g,
  3052. facecolor="#BBF268",
  3053. edgecolor="#006E20",
  3054. alpha=0.75,
  3055. zorder=2)
  3056. ax = subplot(111)
  3057. ax.add_patch(patch)
  3058. else:
  3059. x, y = g.exterior.coords.xy
  3060. plot(x, y, color=color)
  3061. for ints in g.interiors:
  3062. x, y = ints.coords.xy
  3063. plot(x, y, color=color)
  3064. continue
  3065. if type(g) == LineString or type(g) == LinearRing:
  3066. x, y = g.coords.xy
  3067. plot(x, y, color=color)
  3068. continue
  3069. if type(g) == Point:
  3070. x, y = g.coords.xy
  3071. plot(x, y, 'o')
  3072. continue
  3073. try:
  3074. _ = iter(g)
  3075. plotg(g, color=color)
  3076. except:
  3077. log.error("Cannot plot: " + str(type(g)))
  3078. continue
  3079. def parse_gerber_number(strnumber, frac_digits):
  3080. """
  3081. Parse a single number of Gerber coordinates.
  3082. :param strnumber: String containing a number in decimal digits
  3083. from a coordinate data block, possibly with a leading sign.
  3084. :type strnumber: str
  3085. :param frac_digits: Number of digits used for the fractional
  3086. part of the number
  3087. :type frac_digits: int
  3088. :return: The number in floating point.
  3089. :rtype: float
  3090. """
  3091. return int(strnumber) * (10 ** (-frac_digits))
  3092. # def voronoi(P):
  3093. # """
  3094. # Returns a list of all edges of the voronoi diagram for the given input points.
  3095. # """
  3096. # delauny = Delaunay(P)
  3097. # triangles = delauny.points[delauny.vertices]
  3098. #
  3099. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  3100. # long_lines_endpoints = []
  3101. #
  3102. # lineIndices = []
  3103. # for i, triangle in enumerate(triangles):
  3104. # circum_center = circum_centers[i]
  3105. # for j, neighbor in enumerate(delauny.neighbors[i]):
  3106. # if neighbor != -1:
  3107. # lineIndices.append((i, neighbor))
  3108. # else:
  3109. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  3110. # ps = np.array((ps[1], -ps[0]))
  3111. #
  3112. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  3113. # di = middle - triangle[j]
  3114. #
  3115. # ps /= np.linalg.norm(ps)
  3116. # di /= np.linalg.norm(di)
  3117. #
  3118. # if np.dot(di, ps) < 0.0:
  3119. # ps *= -1000.0
  3120. # else:
  3121. # ps *= 1000.0
  3122. #
  3123. # long_lines_endpoints.append(circum_center + ps)
  3124. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  3125. #
  3126. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  3127. #
  3128. # # filter out any duplicate lines
  3129. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  3130. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  3131. # lineIndicesUnique = np.unique(lineIndicesTupled)
  3132. #
  3133. # return vertices, lineIndicesUnique
  3134. #
  3135. #
  3136. # def triangle_csc(pts):
  3137. # rows, cols = pts.shape
  3138. #
  3139. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  3140. # [np.ones((1, rows)), np.zeros((1, 1))]])
  3141. #
  3142. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  3143. # x = np.linalg.solve(A,b)
  3144. # bary_coords = x[:-1]
  3145. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  3146. #
  3147. #
  3148. # def voronoi_cell_lines(points, vertices, lineIndices):
  3149. # """
  3150. # Returns a mapping from a voronoi cell to its edges.
  3151. #
  3152. # :param points: shape (m,2)
  3153. # :param vertices: shape (n,2)
  3154. # :param lineIndices: shape (o,2)
  3155. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  3156. # """
  3157. # kd = KDTree(points)
  3158. #
  3159. # cells = collections.defaultdict(list)
  3160. # for i1, i2 in lineIndices:
  3161. # v1, v2 = vertices[i1], vertices[i2]
  3162. # mid = (v1+v2)/2
  3163. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  3164. # cells[p1Idx].append((i1, i2))
  3165. # cells[p2Idx].append((i1, i2))
  3166. #
  3167. # return cells
  3168. #
  3169. #
  3170. # def voronoi_edges2polygons(cells):
  3171. # """
  3172. # Transforms cell edges into polygons.
  3173. #
  3174. # :param cells: as returned from voronoi_cell_lines
  3175. # :rtype: dict point index -> list of vertex indices which form a polygon
  3176. # """
  3177. #
  3178. # # first, close the outer cells
  3179. # for pIdx, lineIndices_ in cells.items():
  3180. # dangling_lines = []
  3181. # for i1, i2 in lineIndices_:
  3182. # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  3183. # assert 1 <= len(connections) <= 2
  3184. # if len(connections) == 1:
  3185. # dangling_lines.append((i1, i2))
  3186. # assert len(dangling_lines) in [0, 2]
  3187. # if len(dangling_lines) == 2:
  3188. # (i11, i12), (i21, i22) = dangling_lines
  3189. #
  3190. # # determine which line ends are unconnected
  3191. # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  3192. # i11Unconnected = len(connected) == 0
  3193. #
  3194. # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  3195. # i21Unconnected = len(connected) == 0
  3196. #
  3197. # startIdx = i11 if i11Unconnected else i12
  3198. # endIdx = i21 if i21Unconnected else i22
  3199. #
  3200. # cells[pIdx].append((startIdx, endIdx))
  3201. #
  3202. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  3203. # polys = dict()
  3204. # for pIdx, lineIndices_ in cells.items():
  3205. # # get a directed graph which contains both directions and arbitrarily follow one of both
  3206. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  3207. # directedGraphMap = collections.defaultdict(list)
  3208. # for (i1, i2) in directedGraph:
  3209. # directedGraphMap[i1].append(i2)
  3210. # orderedEdges = []
  3211. # currentEdge = directedGraph[0]
  3212. # while len(orderedEdges) < len(lineIndices_):
  3213. # i1 = currentEdge[1]
  3214. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  3215. # nextEdge = (i1, i2)
  3216. # orderedEdges.append(nextEdge)
  3217. # currentEdge = nextEdge
  3218. #
  3219. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  3220. #
  3221. # return polys
  3222. #
  3223. #
  3224. # def voronoi_polygons(points):
  3225. # """
  3226. # Returns the voronoi polygon for each input point.
  3227. #
  3228. # :param points: shape (n,2)
  3229. # :rtype: list of n polygons where each polygon is an array of vertices
  3230. # """
  3231. # vertices, lineIndices = voronoi(points)
  3232. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  3233. # polys = voronoi_edges2polygons(cells)
  3234. # polylist = []
  3235. # for i in xrange(len(points)):
  3236. # poly = vertices[np.asarray(polys[i])]
  3237. # polylist.append(poly)
  3238. # return polylist
  3239. #
  3240. #
  3241. # class Zprofile:
  3242. # def __init__(self):
  3243. #
  3244. # # data contains lists of [x, y, z]
  3245. # self.data = []
  3246. #
  3247. # # Computed voronoi polygons (shapely)
  3248. # self.polygons = []
  3249. # pass
  3250. #
  3251. # def plot_polygons(self):
  3252. # axes = plt.subplot(1, 1, 1)
  3253. #
  3254. # plt.axis([-0.05, 1.05, -0.05, 1.05])
  3255. #
  3256. # for poly in self.polygons:
  3257. # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  3258. # axes.add_patch(p)
  3259. #
  3260. # def init_from_csv(self, filename):
  3261. # pass
  3262. #
  3263. # def init_from_string(self, zpstring):
  3264. # pass
  3265. #
  3266. # def init_from_list(self, zplist):
  3267. # self.data = zplist
  3268. #
  3269. # def generate_polygons(self):
  3270. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  3271. #
  3272. # def normalize(self, origin):
  3273. # pass
  3274. #
  3275. # def paste(self, path):
  3276. # """
  3277. # Return a list of dictionaries containing the parts of the original
  3278. # path and their z-axis offset.
  3279. # """
  3280. #
  3281. # # At most one region/polygon will contain the path
  3282. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  3283. #
  3284. # if len(containing) > 0:
  3285. # return [{"path": path, "z": self.data[containing[0]][2]}]
  3286. #
  3287. # # All region indexes that intersect with the path
  3288. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  3289. #
  3290. # return [{"path": path.intersection(self.polygons[i]),
  3291. # "z": self.data[i][2]} for i in crossing]
  3292. def autolist(obj):
  3293. try:
  3294. _ = iter(obj)
  3295. return obj
  3296. except TypeError:
  3297. return [obj]
  3298. def three_point_circle(p1, p2, p3):
  3299. """
  3300. Computes the center and radius of a circle from
  3301. 3 points on its circumference.
  3302. :param p1: Point 1
  3303. :param p2: Point 2
  3304. :param p3: Point 3
  3305. :return: center, radius
  3306. """
  3307. # Midpoints
  3308. a1 = (p1 + p2) / 2.0
  3309. a2 = (p2 + p3) / 2.0
  3310. # Normals
  3311. b1 = dot((p2 - p1), array([[0, -1], [1, 0]], dtype=float32))
  3312. b2 = dot((p3 - p2), array([[0, 1], [-1, 0]], dtype=float32))
  3313. # Params
  3314. T = solve(transpose(array([-b1, b2])), a1 - a2)
  3315. # Center
  3316. center = a1 + b1 * T[0]
  3317. # Radius
  3318. radius = norm(center - p1)
  3319. return center, radius, T[0]
  3320. def distance(pt1, pt2):
  3321. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  3322. class FlatCAMRTree(object):
  3323. """
  3324. Indexes geometry (Any object with "cooords" property containing
  3325. a list of tuples with x, y values). Objects are indexed by
  3326. all their points by default. To index by arbitrary points,
  3327. override self.points2obj.
  3328. """
  3329. def __init__(self):
  3330. # Python RTree Index
  3331. self.rti = rtindex.Index()
  3332. ## Track object-point relationship
  3333. # Each is list of points in object.
  3334. self.obj2points = []
  3335. # Index is index in rtree, value is index of
  3336. # object in obj2points.
  3337. self.points2obj = []
  3338. self.get_points = lambda go: go.coords
  3339. def grow_obj2points(self, idx):
  3340. """
  3341. Increases the size of self.obj2points to fit
  3342. idx + 1 items.
  3343. :param idx: Index to fit into list.
  3344. :return: None
  3345. """
  3346. if len(self.obj2points) > idx:
  3347. # len == 2, idx == 1, ok.
  3348. return
  3349. else:
  3350. # len == 2, idx == 2, need 1 more.
  3351. # range(2, 3)
  3352. for i in range(len(self.obj2points), idx + 1):
  3353. self.obj2points.append([])
  3354. def insert(self, objid, obj):
  3355. self.grow_obj2points(objid)
  3356. self.obj2points[objid] = []
  3357. for pt in self.get_points(obj):
  3358. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  3359. self.obj2points[objid].append(len(self.points2obj))
  3360. self.points2obj.append(objid)
  3361. def remove_obj(self, objid, obj):
  3362. # Use all ptids to delete from index
  3363. for i, pt in enumerate(self.get_points(obj)):
  3364. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  3365. def nearest(self, pt):
  3366. """
  3367. Will raise StopIteration if no items are found.
  3368. :param pt:
  3369. :return:
  3370. """
  3371. return next(self.rti.nearest(pt, objects=True))
  3372. class FlatCAMRTreeStorage(FlatCAMRTree):
  3373. """
  3374. Just like FlatCAMRTree it indexes geometry, but also serves
  3375. as storage for the geometry.
  3376. """
  3377. def __init__(self):
  3378. super(FlatCAMRTreeStorage, self).__init__()
  3379. self.objects = []
  3380. # Optimization attempt!
  3381. self.indexes = {}
  3382. def insert(self, obj):
  3383. self.objects.append(obj)
  3384. idx = len(self.objects) - 1
  3385. # Note: Shapely objects are not hashable any more, althought
  3386. # there seem to be plans to re-introduce the feature in
  3387. # version 2.0. For now, we will index using the object's id,
  3388. # but it's important to remember that shapely geometry is
  3389. # mutable, ie. it can be modified to a totally different shape
  3390. # and continue to have the same id.
  3391. # self.indexes[obj] = idx
  3392. self.indexes[id(obj)] = idx
  3393. super(FlatCAMRTreeStorage, self).insert(idx, obj)
  3394. #@profile
  3395. def remove(self, obj):
  3396. # See note about self.indexes in insert().
  3397. # objidx = self.indexes[obj]
  3398. objidx = self.indexes[id(obj)]
  3399. # Remove from list
  3400. self.objects[objidx] = None
  3401. # Remove from index
  3402. self.remove_obj(objidx, obj)
  3403. def get_objects(self):
  3404. return (o for o in self.objects if o is not None)
  3405. def nearest(self, pt):
  3406. """
  3407. Returns the nearest matching points and the object
  3408. it belongs to.
  3409. :param pt: Query point.
  3410. :return: (match_x, match_y), Object owner of
  3411. matching point.
  3412. :rtype: tuple
  3413. """
  3414. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  3415. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  3416. # class myO:
  3417. # def __init__(self, coords):
  3418. # self.coords = coords
  3419. #
  3420. #
  3421. # def test_rti():
  3422. #
  3423. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  3424. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  3425. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  3426. #
  3427. # os = [o1, o2]
  3428. #
  3429. # idx = FlatCAMRTree()
  3430. #
  3431. # for o in range(len(os)):
  3432. # idx.insert(o, os[o])
  3433. #
  3434. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3435. #
  3436. # idx.remove_obj(0, o1)
  3437. #
  3438. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3439. #
  3440. # idx.remove_obj(1, o2)
  3441. #
  3442. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3443. #
  3444. #
  3445. # def test_rtis():
  3446. #
  3447. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  3448. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  3449. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  3450. #
  3451. # os = [o1, o2]
  3452. #
  3453. # idx = FlatCAMRTreeStorage()
  3454. #
  3455. # for o in range(len(os)):
  3456. # idx.insert(os[o])
  3457. #
  3458. # #os = None
  3459. # #o1 = None
  3460. # #o2 = None
  3461. #
  3462. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3463. #
  3464. # idx.remove(idx.nearest((2,0))[1])
  3465. #
  3466. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3467. #
  3468. # idx.remove(idx.nearest((0,0))[1])
  3469. #
  3470. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]