camlib.py 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://caram.cl/software/flatcam #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import traceback
  9. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos
  10. from matplotlib.figure import Figure
  11. import re
  12. # See: http://toblerity.org/shapely/manual.html
  13. from shapely.geometry import Polygon, LineString, Point, LinearRing
  14. from shapely.geometry import MultiPoint, MultiPolygon
  15. from shapely.geometry import box as shply_box
  16. from shapely.ops import cascaded_union
  17. import shapely.affinity as affinity
  18. from shapely.wkt import loads as sloads
  19. from shapely.wkt import dumps as sdumps
  20. from shapely.geometry.base import BaseGeometry
  21. # Used for solid polygons in Matplotlib
  22. from descartes.patch import PolygonPatch
  23. import simplejson as json
  24. # TODO: Commented for FlatCAM packaging with cx_freeze
  25. #from matplotlib.pyplot import plot
  26. import logging
  27. log = logging.getLogger('base2')
  28. #log.setLevel(logging.DEBUG)
  29. #log.setLevel(logging.WARNING)
  30. log.setLevel(logging.INFO)
  31. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  32. handler = logging.StreamHandler()
  33. handler.setFormatter(formatter)
  34. log.addHandler(handler)
  35. class Geometry(object):
  36. def __init__(self):
  37. # Units (in or mm)
  38. self.units = 'in'
  39. # Final geometry: MultiPolygon
  40. self.solid_geometry = None
  41. # Attributes to be included in serialization
  42. self.ser_attrs = ['units', 'solid_geometry']
  43. def isolation_geometry(self, offset):
  44. """
  45. Creates contours around geometry at a given
  46. offset distance.
  47. :param offset: Offset distance.
  48. :type offset: float
  49. :return: The buffered geometry.
  50. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  51. """
  52. return self.solid_geometry.buffer(offset)
  53. def bounds(self):
  54. """
  55. Returns coordinates of rectangular bounds
  56. of geometry: (xmin, ymin, xmax, ymax).
  57. """
  58. if self.solid_geometry is None:
  59. log.warning("solid_geometry not computed yet.")
  60. return (0, 0, 0, 0)
  61. if type(self.solid_geometry) == list:
  62. # TODO: This can be done faster. See comment from Shapely mailing lists.
  63. return cascaded_union(self.solid_geometry).bounds
  64. else:
  65. return self.solid_geometry.bounds
  66. def size(self):
  67. """
  68. Returns (width, height) of rectangular
  69. bounds of geometry.
  70. """
  71. if self.solid_geometry is None:
  72. log.warning("Solid_geometry not computed yet.")
  73. return 0
  74. bounds = self.bounds()
  75. return (bounds[2]-bounds[0], bounds[3]-bounds[1])
  76. def get_empty_area(self, boundary=None):
  77. """
  78. Returns the complement of self.solid_geometry within
  79. the given boundary polygon. If not specified, it defaults to
  80. the rectangular bounding box of self.solid_geometry.
  81. """
  82. if boundary is None:
  83. boundary = self.solid_geometry.envelope
  84. return boundary.difference(self.solid_geometry)
  85. def clear_polygon(self, polygon, tooldia, overlap=0.15):
  86. """
  87. Creates geometry inside a polygon for a tool to cover
  88. the whole area.
  89. """
  90. poly_cuts = [polygon.buffer(-tooldia/2.0)]
  91. while True:
  92. polygon = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  93. if polygon.area > 0:
  94. poly_cuts.append(polygon)
  95. else:
  96. break
  97. return poly_cuts
  98. def scale(self, factor):
  99. """
  100. Scales all of the object's geometry by a given factor. Override
  101. this method.
  102. :param factor: Number by which to scale.
  103. :type factor: float
  104. :return: None
  105. :rtype: None
  106. """
  107. return
  108. def offset(self, vect):
  109. """
  110. Offset the geometry by the given vector. Override this method.
  111. :param vect: (x, y) vector by which to offset the object.
  112. :type vect: tuple
  113. :return: None
  114. """
  115. return
  116. def convert_units(self, units):
  117. """
  118. Converts the units of the object to ``units`` by scaling all
  119. the geometry appropriately. This call ``scale()``. Don't call
  120. it again in descendents.
  121. :param units: "IN" or "MM"
  122. :type units: str
  123. :return: Scaling factor resulting from unit change.
  124. :rtype: float
  125. """
  126. log.debug("Geometry.convert_units()")
  127. if units.upper() == self.units.upper():
  128. return 1.0
  129. if units.upper() == "MM":
  130. factor = 25.4
  131. elif units.upper() == "IN":
  132. factor = 1/25.4
  133. else:
  134. log.error("Unsupported units: %s" % str(units))
  135. return 1.0
  136. self.units = units
  137. self.scale(factor)
  138. return factor
  139. def to_dict(self):
  140. """
  141. Returns a respresentation of the object as a dictionary.
  142. Attributes to include are listed in ``self.ser_attrs``.
  143. :return: A dictionary-encoded copy of the object.
  144. :rtype: dict
  145. """
  146. d = {}
  147. for attr in self.ser_attrs:
  148. d[attr] = getattr(self, attr)
  149. return d
  150. def from_dict(self, d):
  151. """
  152. Sets object's attributes from a dictionary.
  153. Attributes to include are listed in ``self.ser_attrs``.
  154. This method will look only for only and all the
  155. attributes in ``self.ser_attrs``. They must all
  156. be present. Use only for deserializing saved
  157. objects.
  158. :param d: Dictionary of attributes to set in the object.
  159. :type d: dict
  160. :return: None
  161. """
  162. for attr in self.ser_attrs:
  163. setattr(self, attr, d[attr])
  164. class ApertureMacro:
  165. """
  166. Syntax of aperture macros.
  167. <AM command>: AM<Aperture macro name>*<Macro content>
  168. <Macro content>: {{<Variable definition>*}{<Primitive>*}}
  169. <Variable definition>: $K=<Arithmetic expression>
  170. <Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
  171. <Modifier>: $M|< Arithmetic expression>
  172. <Comment>: 0 <Text>
  173. """
  174. ## Regular expressions
  175. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  176. am2_re = re.compile(r'(.*)%$')
  177. amcomm_re = re.compile(r'^0(.*)')
  178. amprim_re = re.compile(r'^[1-9].*')
  179. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  180. def __init__(self, name=None):
  181. self.name = name
  182. self.raw = ""
  183. ## These below are recomputed for every aperture
  184. ## definition, in other words, are temporary variables.
  185. self.primitives = []
  186. self.locvars = {}
  187. self.geometry = None
  188. def to_dict(self):
  189. """
  190. Returns the object in a serializable form. Only the name and
  191. raw are required.
  192. :return: Dictionary representing the object. JSON ready.
  193. :rtype: dict
  194. """
  195. return {
  196. 'name': self.name,
  197. 'raw': self.raw
  198. }
  199. def from_dict(self, d):
  200. """
  201. Populates the object from a serial representation created
  202. with ``self.to_dict()``.
  203. :param d: Serial representation of an ApertureMacro object.
  204. :return: None
  205. """
  206. for attr in ['name', 'raw']:
  207. setattr(self, attr, d[attr])
  208. def parse_content(self):
  209. """
  210. Creates numerical lists for all primitives in the aperture
  211. macro (in ``self.raw``) by replacing all variables by their
  212. values iteratively and evaluating expressions. Results
  213. are stored in ``self.primitives``.
  214. :return: None
  215. """
  216. # Cleanup
  217. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  218. self.primitives = []
  219. # Separate parts
  220. parts = self.raw.split('*')
  221. #### Every part in the macro ####
  222. for part in parts:
  223. ### Comments. Ignored.
  224. match = ApertureMacro.amcomm_re.search(part)
  225. if match:
  226. continue
  227. ### Variables
  228. # These are variables defined locally inside the macro. They can be
  229. # numerical constant or defind in terms of previously define
  230. # variables, which can be defined locally or in an aperture
  231. # definition. All replacements ocurr here.
  232. match = ApertureMacro.amvar_re.search(part)
  233. if match:
  234. var = match.group(1)
  235. val = match.group(2)
  236. # Replace variables in value
  237. for v in self.locvars:
  238. val = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), val)
  239. # Make all others 0
  240. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  241. # Change x with *
  242. val = re.sub(r'[xX]', "*", val)
  243. # Eval() and store.
  244. self.locvars[var] = eval(val)
  245. continue
  246. ### Primitives
  247. # Each is an array. The first identifies the primitive, while the
  248. # rest depend on the primitive. All are strings representing a
  249. # number and may contain variable definition. The values of these
  250. # variables are defined in an aperture definition.
  251. match = ApertureMacro.amprim_re.search(part)
  252. if match:
  253. ## Replace all variables
  254. for v in self.locvars:
  255. part = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  256. # Make all others 0
  257. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  258. # Change x with *
  259. part = re.sub(r'[xX]', "*", part)
  260. ## Store
  261. elements = part.split(",")
  262. self.primitives.append([eval(x) for x in elements])
  263. continue
  264. log.warning("Unknown syntax of aperture macro part: %s" % str(part))
  265. def append(self, data):
  266. """
  267. Appends a string to the raw macro.
  268. :param data: Part of the macro.
  269. :type data: str
  270. :return: None
  271. """
  272. self.raw += data
  273. @staticmethod
  274. def default2zero(n, mods):
  275. """
  276. Pads the ``mods`` list with zeros resulting in an
  277. list of length n.
  278. :param n: Length of the resulting list.
  279. :type n: int
  280. :param mods: List to be padded.
  281. :type mods: list
  282. :return: Zero-padded list.
  283. :rtype: list
  284. """
  285. x = [0.0]*n
  286. na = len(mods)
  287. x[0:na] = mods
  288. return x
  289. @staticmethod
  290. def make_circle(mods):
  291. """
  292. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  293. :return:
  294. """
  295. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  296. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  297. @staticmethod
  298. def make_vectorline(mods):
  299. """
  300. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  301. rotation angle around origin in degrees)
  302. :return:
  303. """
  304. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  305. line = LineString([(xs, ys), (xe, ye)])
  306. box = line.buffer(width/2, cap_style=2)
  307. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  308. return {"pol": int(pol), "geometry": box_rotated}
  309. @staticmethod
  310. def make_centerline(mods):
  311. """
  312. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  313. rotation angle around origin in degrees)
  314. :return:
  315. """
  316. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  317. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  318. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  319. return {"pol": int(pol), "geometry": box_rotated}
  320. @staticmethod
  321. def make_lowerleftline(mods):
  322. """
  323. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  324. rotation angle around origin in degrees)
  325. :return:
  326. """
  327. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  328. box = shply_box(x, y, x+width, y+height)
  329. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  330. return {"pol": int(pol), "geometry": box_rotated}
  331. @staticmethod
  332. def make_outline(mods):
  333. """
  334. :param mods:
  335. :return:
  336. """
  337. pol = mods[0]
  338. n = mods[1]
  339. points = [(0, 0)]*(n+1)
  340. for i in range(n+1):
  341. points[i] = mods[2*i + 2:2*i + 4]
  342. angle = mods[2*n + 4]
  343. poly = Polygon(points)
  344. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  345. return {"pol": int(pol), "geometry": poly_rotated}
  346. @staticmethod
  347. def make_polygon(mods):
  348. """
  349. Note: Specs indicate that rotation is only allowed if the center
  350. (x, y) == (0, 0). I will tolerate breaking this rule.
  351. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  352. diameter of circumscribed circle >=0, rotation angle around origin)
  353. :return:
  354. """
  355. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  356. points = [(0, 0)]*nverts
  357. for i in range(nverts):
  358. points[i] = (x + 0.5 * dia * cos(2*pi * i/nverts),
  359. y + 0.5 * dia * sin(2*pi * i/nverts))
  360. poly = Polygon(points)
  361. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  362. return {"pol": int(pol), "geometry": poly_rotated}
  363. @staticmethod
  364. def make_moire(mods):
  365. """
  366. Note: Specs indicate that rotation is only allowed if the center
  367. (x, y) == (0, 0). I will tolerate breaking this rule.
  368. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  369. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  370. angle around origin in degrees)
  371. :return:
  372. """
  373. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  374. r = dia/2 - thickness/2
  375. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  376. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  377. i = 1 # Number of rings created so far
  378. ## If the ring does not have an interior it means that it is
  379. ## a disk. Then stop.
  380. while len(ring.interiors) > 0 and i < nrings:
  381. r -= thickness + gap
  382. if r <= 0:
  383. break
  384. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  385. result = cascaded_union([result, ring])
  386. i += 1
  387. ## Crosshair
  388. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  389. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  390. result = cascaded_union([result, hor, ver])
  391. return {"pol": 1, "geometry": result}
  392. @staticmethod
  393. def make_thermal(mods):
  394. """
  395. Note: Specs indicate that rotation is only allowed if the center
  396. (x, y) == (0, 0). I will tolerate breaking this rule.
  397. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  398. gap-thickness, rotation angle around origin]
  399. :return:
  400. """
  401. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  402. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  403. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  404. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  405. thermal = ring.difference(hline.union(vline))
  406. return {"pol": 1, "geometry": thermal}
  407. def make_geometry(self, modifiers):
  408. """
  409. Runs the macro for the given modifiers and generates
  410. the corresponding geometry.
  411. :param modifiers: Modifiers (parameters) for this macro
  412. :type modifiers: list
  413. """
  414. ## Primitive makers
  415. makers = {
  416. "1": ApertureMacro.make_circle,
  417. "2": ApertureMacro.make_vectorline,
  418. "20": ApertureMacro.make_vectorline,
  419. "21": ApertureMacro.make_centerline,
  420. "22": ApertureMacro.make_lowerleftline,
  421. "4": ApertureMacro.make_outline,
  422. "5": ApertureMacro.make_polygon,
  423. "6": ApertureMacro.make_moire,
  424. "7": ApertureMacro.make_thermal
  425. }
  426. ## Store modifiers as local variables
  427. modifiers = modifiers or []
  428. modifiers = [float(m) for m in modifiers]
  429. self.locvars = {}
  430. for i in range(0, len(modifiers)):
  431. self.locvars[str(i+1)] = modifiers[i]
  432. ## Parse
  433. self.primitives = [] # Cleanup
  434. self.geometry = None
  435. self.parse_content()
  436. ## Make the geometry
  437. for primitive in self.primitives:
  438. # Make the primitive
  439. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  440. # Add it (according to polarity)
  441. if self.geometry is None and prim_geo['pol'] == 1:
  442. self.geometry = prim_geo['geometry']
  443. continue
  444. if prim_geo['pol'] == 1:
  445. self.geometry = self.geometry.union(prim_geo['geometry'])
  446. continue
  447. if prim_geo['pol'] == 0:
  448. self.geometry = self.geometry.difference(prim_geo['geometry'])
  449. continue
  450. return self.geometry
  451. class Gerber (Geometry):
  452. """
  453. **ATTRIBUTES**
  454. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  455. The values are dictionaries key/value pairs which describe the aperture. The
  456. type key is always present and the rest depend on the key:
  457. +-----------+-----------------------------------+
  458. | Key | Value |
  459. +===========+===================================+
  460. | type | (str) "C", "R", "O", "P", or "AP" |
  461. +-----------+-----------------------------------+
  462. | others | Depend on ``type`` |
  463. +-----------+-----------------------------------+
  464. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  465. that can be instanciated with different parameters in an aperture
  466. definition. See ``apertures`` above. The key is the name of the macro,
  467. and the macro itself, the value, is a ``Aperture_Macro`` object.
  468. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  469. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  470. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  471. *buffering* (or thickening) the ``paths`` with the aperture. These are
  472. generated from ``paths`` in ``buffer_paths()``.
  473. **USAGE**::
  474. g = Gerber()
  475. g.parse_file(filename)
  476. g.create_geometry()
  477. do_something(s.solid_geometry)
  478. """
  479. def __init__(self):
  480. """
  481. The constructor takes no parameters. Use ``gerber.parse_files()``
  482. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  483. :return: Gerber object
  484. :rtype: Gerber
  485. """
  486. # Initialize parent
  487. Geometry.__init__(self)
  488. self.solid_geometry = Polygon()
  489. # Number format
  490. self.int_digits = 3
  491. """Number of integer digits in Gerber numbers. Used during parsing."""
  492. self.frac_digits = 4
  493. """Number of fraction digits in Gerber numbers. Used during parsing."""
  494. ## Gerber elements ##
  495. # Apertures {'id':{'type':chr,
  496. # ['size':float], ['width':float],
  497. # ['height':float]}, ...}
  498. self.apertures = {}
  499. # Aperture Macros
  500. self.aperture_macros = {}
  501. # Attributes to be included in serialization
  502. # Always append to it because it carries contents
  503. # from Geometry.
  504. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures',
  505. 'aperture_macros', 'solid_geometry']
  506. #### Parser patterns ####
  507. # FS - Format Specification
  508. # The format of X and Y must be the same!
  509. # L-omit leading zeros, T-omit trailing zeros
  510. # A-absolute notation, I-incremental notation
  511. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  512. # Mode (IN/MM)
  513. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  514. # Comment G04|G4
  515. self.comm_re = re.compile(r'^G0?4(.*)$')
  516. # AD - Aperture definition
  517. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z_$\.][a-zA-Z0-9_$\.]*)(?:,(.*))?\*%$')
  518. # AM - Aperture Macro
  519. # Beginning of macro (Ends with *%):
  520. #self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  521. # Tool change
  522. # May begin with G54 but that is deprecated
  523. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  524. # G01... - Linear interpolation plus flashes with coordinates
  525. # Operation code (D0x) missing is deprecated... oh well I will support it.
  526. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X(-?\d+))?(?=.*Y(-?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  527. # Operation code alone, usually just D03 (Flash)
  528. self.opcode_re = re.compile(r'^D0?([123])\*$')
  529. # G02/3... - Circular interpolation with coordinates
  530. # 2-clockwise, 3-counterclockwise
  531. # Operation code (D0x) missing is deprecated... oh well I will support it.
  532. # Optional start with G02 or G03, optional end with D01 or D02 with
  533. # optional coordinates but at least one in any order.
  534. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X(-?\d+))?(?=.*Y(-?\d+))' +
  535. '?(?=.*I(-?\d+))?(?=.*J(-?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  536. # G01/2/3 Occurring without coordinates
  537. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  538. # Single D74 or multi D75 quadrant for circular interpolation
  539. self.quad_re = re.compile(r'^G7([45])\*$')
  540. # Region mode on
  541. # In region mode, D01 starts a region
  542. # and D02 ends it. A new region can be started again
  543. # with D01. All contours must be closed before
  544. # D02 or G37.
  545. self.regionon_re = re.compile(r'^G36\*$')
  546. # Region mode off
  547. # Will end a region and come off region mode.
  548. # All contours must be closed before D02 or G37.
  549. self.regionoff_re = re.compile(r'^G37\*$')
  550. # End of file
  551. self.eof_re = re.compile(r'^M02\*')
  552. # IP - Image polarity
  553. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  554. # LP - Level polarity
  555. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  556. # Units (OBSOLETE)
  557. self.units_re = re.compile(r'^G7([01])\*$')
  558. # Absolute/Relative G90/1 (OBSOLETE)
  559. self.absrel_re = re.compile(r'^G9([01])\*$')
  560. # Aperture macros
  561. self.am1_re = re.compile(r'^%AM([^\*]+)\*([^%]+)?(%)?$')
  562. self.am2_re = re.compile(r'(.*)%$')
  563. # TODO: This is bad.
  564. self.steps_per_circ = 40
  565. def scale(self, factor):
  566. """
  567. Scales the objects' geometry on the XY plane by a given factor.
  568. These are:
  569. * ``buffered_paths``
  570. * ``flash_geometry``
  571. * ``solid_geometry``
  572. * ``regions``
  573. NOTE:
  574. Does not modify the data used to create these elements. If these
  575. are recreated, the scaling will be lost. This behavior was modified
  576. because of the complexity reached in this class.
  577. :param factor: Number by which to scale.
  578. :type factor: float
  579. :rtype : None
  580. """
  581. ## solid_geometry ???
  582. # It's a cascaded union of objects.
  583. self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  584. factor, origin=(0, 0))
  585. # # Now buffered_paths, flash_geometry and solid_geometry
  586. # self.create_geometry()
  587. def offset(self, vect):
  588. """
  589. Offsets the objects' geometry on the XY plane by a given vector.
  590. These are:
  591. * ``buffered_paths``
  592. * ``flash_geometry``
  593. * ``solid_geometry``
  594. * ``regions``
  595. NOTE:
  596. Does not modify the data used to create these elements. If these
  597. are recreated, the scaling will be lost. This behavior was modified
  598. because of the complexity reached in this class.
  599. :param vect: (x, y) offset vector.
  600. :type vect: tuple
  601. :return: None
  602. """
  603. dx, dy = vect
  604. ## Solid geometry
  605. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  606. def mirror(self, axis, point):
  607. """
  608. Mirrors the object around a specified axis passign through
  609. the given point. What is affected:
  610. * ``buffered_paths``
  611. * ``flash_geometry``
  612. * ``solid_geometry``
  613. * ``regions``
  614. NOTE:
  615. Does not modify the data used to create these elements. If these
  616. are recreated, the scaling will be lost. This behavior was modified
  617. because of the complexity reached in this class.
  618. :param axis: "X" or "Y" indicates around which axis to mirror.
  619. :type axis: str
  620. :param point: [x, y] point belonging to the mirror axis.
  621. :type point: list
  622. :return: None
  623. """
  624. px, py = point
  625. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  626. ## solid_geometry ???
  627. # It's a cascaded union of objects.
  628. self.solid_geometry = affinity.scale(self.solid_geometry,
  629. xscale, yscale, origin=(px, py))
  630. def aperture_parse(self, apertureId, apertureType, apParameters):
  631. """
  632. Parse gerber aperture definition into dictionary of apertures.
  633. The following kinds and their attributes are supported:
  634. * *Circular (C)*: size (float)
  635. * *Rectangle (R)*: width (float), height (float)
  636. * *Obround (O)*: width (float), height (float).
  637. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  638. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  639. :param apertureId: Id of the aperture being defined.
  640. :param apertureType: Type of the aperture.
  641. :param apParameters: Parameters of the aperture.
  642. :type apertureId: str
  643. :type apertureType: str
  644. :type apParameters: str
  645. :return: Identifier of the aperture.
  646. :rtype: str
  647. """
  648. # Found some Gerber with a leading zero in the aperture id and the
  649. # referenced it without the zero, so this is a hack to handle that.
  650. apid = str(int(apertureId))
  651. try: # Could be empty for aperture macros
  652. paramList = apParameters.split('X')
  653. except:
  654. paramList = None
  655. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  656. self.apertures[apid] = {"type": "C",
  657. "size": float(paramList[0])}
  658. return apid
  659. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  660. self.apertures[apid] = {"type": "R",
  661. "width": float(paramList[0]),
  662. "height": float(paramList[1])}
  663. return apid
  664. if apertureType == "O": # Obround
  665. self.apertures[apid] = {"type": "O",
  666. "width": float(paramList[0]),
  667. "height": float(paramList[1])}
  668. return apid
  669. if apertureType == "P": # Polygon (regular)
  670. self.apertures[apid] = {"type": "P",
  671. "diam": float(paramList[0]),
  672. "nVertices": int(paramList[1])}
  673. if len(paramList) >= 3:
  674. self.apertures[apid]["rotation"] = float(paramList[2])
  675. return apid
  676. if apertureType in self.aperture_macros:
  677. self.apertures[apid] = {"type": "AM",
  678. "macro": self.aperture_macros[apertureType],
  679. "modifiers": paramList}
  680. return apid
  681. log.warning("Aperture not implemented: %s" % str(apertureType))
  682. return None
  683. def parse_file(self, filename):
  684. """
  685. Calls Gerber.parse_lines() with array of lines
  686. read from the given file.
  687. :param filename: Gerber file to parse.
  688. :type filename: str
  689. :return: None
  690. """
  691. gfile = open(filename, 'r')
  692. gstr = gfile.readlines()
  693. gfile.close()
  694. self.parse_lines(gstr)
  695. def parse_lines(self, glines):
  696. """
  697. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  698. ``self.flashes``, ``self.regions`` and ``self.units``.
  699. :param glines: Gerber code as list of strings, each element being
  700. one line of the source file.
  701. :type glines: list
  702. :return: None
  703. :rtype: None
  704. """
  705. # Coordinates of the current path, each is [x, y]
  706. path = []
  707. # Polygons are stored here until there is a change in polarity.
  708. # Only then they are combined via cascaded_union and added or
  709. # subtracted from solid_geometry. This is ~100 times faster than
  710. # applyng a union for every new polygon.
  711. poly_buffer = []
  712. last_path_aperture = None
  713. current_aperture = None
  714. # 1,2 or 3 from "G01", "G02" or "G03"
  715. current_interpolation_mode = None
  716. # 1 or 2 from "D01" or "D02"
  717. # Note this is to support deprecated Gerber not putting
  718. # an operation code at the end of every coordinate line.
  719. current_operation_code = None
  720. # Current coordinates
  721. current_x = None
  722. current_y = None
  723. # Absolute or Relative/Incremental coordinates
  724. # Not implemented
  725. absolute = True
  726. # How to interpret circular interpolation: SINGLE or MULTI
  727. quadrant_mode = None
  728. # Indicates we are parsing an aperture macro
  729. current_macro = None
  730. # Indicates the current polarity: D-Dark, C-Clear
  731. current_polarity = 'D'
  732. # If a region is being defined
  733. making_region = False
  734. #### Parsing starts here ####
  735. line_num = 0
  736. gline = ""
  737. try:
  738. for gline in glines:
  739. line_num += 1
  740. ### Cleanup
  741. gline = gline.strip(' \r\n')
  742. ### Aperture Macros
  743. # Having this at the beggining will slow things down
  744. # but macros can have complicated statements than could
  745. # be caught by other ptterns.
  746. if current_macro is None: # No macro started yet
  747. match = self.am1_re.search(gline)
  748. # Start macro if match, else not an AM, carry on.
  749. if match:
  750. log.info("Starting macro. Line %d: %s" % (line_num, gline))
  751. current_macro = match.group(1)
  752. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  753. if match.group(2): # Append
  754. self.aperture_macros[current_macro].append(match.group(2))
  755. if match.group(3): # Finish macro
  756. #self.aperture_macros[current_macro].parse_content()
  757. current_macro = None
  758. log.info("Macro complete in 1 line.")
  759. continue
  760. else: # Continue macro
  761. log.info("Continuing macro. Line %d." % line_num)
  762. match = self.am2_re.search(gline)
  763. if match: # Finish macro
  764. log.info("End of macro. Line %d." % line_num)
  765. self.aperture_macros[current_macro].append(match.group(1))
  766. #self.aperture_macros[current_macro].parse_content()
  767. current_macro = None
  768. else: # Append
  769. self.aperture_macros[current_macro].append(gline)
  770. continue
  771. ### G01 - Linear interpolation plus flashes
  772. # Operation code (D0x) missing is deprecated... oh well I will support it.
  773. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  774. match = self.lin_re.search(gline)
  775. if match:
  776. # Dxx alone?
  777. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  778. # try:
  779. # current_operation_code = int(match.group(4))
  780. # except:
  781. # pass # A line with just * will match too.
  782. # continue
  783. # NOTE: Letting it continue allows it to react to the
  784. # operation code.
  785. # Parse coordinates
  786. if match.group(2) is not None:
  787. current_x = parse_gerber_number(match.group(2), self.frac_digits)
  788. if match.group(3) is not None:
  789. current_y = parse_gerber_number(match.group(3), self.frac_digits)
  790. # Parse operation code
  791. if match.group(4) is not None:
  792. current_operation_code = int(match.group(4))
  793. # Pen down: add segment
  794. if current_operation_code == 1:
  795. path.append([current_x, current_y])
  796. last_path_aperture = current_aperture
  797. elif current_operation_code == 2:
  798. if len(path) > 1:
  799. ## --- BUFFERED ---
  800. if making_region:
  801. geo = Polygon(path)
  802. else:
  803. if last_path_aperture is None:
  804. log.warning("No aperture defined for curent path. (%d)" % line_num)
  805. width = self.apertures[last_path_aperture]["size"]
  806. geo = LineString(path).buffer(width/2)
  807. poly_buffer.append(geo)
  808. path = [[current_x, current_y]] # Start new path
  809. # Flash
  810. elif current_operation_code == 3:
  811. # --- BUFFERED ---
  812. flash = Gerber.create_flash_geometry(Point([current_x, current_y]),
  813. self.apertures[current_aperture])
  814. poly_buffer.append(flash)
  815. continue
  816. ### G02/3 - Circular interpolation
  817. # 2-clockwise, 3-counterclockwise
  818. match = self.circ_re.search(gline)
  819. if match:
  820. mode, x, y, i, j, d = match.groups()
  821. try:
  822. x = parse_gerber_number(x, self.frac_digits)
  823. except:
  824. x = current_x
  825. try:
  826. y = parse_gerber_number(y, self.frac_digits)
  827. except:
  828. y = current_y
  829. try:
  830. i = parse_gerber_number(i, self.frac_digits)
  831. except:
  832. i = 0
  833. try:
  834. j = parse_gerber_number(j, self.frac_digits)
  835. except:
  836. j = 0
  837. if quadrant_mode is None:
  838. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  839. log.error(gline)
  840. continue
  841. if mode is None and current_interpolation_mode not in [2, 3]:
  842. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  843. log.error(gline)
  844. continue
  845. elif mode is not None:
  846. current_interpolation_mode = int(mode)
  847. # Set operation code if provided
  848. if d is not None:
  849. current_operation_code = int(d)
  850. # Nothing created! Pen Up.
  851. if current_operation_code == 2:
  852. log.warning("Arc with D2. (%d)" % line_num)
  853. if len(path) > 1:
  854. if last_path_aperture is None:
  855. log.warning("No aperture defined for curent path. (%d)" % line_num)
  856. # --- BUFFERED ---
  857. width = self.apertures[last_path_aperture]["size"]
  858. buffered = LineString(path).buffer(width/2)
  859. poly_buffer.append(buffered)
  860. current_x = x
  861. current_y = y
  862. path = [[current_x, current_y]] # Start new path
  863. continue
  864. # Flash should not happen here
  865. if current_operation_code == 3:
  866. log.error("Trying to flash within arc. (%d)" % line_num)
  867. continue
  868. if quadrant_mode == 'MULTI':
  869. center = [i + current_x, j + current_y]
  870. radius = sqrt(i**2 + j**2)
  871. start = arctan2(-j, -i)
  872. stop = arctan2(-center[1] + y, -center[0] + x)
  873. arcdir = [None, None, "cw", "ccw"]
  874. this_arc = arc(center, radius, start, stop,
  875. arcdir[current_interpolation_mode],
  876. self.steps_per_circ)
  877. # Last point in path is current point
  878. current_x = this_arc[-1][0]
  879. current_y = this_arc[-1][1]
  880. # Append
  881. path += this_arc
  882. last_path_aperture = current_aperture
  883. continue
  884. if quadrant_mode == 'SINGLE':
  885. log.warning("Single quadrant arc are not implemented yet. (%d)" % line_num)
  886. ### Operation code alone
  887. match = self.opcode_re.search(gline)
  888. if match:
  889. current_operation_code = int(match.group(1))
  890. if current_operation_code == 3:
  891. ## --- Buffered ---
  892. flash = Gerber.create_flash_geometry(Point(path[-1]),
  893. self.apertures[current_aperture])
  894. poly_buffer.append(flash)
  895. continue
  896. ### G74/75* - Single or multiple quadrant arcs
  897. match = self.quad_re.search(gline)
  898. if match:
  899. if match.group(1) == '4':
  900. quadrant_mode = 'SINGLE'
  901. else:
  902. quadrant_mode = 'MULTI'
  903. continue
  904. ### G36* - Begin region
  905. if self.regionon_re.search(gline):
  906. if len(path) > 1:
  907. # Take care of what is left in the path
  908. ## --- Buffered ---
  909. width = self.apertures[last_path_aperture]["size"]
  910. geo = LineString(path).buffer(width/2)
  911. poly_buffer.append(geo)
  912. path = [path[-1]]
  913. making_region = True
  914. continue
  915. ### G37* - End region
  916. if self.regionoff_re.search(gline):
  917. making_region = False
  918. # Only one path defines region?
  919. # This can happen if D02 happened before G37 and
  920. # is not and error.
  921. if len(path) < 3:
  922. # print "ERROR: Path contains less than 3 points:"
  923. # print path
  924. # print "Line (%d): " % line_num, gline
  925. # path = []
  926. #path = [[current_x, current_y]]
  927. continue
  928. # For regions we may ignore an aperture that is None
  929. # self.regions.append({"polygon": Polygon(path),
  930. # "aperture": last_path_aperture})
  931. # --- Buffered ---
  932. region = Polygon(path)
  933. if not region.is_valid:
  934. region = region.buffer(0)
  935. poly_buffer.append(region)
  936. path = [[current_x, current_y]] # Start new path
  937. continue
  938. ### Aperture definitions %ADD...
  939. match = self.ad_re.search(gline)
  940. if match:
  941. log.info("Found aperture definition. Line %d: %s" % (line_num, gline))
  942. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  943. continue
  944. ### G01/2/3* - Interpolation mode change
  945. # Can occur along with coordinates and operation code but
  946. # sometimes by itself (handled here).
  947. # Example: G01*
  948. match = self.interp_re.search(gline)
  949. if match:
  950. current_interpolation_mode = int(match.group(1))
  951. continue
  952. ### Tool/aperture change
  953. # Example: D12*
  954. match = self.tool_re.search(gline)
  955. if match:
  956. current_aperture = match.group(1)
  957. continue
  958. ### Polarity change
  959. # Example: %LPD*% or %LPC*%
  960. match = self.lpol_re.search(gline)
  961. if match:
  962. if len(path) > 1 and current_polarity != match.group(1):
  963. # --- Buffered ----
  964. width = self.apertures[last_path_aperture]["size"]
  965. geo = LineString(path).buffer(width/2)
  966. poly_buffer.append(geo)
  967. path = [path[-1]]
  968. # --- Apply buffer ---
  969. if current_polarity == 'D':
  970. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  971. else:
  972. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  973. poly_buffer = []
  974. current_polarity = match.group(1)
  975. continue
  976. ### Number format
  977. # Example: %FSLAX24Y24*%
  978. # TODO: This is ignoring most of the format. Implement the rest.
  979. match = self.fmt_re.search(gline)
  980. if match:
  981. absolute = {'A': True, 'I': False}
  982. self.int_digits = int(match.group(3))
  983. self.frac_digits = int(match.group(4))
  984. continue
  985. ### Mode (IN/MM)
  986. # Example: %MOIN*%
  987. match = self.mode_re.search(gline)
  988. if match:
  989. self.units = match.group(1)
  990. continue
  991. ### Units (G70/1) OBSOLETE
  992. match = self.units_re.search(gline)
  993. if match:
  994. self.units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  995. continue
  996. ### Absolute/relative coordinates G90/1 OBSOLETE
  997. match = self.absrel_re.search(gline)
  998. if match:
  999. absolute = {'0': True, '1': False}[match.group(1)]
  1000. continue
  1001. #### Ignored lines
  1002. ## Comments
  1003. match = self.comm_re.search(gline)
  1004. if match:
  1005. continue
  1006. ## EOF
  1007. match = self.eof_re.search(gline)
  1008. if match:
  1009. continue
  1010. ### Line did not match any pattern. Warn user.
  1011. log.warning("Line ignored (%d): %s" % (line_num, gline))
  1012. if len(path) > 1:
  1013. # EOF, create shapely LineString if something still in path
  1014. ## --- Buffered ---
  1015. width = self.apertures[last_path_aperture]["size"]
  1016. geo = LineString(path).buffer(width/2)
  1017. poly_buffer.append(geo)
  1018. # --- Apply buffer ---
  1019. if current_polarity == 'D':
  1020. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1021. else:
  1022. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1023. except Exception, err:
  1024. #print traceback.format_exc()
  1025. log.error("PARSING FAILED. Line %d: %s" % (line_num, gline))
  1026. raise
  1027. @staticmethod
  1028. def create_flash_geometry(location, aperture):
  1029. if type(location) == list:
  1030. location = Point(location)
  1031. if aperture['type'] == 'C': # Circles
  1032. return location.buffer(aperture['size']/2)
  1033. if aperture['type'] == 'R': # Rectangles
  1034. loc = location.coords[0]
  1035. width = aperture['width']
  1036. height = aperture['height']
  1037. minx = loc[0] - width/2
  1038. maxx = loc[0] + width/2
  1039. miny = loc[1] - height/2
  1040. maxy = loc[1] + height/2
  1041. return shply_box(minx, miny, maxx, maxy)
  1042. if aperture['type'] == 'O': # Obround
  1043. loc = location.coords[0]
  1044. width = aperture['width']
  1045. height = aperture['height']
  1046. if width > height:
  1047. p1 = Point(loc[0] + 0.5*(width-height), loc[1])
  1048. p2 = Point(loc[0] - 0.5*(width-height), loc[1])
  1049. c1 = p1.buffer(height*0.5)
  1050. c2 = p2.buffer(height*0.5)
  1051. else:
  1052. p1 = Point(loc[0], loc[1] + 0.5*(height-width))
  1053. p2 = Point(loc[0], loc[1] - 0.5*(height-width))
  1054. c1 = p1.buffer(width*0.5)
  1055. c2 = p2.buffer(width*0.5)
  1056. return cascaded_union([c1, c2]).convex_hull
  1057. if aperture['type'] == 'P': # Regular polygon
  1058. loc = location.coords[0]
  1059. diam = aperture['diam']
  1060. n_vertices = aperture['nVertices']
  1061. points = []
  1062. for i in range(0, n_vertices):
  1063. x = loc[0] + diam * (cos(2 * pi * i / n_vertices))
  1064. y = loc[1] + diam * (sin(2 * pi * i / n_vertices))
  1065. points.append((x, y))
  1066. ply = Polygon(points)
  1067. if 'rotation' in aperture:
  1068. ply = affinity.rotate(ply, aperture['rotation'])
  1069. return ply
  1070. if aperture['type'] == 'AM': # Aperture Macro
  1071. loc = location.coords[0]
  1072. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1073. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1074. return None
  1075. def create_geometry(self):
  1076. """
  1077. Geometry from a Gerber file is made up entirely of polygons.
  1078. Every stroke (linear or circular) has an aperture which gives
  1079. it thickness. Additionally, aperture strokes have non-zero area,
  1080. and regions naturally do as well.
  1081. :rtype : None
  1082. :return: None
  1083. """
  1084. # self.buffer_paths()
  1085. #
  1086. # self.fix_regions()
  1087. #
  1088. # self.do_flashes()
  1089. #
  1090. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1091. # [poly['polygon'] for poly in self.regions] +
  1092. # self.flash_geometry)
  1093. def get_bounding_box(self, margin=0.0, rounded=False):
  1094. """
  1095. Creates and returns a rectangular polygon bounding at a distance of
  1096. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1097. can optionally have rounded corners of radius equal to margin.
  1098. :param margin: Distance to enlarge the rectangular bounding
  1099. box in both positive and negative, x and y axes.
  1100. :type margin: float
  1101. :param rounded: Wether or not to have rounded corners.
  1102. :type rounded: bool
  1103. :return: The bounding box.
  1104. :rtype: Shapely.Polygon
  1105. """
  1106. bbox = self.solid_geometry.envelope.buffer(margin)
  1107. if not rounded:
  1108. bbox = bbox.envelope
  1109. return bbox
  1110. class Excellon(Geometry):
  1111. """
  1112. *ATTRIBUTES*
  1113. * ``tools`` (dict): The key is the tool name and the value is
  1114. a dictionary specifying the tool:
  1115. ================ ====================================
  1116. Key Value
  1117. ================ ====================================
  1118. C Diameter of the tool
  1119. Others Not supported (Ignored).
  1120. ================ ====================================
  1121. * ``drills`` (list): Each is a dictionary:
  1122. ================ ====================================
  1123. Key Value
  1124. ================ ====================================
  1125. point (Shapely.Point) Where to drill
  1126. tool (str) A key in ``tools``
  1127. ================ ====================================
  1128. """
  1129. def __init__(self):
  1130. """
  1131. The constructor takes no parameters.
  1132. :return: Excellon object.
  1133. :rtype: Excellon
  1134. """
  1135. Geometry.__init__(self)
  1136. self.tools = {}
  1137. self.drills = []
  1138. # Trailing "T" or leading "L" (default)
  1139. self.zeros = "L"
  1140. # Attributes to be included in serialization
  1141. # Always append to it because it carries contents
  1142. # from Geometry.
  1143. self.ser_attrs += ['tools', 'drills', 'zeros']
  1144. #### Patterns ####
  1145. # Regex basics:
  1146. # ^ - beginning
  1147. # $ - end
  1148. # *: 0 or more, +: 1 or more, ?: 0 or 1
  1149. # M48 - Beggining of Part Program Header
  1150. self.hbegin_re = re.compile(r'^M48$')
  1151. # M95 or % - End of Part Program Header
  1152. # NOTE: % has different meaning in the body
  1153. self.hend_re = re.compile(r'^(?:M95|%)$')
  1154. # FMAT Excellon format
  1155. self.fmat_re = re.compile(r'^FMAT,([12])$')
  1156. # Number format and units
  1157. # INCH uses 6 digits
  1158. # METRIC uses 5/6
  1159. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  1160. # Tool definition/parameters (?= is look-ahead
  1161. # NOTE: This might be an overkill!
  1162. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  1163. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1164. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1165. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1166. self.toolset_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))?' +
  1167. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1168. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1169. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1170. # Tool select
  1171. # Can have additional data after tool number but
  1172. # is ignored if present in the header.
  1173. # Warning: This will match toolset_re too.
  1174. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  1175. self.toolsel_re = re.compile(r'^T(\d+)')
  1176. # Comment
  1177. self.comm_re = re.compile(r'^;(.*)$')
  1178. # Absolute/Incremental G90/G91
  1179. self.absinc_re = re.compile(r'^G9([01])$')
  1180. # Modes of operation
  1181. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  1182. self.modes_re = re.compile(r'^G0([012345])')
  1183. # Measuring mode
  1184. # 1-metric, 2-inch
  1185. self.meas_re = re.compile(r'^M7([12])$')
  1186. # Coordinates
  1187. #self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  1188. #self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  1189. self.coordsperiod_re = re.compile(r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]')
  1190. self.coordsnoperiod_re = re.compile(r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]')
  1191. # R - Repeat hole (# times, X offset, Y offset)
  1192. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  1193. # Various stop/pause commands
  1194. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  1195. # Parse coordinates
  1196. self.leadingzeros_re = re.compile(r'^(0*)(\d*)')
  1197. def parse_file(self, filename):
  1198. """
  1199. Reads the specified file as array of lines as
  1200. passes it to ``parse_lines()``.
  1201. :param filename: The file to be read and parsed.
  1202. :type filename: str
  1203. :return: None
  1204. """
  1205. efile = open(filename, 'r')
  1206. estr = efile.readlines()
  1207. efile.close()
  1208. self.parse_lines(estr)
  1209. def parse_lines(self, elines):
  1210. """
  1211. Main Excellon parser.
  1212. :param elines: List of strings, each being a line of Excellon code.
  1213. :type elines: list
  1214. :return: None
  1215. """
  1216. # State variables
  1217. current_tool = ""
  1218. in_header = False
  1219. current_x = None
  1220. current_y = None
  1221. line_num = 0 # Line number
  1222. for eline in elines:
  1223. line_num += 1
  1224. ### Cleanup lines
  1225. eline = eline.strip(' \r\n')
  1226. ## Header Begin/End ##
  1227. if self.hbegin_re.search(eline):
  1228. in_header = True
  1229. continue
  1230. if self.hend_re.search(eline):
  1231. in_header = False
  1232. continue
  1233. #### Body ####
  1234. if not in_header:
  1235. ## Tool change ##
  1236. match = self.toolsel_re.search(eline)
  1237. if match:
  1238. current_tool = str(int(match.group(1)))
  1239. continue
  1240. ## Coordinates without period ##
  1241. match = self.coordsnoperiod_re.search(eline)
  1242. if match:
  1243. try:
  1244. #x = float(match.group(1))/10000
  1245. x = self.parse_number(match.group(1))
  1246. current_x = x
  1247. except TypeError:
  1248. x = current_x
  1249. try:
  1250. #y = float(match.group(2))/10000
  1251. y = self.parse_number(match.group(2))
  1252. current_y = y
  1253. except TypeError:
  1254. y = current_y
  1255. if x is None or y is None:
  1256. log.error("Missing coordinates")
  1257. continue
  1258. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1259. continue
  1260. ## Coordinates with period: Use literally. ##
  1261. match = self.coordsperiod_re.search(eline)
  1262. if match:
  1263. try:
  1264. x = float(match.group(1))
  1265. current_x = x
  1266. except TypeError:
  1267. x = current_x
  1268. try:
  1269. y = float(match.group(2))
  1270. current_y = y
  1271. except TypeError:
  1272. y = current_y
  1273. if x is None or y is None:
  1274. log.error("Missing coordinates")
  1275. continue
  1276. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1277. continue
  1278. #### Header ####
  1279. if in_header:
  1280. ## Tool definitions ##
  1281. match = self.toolset_re.search(eline)
  1282. if match:
  1283. name = str(int(match.group(1)))
  1284. spec = {
  1285. "C": float(match.group(2)),
  1286. # "F": float(match.group(3)),
  1287. # "S": float(match.group(4)),
  1288. # "B": float(match.group(5)),
  1289. # "H": float(match.group(6)),
  1290. # "Z": float(match.group(7))
  1291. }
  1292. self.tools[name] = spec
  1293. continue
  1294. ## Units and number format ##
  1295. match = self.units_re.match(eline)
  1296. if match:
  1297. self.zeros = match.group(2) # "T" or "L"
  1298. self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  1299. continue
  1300. log.warning("Line ignored: %s" % eline)
  1301. def parse_number(self, number_str):
  1302. """
  1303. Parses coordinate numbers without period.
  1304. :param number_str: String representing the numerical value.
  1305. :type number_str: str
  1306. :return: Floating point representation of the number
  1307. :rtype: foat
  1308. """
  1309. if self.zeros == "L":
  1310. match = self.leadingzeros_re.search(number_str)
  1311. return float(number_str)/(10**(len(match.group(2))-2+len(match.group(1))))
  1312. else: # Trailing
  1313. return float(number_str)/10000
  1314. def create_geometry(self):
  1315. """
  1316. Creates circles of the tool diameter at every point
  1317. specified in ``self.drills``.
  1318. :return: None
  1319. """
  1320. self.solid_geometry = []
  1321. for drill in self.drills:
  1322. #poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  1323. tooldia = self.tools[drill['tool']]['C']
  1324. poly = drill['point'].buffer(tooldia/2.0)
  1325. self.solid_geometry.append(poly)
  1326. def scale(self, factor):
  1327. """
  1328. Scales geometry on the XY plane in the object by a given factor.
  1329. Tool sizes, feedrates an Z-plane dimensions are untouched.
  1330. :param factor: Number by which to scale the object.
  1331. :type factor: float
  1332. :return: None
  1333. :rtype: NOne
  1334. """
  1335. # Drills
  1336. for drill in self.drills:
  1337. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  1338. self.create_geometry()
  1339. def offset(self, vect):
  1340. """
  1341. Offsets geometry on the XY plane in the object by a given vector.
  1342. :param vect: (x, y) offset vector.
  1343. :type vect: tuple
  1344. :return: None
  1345. """
  1346. dx, dy = vect
  1347. # Drills
  1348. for drill in self.drills:
  1349. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  1350. # Recreate geometry
  1351. self.create_geometry()
  1352. def mirror(self, axis, point):
  1353. """
  1354. :param axis: "X" or "Y" indicates around which axis to mirror.
  1355. :type axis: str
  1356. :param point: [x, y] point belonging to the mirror axis.
  1357. :type point: list
  1358. :return: None
  1359. """
  1360. px, py = point
  1361. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1362. # Modify data
  1363. for drill in self.drills:
  1364. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  1365. # Recreate geometry
  1366. self.create_geometry()
  1367. def convert_units(self, units):
  1368. factor = Geometry.convert_units(self, units)
  1369. # Tools
  1370. for tname in self.tools:
  1371. self.tools[tname]["C"] *= factor
  1372. self.create_geometry()
  1373. return factor
  1374. class CNCjob(Geometry):
  1375. """
  1376. Represents work to be done by a CNC machine.
  1377. *ATTRIBUTES*
  1378. * ``gcode_parsed`` (list): Each is a dictionary:
  1379. ===================== =========================================
  1380. Key Value
  1381. ===================== =========================================
  1382. geom (Shapely.LineString) Tool path (XY plane)
  1383. kind (string) "AB", A is "T" (travel) or
  1384. "C" (cut). B is "F" (fast) or "S" (slow).
  1385. ===================== =========================================
  1386. """
  1387. def __init__(self, units="in", kind="generic", z_move=0.1,
  1388. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  1389. Geometry.__init__(self)
  1390. self.kind = kind
  1391. self.units = units
  1392. self.z_cut = z_cut
  1393. self.z_move = z_move
  1394. self.feedrate = feedrate
  1395. self.tooldia = tooldia
  1396. self.unitcode = {"IN": "G20", "MM": "G21"}
  1397. self.pausecode = "G04 P1"
  1398. self.feedminutecode = "G94"
  1399. self.absolutecode = "G90"
  1400. self.gcode = ""
  1401. self.input_geometry_bounds = None
  1402. self.gcode_parsed = None
  1403. self.steps_per_circ = 20 # Used when parsing G-code arcs
  1404. # Attributes to be included in serialization
  1405. # Always append to it because it carries contents
  1406. # from Geometry.
  1407. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  1408. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  1409. 'steps_per_circ']
  1410. def convert_units(self, units):
  1411. factor = Geometry.convert_units(self, units)
  1412. log.debug("CNCjob.convert_units()")
  1413. self.z_cut *= factor
  1414. self.z_move *= factor
  1415. self.feedrate *= factor
  1416. self.tooldia *= factor
  1417. return factor
  1418. def generate_from_excellon(self, exobj):
  1419. """
  1420. Generates G-code for drilling from Excellon object.
  1421. self.gcode becomes a list, each element is a
  1422. different job for each tool in the excellon code.
  1423. """
  1424. self.kind = "drill"
  1425. self.gcode = []
  1426. t = "G00 X%.4fY%.4f\n"
  1427. down = "G01 Z%.4f\n" % self.z_cut
  1428. up = "G01 Z%.4f\n" % self.z_move
  1429. for tool in exobj.tools:
  1430. points = []
  1431. for drill in exobj.drill:
  1432. if drill['tool'] == tool:
  1433. points.append(drill['point'])
  1434. gcode = self.unitcode[self.units.upper()] + "\n"
  1435. gcode += self.absolutecode + "\n"
  1436. gcode += self.feedminutecode + "\n"
  1437. gcode += "F%.2f\n" % self.feedrate
  1438. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1439. gcode += "M03\n" # Spindle start
  1440. gcode += self.pausecode + "\n"
  1441. for point in points:
  1442. gcode += t % point
  1443. gcode += down + up
  1444. gcode += t % (0, 0)
  1445. gcode += "M05\n" # Spindle stop
  1446. self.gcode.append(gcode)
  1447. def generate_from_excellon_by_tool(self, exobj, tools="all"):
  1448. """
  1449. Creates gcode for this object from an Excellon object
  1450. for the specified tools.
  1451. :param exobj: Excellon object to process
  1452. :type exobj: Excellon
  1453. :param tools: Comma separated tool names
  1454. :type: tools: str
  1455. :return: None
  1456. :rtype: None
  1457. """
  1458. log.debug("Creating CNC Job from Excellon...")
  1459. if tools == "all":
  1460. tools = [tool for tool in exobj.tools]
  1461. else:
  1462. tools = [x.strip() for x in tools.split(",")]
  1463. tools = filter(lambda i: i in exobj.tools, tools)
  1464. log.debug("Tools are: %s" % str(tools))
  1465. points = []
  1466. for drill in exobj.drills:
  1467. if drill['tool'] in tools:
  1468. points.append(drill['point'])
  1469. log.debug("Found %d drills." % len(points))
  1470. #self.kind = "drill"
  1471. self.gcode = []
  1472. t = "G00 X%.4fY%.4f\n"
  1473. down = "G01 Z%.4f\n" % self.z_cut
  1474. up = "G01 Z%.4f\n" % self.z_move
  1475. gcode = self.unitcode[self.units.upper()] + "\n"
  1476. gcode += self.absolutecode + "\n"
  1477. gcode += self.feedminutecode + "\n"
  1478. gcode += "F%.2f\n" % self.feedrate
  1479. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1480. gcode += "M03\n" # Spindle start
  1481. gcode += self.pausecode + "\n"
  1482. for point in points:
  1483. x, y = point.coords.xy
  1484. gcode += t % (x[0], y[0])
  1485. gcode += down + up
  1486. gcode += t % (0, 0)
  1487. gcode += "M05\n" # Spindle stop
  1488. self.gcode = gcode
  1489. def generate_from_geometry(self, geometry, append=True, tooldia=None, tolerance=0):
  1490. """
  1491. Generates G-Code from a Geometry object. Stores in ``self.gcode``.
  1492. :param geometry: Geometry defining the toolpath
  1493. :type geometry: Geometry
  1494. :param append: Wether to append to self.gcode or re-write it.
  1495. :type append: bool
  1496. :param tooldia: If given, sets the tooldia property but does
  1497. not affect the process in any other way.
  1498. :type tooldia: bool
  1499. :param tolerance: All points in the simplified object will be within the
  1500. tolerance distance of the original geometry.
  1501. :return: None
  1502. :rtype: None
  1503. """
  1504. if tooldia is not None:
  1505. self.tooldia = tooldia
  1506. self.input_geometry_bounds = geometry.bounds()
  1507. if not append:
  1508. self.gcode = ""
  1509. self.gcode = self.unitcode[self.units.upper()] + "\n"
  1510. self.gcode += self.absolutecode + "\n"
  1511. self.gcode += self.feedminutecode + "\n"
  1512. self.gcode += "F%.2f\n" % self.feedrate
  1513. self.gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1514. self.gcode += "M03\n" # Spindle start
  1515. self.gcode += self.pausecode + "\n"
  1516. for geo in geometry.solid_geometry:
  1517. if type(geo) == Polygon:
  1518. self.gcode += self.polygon2gcode(geo, tolerance=tolerance)
  1519. continue
  1520. if type(geo) == LineString or type(geo) == LinearRing:
  1521. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  1522. continue
  1523. if type(geo) == Point:
  1524. self.gcode += self.point2gcode(geo)
  1525. continue
  1526. if type(geo) == MultiPolygon:
  1527. for poly in geo:
  1528. self.gcode += self.polygon2gcode(poly, tolerance=tolerance)
  1529. continue
  1530. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  1531. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1532. self.gcode += "G00 X0Y0\n"
  1533. self.gcode += "M05\n" # Spindle stop
  1534. def pre_parse(self, gtext):
  1535. """
  1536. Separates parts of the G-Code text into a list of dictionaries.
  1537. Used by ``self.gcode_parse()``.
  1538. :param gtext: A single string with g-code
  1539. """
  1540. # Units: G20-inches, G21-mm
  1541. units_re = re.compile(r'^G2([01])')
  1542. # TODO: This has to be re-done
  1543. gcmds = []
  1544. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  1545. for line in lines:
  1546. # Clean up
  1547. line = line.strip()
  1548. # Remove comments
  1549. # NOTE: Limited to 1 bracket pair
  1550. op = line.find("(")
  1551. cl = line.find(")")
  1552. #if op > -1 and cl > op:
  1553. if cl > op > -1:
  1554. #comment = line[op+1:cl]
  1555. line = line[:op] + line[(cl+1):]
  1556. # Units
  1557. match = units_re.match(line)
  1558. if match:
  1559. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  1560. # Parse GCode
  1561. # 0 4 12
  1562. # G01 X-0.007 Y-0.057
  1563. # --> codes_idx = [0, 4, 12]
  1564. codes = "NMGXYZIJFP"
  1565. codes_idx = []
  1566. i = 0
  1567. for ch in line:
  1568. if ch in codes:
  1569. codes_idx.append(i)
  1570. i += 1
  1571. n_codes = len(codes_idx)
  1572. if n_codes == 0:
  1573. continue
  1574. # Separate codes in line
  1575. parts = []
  1576. for p in range(n_codes-1):
  1577. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  1578. parts.append(line[codes_idx[-1]:].strip())
  1579. # Separate codes from values
  1580. cmds = {}
  1581. for part in parts:
  1582. cmds[part[0]] = float(part[1:])
  1583. gcmds.append(cmds)
  1584. return gcmds
  1585. def gcode_parse(self):
  1586. """
  1587. G-Code parser (from self.gcode). Generates dictionary with
  1588. single-segment LineString's and "kind" indicating cut or travel,
  1589. fast or feedrate speed.
  1590. """
  1591. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1592. # Results go here
  1593. geometry = []
  1594. # TODO: Merge into single parser?
  1595. gobjs = self.pre_parse(self.gcode)
  1596. # Last known instruction
  1597. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  1598. # Current path: temporary storage until tool is
  1599. # lifted or lowered.
  1600. path = [(0, 0)]
  1601. # Process every instruction
  1602. for gobj in gobjs:
  1603. ## Changing height
  1604. if 'Z' in gobj:
  1605. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  1606. log.warning("Non-orthogonal motion: From %s" % str(current))
  1607. log.warning(" To: %s" % str(gobj))
  1608. current['Z'] = gobj['Z']
  1609. # Store the path into geometry and reset path
  1610. if len(path) > 1:
  1611. geometry.append({"geom": LineString(path),
  1612. "kind": kind})
  1613. path = [path[-1]] # Start with the last point of last path.
  1614. if 'G' in gobj:
  1615. current['G'] = int(gobj['G'])
  1616. if 'X' in gobj or 'Y' in gobj:
  1617. if 'X' in gobj:
  1618. x = gobj['X']
  1619. else:
  1620. x = current['X']
  1621. if 'Y' in gobj:
  1622. y = gobj['Y']
  1623. else:
  1624. y = current['Y']
  1625. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1626. if current['Z'] > 0:
  1627. kind[0] = 'T'
  1628. if current['G'] > 0:
  1629. kind[1] = 'S'
  1630. arcdir = [None, None, "cw", "ccw"]
  1631. if current['G'] in [0, 1]: # line
  1632. path.append((x, y))
  1633. if current['G'] in [2, 3]: # arc
  1634. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  1635. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  1636. start = arctan2(-gobj['J'], -gobj['I'])
  1637. stop = arctan2(-center[1]+y, -center[0]+x)
  1638. path += arc(center, radius, start, stop,
  1639. arcdir[current['G']],
  1640. self.steps_per_circ)
  1641. # Update current instruction
  1642. for code in gobj:
  1643. current[code] = gobj[code]
  1644. # There might not be a change in height at the
  1645. # end, therefore, see here too if there is
  1646. # a final path.
  1647. if len(path) > 1:
  1648. geometry.append({"geom": LineString(path),
  1649. "kind": kind})
  1650. self.gcode_parsed = geometry
  1651. return geometry
  1652. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  1653. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1654. # alpha={"T": 0.3, "C": 1.0}):
  1655. # """
  1656. # Creates a Matplotlib figure with a plot of the
  1657. # G-code job.
  1658. # """
  1659. # if tooldia is None:
  1660. # tooldia = self.tooldia
  1661. #
  1662. # fig = Figure(dpi=dpi)
  1663. # ax = fig.add_subplot(111)
  1664. # ax.set_aspect(1)
  1665. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  1666. # ax.set_xlim(xmin-margin, xmax+margin)
  1667. # ax.set_ylim(ymin-margin, ymax+margin)
  1668. #
  1669. # if tooldia == 0:
  1670. # for geo in self.gcode_parsed:
  1671. # linespec = '--'
  1672. # linecolor = color[geo['kind'][0]][1]
  1673. # if geo['kind'][0] == 'C':
  1674. # linespec = 'k-'
  1675. # x, y = geo['geom'].coords.xy
  1676. # ax.plot(x, y, linespec, color=linecolor)
  1677. # else:
  1678. # for geo in self.gcode_parsed:
  1679. # poly = geo['geom'].buffer(tooldia/2.0)
  1680. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1681. # edgecolor=color[geo['kind'][0]][1],
  1682. # alpha=alpha[geo['kind'][0]], zorder=2)
  1683. # ax.add_patch(patch)
  1684. #
  1685. # return fig
  1686. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  1687. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1688. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005):
  1689. """
  1690. Plots the G-code job onto the given axes.
  1691. :param axes: Matplotlib axes on which to plot.
  1692. :param tooldia: Tool diameter.
  1693. :param dpi: Not used!
  1694. :param margin: Not used!
  1695. :param color: Color specification.
  1696. :param alpha: Transparency specification.
  1697. :param tool_tolerance: Tolerance when drawing the toolshape.
  1698. :return: None
  1699. """
  1700. if tooldia is None:
  1701. tooldia = self.tooldia
  1702. if tooldia == 0:
  1703. for geo in self.gcode_parsed:
  1704. linespec = '--'
  1705. linecolor = color[geo['kind'][0]][1]
  1706. if geo['kind'][0] == 'C':
  1707. linespec = 'k-'
  1708. x, y = geo['geom'].coords.xy
  1709. axes.plot(x, y, linespec, color=linecolor)
  1710. else:
  1711. for geo in self.gcode_parsed:
  1712. poly = geo['geom'].buffer(tooldia/2.0).simplify(tool_tolerance)
  1713. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1714. edgecolor=color[geo['kind'][0]][1],
  1715. alpha=alpha[geo['kind'][0]], zorder=2)
  1716. axes.add_patch(patch)
  1717. def create_geometry(self):
  1718. # TODO: This takes forever. Too much data?
  1719. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  1720. def polygon2gcode(self, polygon, tolerance=0):
  1721. """
  1722. Creates G-Code for the exterior and all interior paths
  1723. of a polygon.
  1724. :param polygon: A Shapely.Polygon
  1725. :type polygon: Shapely.Polygon
  1726. :param tolerance: All points in the simplified object will be within the
  1727. tolerance distance of the original geometry.
  1728. :type tolerance: float
  1729. :return: G-code to cut along polygon.
  1730. :rtype: str
  1731. """
  1732. if tolerance > 0:
  1733. target_polygon = polygon.simplify(tolerance)
  1734. else:
  1735. target_polygon = polygon
  1736. gcode = ""
  1737. t = "G0%d X%.4fY%.4f\n"
  1738. path = list(target_polygon.exterior.coords) # Polygon exterior
  1739. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1740. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1741. for pt in path[1:]:
  1742. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1743. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1744. for ints in target_polygon.interiors: # Polygon interiors
  1745. path = list(ints.coords)
  1746. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1747. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1748. for pt in path[1:]:
  1749. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1750. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1751. return gcode
  1752. def linear2gcode(self, linear, tolerance=0):
  1753. """
  1754. Generates G-code to cut along the linear feature.
  1755. :param linear: The path to cut along.
  1756. :type: Shapely.LinearRing or Shapely.Linear String
  1757. :param tolerance: All points in the simplified object will be within the
  1758. tolerance distance of the original geometry.
  1759. :type tolerance: float
  1760. :return: G-code to cut alon the linear feature.
  1761. :rtype: str
  1762. """
  1763. if tolerance > 0:
  1764. target_linear = linear.simplify(tolerance)
  1765. else:
  1766. target_linear = linear
  1767. gcode = ""
  1768. t = "G0%d X%.4fY%.4f\n"
  1769. path = list(target_linear.coords)
  1770. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1771. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1772. for pt in path[1:]:
  1773. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1774. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1775. return gcode
  1776. def point2gcode(self, point):
  1777. # TODO: This is not doing anything.
  1778. gcode = ""
  1779. t = "G0%d X%.4fY%.4f\n"
  1780. path = list(point.coords)
  1781. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1782. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1783. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1784. def scale(self, factor):
  1785. """
  1786. Scales all the geometry on the XY plane in the object by the
  1787. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  1788. not altered.
  1789. :param factor: Number by which to scale the object.
  1790. :type factor: float
  1791. :return: None
  1792. :rtype: None
  1793. """
  1794. for g in self.gcode_parsed:
  1795. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1796. self.create_geometry()
  1797. def offset(self, vect):
  1798. """
  1799. Offsets all the geometry on the XY plane in the object by the
  1800. given vector.
  1801. :param vect: (x, y) offset vector.
  1802. :type vect: tuple
  1803. :return: None
  1804. """
  1805. dx, dy = vect
  1806. for g in self.gcode_parsed:
  1807. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  1808. self.create_geometry()
  1809. # def get_bounds(geometry_set):
  1810. # xmin = Inf
  1811. # ymin = Inf
  1812. # xmax = -Inf
  1813. # ymax = -Inf
  1814. #
  1815. # #print "Getting bounds of:", str(geometry_set)
  1816. # for gs in geometry_set:
  1817. # try:
  1818. # gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  1819. # xmin = min([xmin, gxmin])
  1820. # ymin = min([ymin, gymin])
  1821. # xmax = max([xmax, gxmax])
  1822. # ymax = max([ymax, gymax])
  1823. # except:
  1824. # print "DEV WARNING: Tried to get bounds of empty geometry."
  1825. #
  1826. # return [xmin, ymin, xmax, ymax]
  1827. def get_bounds(geometry_list):
  1828. xmin = Inf
  1829. ymin = Inf
  1830. xmax = -Inf
  1831. ymax = -Inf
  1832. #print "Getting bounds of:", str(geometry_set)
  1833. for gs in geometry_list:
  1834. try:
  1835. gxmin, gymin, gxmax, gymax = gs.bounds()
  1836. xmin = min([xmin, gxmin])
  1837. ymin = min([ymin, gymin])
  1838. xmax = max([xmax, gxmax])
  1839. ymax = max([ymax, gymax])
  1840. except:
  1841. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  1842. return [xmin, ymin, xmax, ymax]
  1843. def arc(center, radius, start, stop, direction, steps_per_circ):
  1844. """
  1845. Creates a list of point along the specified arc.
  1846. :param center: Coordinates of the center [x, y]
  1847. :type center: list
  1848. :param radius: Radius of the arc.
  1849. :type radius: float
  1850. :param start: Starting angle in radians
  1851. :type start: float
  1852. :param stop: End angle in radians
  1853. :type stop: float
  1854. :param direction: Orientation of the arc, "CW" or "CCW"
  1855. :type direction: string
  1856. :param steps_per_circ: Number of straight line segments to
  1857. represent a circle.
  1858. :type steps_per_circ: int
  1859. :return: The desired arc, as list of tuples
  1860. :rtype: list
  1861. """
  1862. # TODO: Resolution should be established by fraction of total length, not angle.
  1863. da_sign = {"cw": -1.0, "ccw": 1.0}
  1864. points = []
  1865. if direction == "ccw" and stop <= start:
  1866. stop += 2*pi
  1867. if direction == "cw" and stop >= start:
  1868. stop -= 2*pi
  1869. angle = abs(stop - start)
  1870. #angle = stop-start
  1871. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  1872. delta_angle = da_sign[direction]*angle*1.0/steps
  1873. for i in range(steps+1):
  1874. theta = start + delta_angle*i
  1875. points.append((center[0]+radius*cos(theta), center[1]+radius*sin(theta)))
  1876. return points
  1877. def clear_poly(poly, tooldia, overlap=0.1):
  1878. """
  1879. Creates a list of Shapely geometry objects covering the inside
  1880. of a Shapely.Polygon. Use for removing all the copper in a region
  1881. or bed flattening.
  1882. :param poly: Target polygon
  1883. :type poly: Shapely.Polygon
  1884. :param tooldia: Diameter of the tool
  1885. :type tooldia: float
  1886. :param overlap: Fraction of the tool diameter to overlap
  1887. in each pass.
  1888. :type overlap: float
  1889. :return: list of Shapely.Polygon
  1890. :rtype: list
  1891. """
  1892. poly_cuts = [poly.buffer(-tooldia/2.0)]
  1893. while True:
  1894. poly = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  1895. if poly.area > 0:
  1896. poly_cuts.append(poly)
  1897. else:
  1898. break
  1899. return poly_cuts
  1900. def find_polygon(poly_set, point):
  1901. """
  1902. Return the first polygon in the list of polygons poly_set
  1903. that contains the given point.
  1904. """
  1905. p = Point(point)
  1906. for poly in poly_set:
  1907. if poly.contains(p):
  1908. return poly
  1909. return None
  1910. def to_dict(obj):
  1911. """
  1912. Makes a Shapely geometry object into serializeable form.
  1913. :param obj: Shapely geometry.
  1914. :type obj: BaseGeometry
  1915. :return: Dictionary with serializable form if ``obj`` was
  1916. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  1917. """
  1918. if isinstance(obj, ApertureMacro):
  1919. return {
  1920. "__class__": "ApertureMacro",
  1921. "__inst__": obj.to_dict()
  1922. }
  1923. if isinstance(obj, BaseGeometry):
  1924. return {
  1925. "__class__": "Shply",
  1926. "__inst__": sdumps(obj)
  1927. }
  1928. return obj
  1929. def dict2obj(d):
  1930. """
  1931. Default deserializer.
  1932. :param d: Serializable dictionary representation of an object
  1933. to be reconstructed.
  1934. :return: Reconstructed object.
  1935. """
  1936. if '__class__' in d and '__inst__' in d:
  1937. if d['__class__'] == "Shply":
  1938. return sloads(d['__inst__'])
  1939. if d['__class__'] == "ApertureMacro":
  1940. am = ApertureMacro()
  1941. am.from_dict(d['__inst__'])
  1942. return am
  1943. return d
  1944. else:
  1945. return d
  1946. def plotg(geo):
  1947. try:
  1948. _ = iter(geo)
  1949. except:
  1950. geo = [geo]
  1951. for g in geo:
  1952. if type(g) == Polygon:
  1953. x, y = g.exterior.coords.xy
  1954. plot(x, y)
  1955. for ints in g.interiors:
  1956. x, y = ints.coords.xy
  1957. plot(x, y)
  1958. continue
  1959. if type(g) == LineString or type(g) == LinearRing:
  1960. x, y = g.coords.xy
  1961. plot(x, y)
  1962. continue
  1963. if type(g) == Point:
  1964. x, y = g.coords.xy
  1965. plot(x, y, 'o')
  1966. continue
  1967. try:
  1968. _ = iter(g)
  1969. plotg(g)
  1970. except:
  1971. log.error("Cannot plot: " + str(type(g)))
  1972. continue
  1973. def parse_gerber_number(strnumber, frac_digits):
  1974. """
  1975. Parse a single number of Gerber coordinates.
  1976. :param strnumber: String containing a number in decimal digits
  1977. from a coordinate data block, possibly with a leading sign.
  1978. :type strnumber: str
  1979. :param frac_digits: Number of digits used for the fractional
  1980. part of the number
  1981. :type frac_digits: int
  1982. :return: The number in floating point.
  1983. :rtype: float
  1984. """
  1985. return int(strnumber)*(10**(-frac_digits))