camlib.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866
  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. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos
  9. from matplotlib.figure import Figure
  10. import re
  11. # See: http://toblerity.org/shapely/manual.html
  12. from shapely.geometry import Polygon, LineString, Point, LinearRing
  13. from shapely.geometry import MultiPoint, MultiPolygon
  14. from shapely.geometry import box as shply_box
  15. from shapely.ops import cascaded_union
  16. import shapely.affinity as affinity
  17. from shapely.wkt import loads as sloads
  18. from shapely.wkt import dumps as sdumps
  19. from shapely.geometry.base import BaseGeometry
  20. # Used for solid polygons in Matplotlib
  21. from descartes.patch import PolygonPatch
  22. import simplejson as json
  23. # TODO: Commented for FlatCAM packaging with cx_freeze
  24. #from matplotlib.pyplot import plot
  25. class Geometry:
  26. def __init__(self):
  27. # Units (in or mm)
  28. self.units = 'in'
  29. # Final geometry: MultiPolygon
  30. self.solid_geometry = None
  31. # Attributes to be included in serialization
  32. self.ser_attrs = ['units', 'solid_geometry']
  33. def isolation_geometry(self, offset):
  34. """
  35. Creates contours around geometry at a given
  36. offset distance.
  37. :param offset: Offset distance.
  38. :type offset: float
  39. :return: The buffered geometry.
  40. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  41. """
  42. return self.solid_geometry.buffer(offset)
  43. def bounds(self):
  44. """
  45. Returns coordinates of rectangular bounds
  46. of geometry: (xmin, ymin, xmax, ymax).
  47. """
  48. if self.solid_geometry is None:
  49. print "Warning: solid_geometry not computed yet."
  50. return (0, 0, 0, 0)
  51. if type(self.solid_geometry) == list:
  52. # TODO: This can be done faster. See comment from Shapely mailing lists.
  53. return cascaded_union(self.solid_geometry).bounds
  54. else:
  55. return self.solid_geometry.bounds
  56. def size(self):
  57. """
  58. Returns (width, height) of rectangular
  59. bounds of geometry.
  60. """
  61. if self.solid_geometry is None:
  62. print "Warning: solid_geometry not computed yet."
  63. return 0
  64. bounds = self.bounds()
  65. return (bounds[2]-bounds[0], bounds[3]-bounds[1])
  66. def get_empty_area(self, boundary=None):
  67. """
  68. Returns the complement of self.solid_geometry within
  69. the given boundary polygon. If not specified, it defaults to
  70. the rectangular bounding box of self.solid_geometry.
  71. """
  72. if boundary is None:
  73. boundary = self.solid_geometry.envelope
  74. return boundary.difference(self.solid_geometry)
  75. def clear_polygon(self, polygon, tooldia, overlap=0.15):
  76. """
  77. Creates geometry inside a polygon for a tool to cover
  78. the whole area.
  79. """
  80. poly_cuts = [polygon.buffer(-tooldia/2.0)]
  81. while True:
  82. polygon = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  83. if polygon.area > 0:
  84. poly_cuts.append(polygon)
  85. else:
  86. break
  87. return poly_cuts
  88. def scale(self, factor):
  89. """
  90. Scales all of the object's geometry by a given factor. Override
  91. this method.
  92. :param factor: Number by which to scale.
  93. :type factor: float
  94. :return: None
  95. :rtype: None
  96. """
  97. return
  98. def offset(self, vect):
  99. """
  100. Offset the geometry by the given vector. Override this method.
  101. :param vect: (x, y) vector by which to offset the object.
  102. :type vect: tuple
  103. :return: None
  104. """
  105. return
  106. def convert_units(self, units):
  107. """
  108. Converts the units of the object to ``units`` by scaling all
  109. the geometry appropriately. This call ``scale()``. Don't call
  110. it again in descendents.
  111. :param units: "IN" or "MM"
  112. :type units: str
  113. :return: Scaling factor resulting from unit change.
  114. :rtype: float
  115. """
  116. print "Geometry.convert_units()"
  117. if units.upper() == self.units.upper():
  118. return 1.0
  119. if units.upper() == "MM":
  120. factor = 25.4
  121. elif units.upper() == "IN":
  122. factor = 1/25.4
  123. else:
  124. print "Unsupported units:", units
  125. return 1.0
  126. self.units = units
  127. self.scale(factor)
  128. return factor
  129. def to_dict(self):
  130. """
  131. Returns a respresentation of the object as a dictionary.
  132. Attributes to include are listed in ``self.ser_attrs``.
  133. :return: A dictionary-encoded copy of the object.
  134. :rtype: dict
  135. """
  136. d = {}
  137. for attr in self.ser_attrs:
  138. d[attr] = getattr(self, attr)
  139. return d
  140. def from_dict(self, d):
  141. """
  142. Sets object's attributes from a dictionary.
  143. Attributes to include are listed in ``self.ser_attrs``.
  144. This method will look only for only and all the
  145. attributes in ``self.ser_attrs``. They must all
  146. be present. Use only for deserializing saved
  147. objects.
  148. :param d: Dictionary of attributes to set in the object.
  149. :type d: dict
  150. :return: None
  151. """
  152. for attr in self.ser_attrs:
  153. setattr(self, attr, d[attr])
  154. class Gerber (Geometry):
  155. """
  156. **ATTRIBUTES**
  157. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  158. The values are dictionaries key/value pairs which describe the aperture. The
  159. type key is always present and the rest depend on the key:
  160. +-----------+-----------------------------------+
  161. | Key | Value |
  162. +===========+===================================+
  163. | type | (str) "C", "R", or "O" |
  164. +-----------+-----------------------------------+
  165. | others | Depend on ``type`` |
  166. +-----------+-----------------------------------+
  167. * ``paths`` (list): A path is described by a line an aperture that follows that
  168. line. Each paths[i] is a dictionary:
  169. +------------+------------------------------------------------+
  170. | Key | Value |
  171. +============+================================================+
  172. | linestring | (Shapely.LineString) The actual path. |
  173. +------------+------------------------------------------------+
  174. | aperture | (str) The key for an aperture in apertures. |
  175. +------------+------------------------------------------------+
  176. * ``flashes`` (list): Flashes are single-point strokes of an aperture. Each
  177. is a dictionary:
  178. +------------+------------------------------------------------+
  179. | Key | Value |
  180. +============+================================================+
  181. | loc | (list) [x (float), y (float)] coordinates. |
  182. +------------+------------------------------------------------+
  183. | aperture | (str) The key for an aperture in apertures. |
  184. +------------+------------------------------------------------+
  185. * ``regions`` (list): Are surfaces defined by a polygon (Shapely.Polygon),
  186. which have an exterior and zero or more interiors. An aperture is also
  187. associated with a region. Each is a dictionary:
  188. +------------+-----------------------------------------------------+
  189. | Key | Value |
  190. +============+=====================================================+
  191. | polygon | (Shapely.Polygon) The polygon defining the region. |
  192. +------------+-----------------------------------------------------+
  193. | aperture | (str) The key for an aperture in apertures. |
  194. +------------+-----------------------------------------------------+
  195. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  196. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  197. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  198. *buffering* (or thickening) the ``paths`` with the aperture. These are
  199. generated from ``paths`` in ``buffer_paths()``.
  200. **USAGE**::
  201. g = Gerber()
  202. g.parse_file(filename)
  203. g.create_geometry()
  204. do_something(s.solid_geometry)
  205. """
  206. def __init__(self):
  207. """
  208. The constructor takes no parameters. Use ``gerber.parse_files()``
  209. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  210. :return: Gerber object
  211. :rtype: Gerber
  212. """
  213. # Initialize parent
  214. Geometry.__init__(self)
  215. # Number format
  216. self.int_digits = 3
  217. """Number of integer digits in Gerber numbers. Used during parsing."""
  218. self.frac_digits = 4
  219. """Number of fraction digits in Gerber numbers. Used during parsing."""
  220. ## Gerber elements ##
  221. # Apertures {'id':{'type':chr,
  222. # ['size':float], ['width':float],
  223. # ['height':float]}, ...}
  224. self.apertures = {}
  225. # Paths [{'linestring':LineString, 'aperture':str}]
  226. self.paths = []
  227. # Buffered Paths [Polygon]
  228. # Paths transformed into Polygons by
  229. # offsetting the aperture size/2
  230. self.buffered_paths = []
  231. # Polygon regions [{'polygon':Polygon, 'aperture':str}]
  232. self.regions = []
  233. # Flashes [{'loc':[float,float], 'aperture':str}]
  234. self.flashes = []
  235. # Geometry from flashes
  236. self.flash_geometry = []
  237. # Attributes to be included in serialization
  238. # Always append to it because it carries contents
  239. # from Geometry.
  240. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures', 'paths',
  241. 'buffered_paths', 'regions', 'flashes',
  242. 'flash_geometry']
  243. #### Parser patterns ####
  244. # FS - Format Specification
  245. # The format of X and Y must be the same!
  246. # L-omit leading zeros, T-omit trailing zeros
  247. # A-absolute notation, I-incremental notation
  248. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  249. # Mode (IN/MM)
  250. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  251. # Comment G04|G4
  252. self.comm_re = re.compile(r'^G0?4(.*)$')
  253. # AD - Aperture definition
  254. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z0-9]*),(.*)\*%$')
  255. # AM - Aperture Macro
  256. # Beginning of macro (Ends with *%):
  257. self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  258. # Tool change
  259. # May begin with G54 but that is deprecated
  260. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  261. # G01 - Linear interpolation plus flashes
  262. # Operation code (D0x) missing is deprecated... oh well I will support it.
  263. self.lin_re = re.compile(r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$')
  264. self.setlin_re = re.compile(r'^(?:G0?1)\*')
  265. # G02/3 - Circular interpolation
  266. # 2-clockwise, 3-counterclockwise
  267. self.circ_re = re.compile(r'^(?:G0?([23]))?(?:X(-?\d+))?(?:Y(-?\d+))' +
  268. '?(?:I(-?\d+))?(?:J(-?\d+))?D0([12])\*$')
  269. # G01/2/3 Occurring without coordinates
  270. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  271. # Single D74 or multi D75 quadrant for circular interpolation
  272. self.quad_re = re.compile(r'^G7([45])\*$')
  273. # Region mode on
  274. # In region mode, D01 starts a region
  275. # and D02 ends it. A new region can be started again
  276. # with D01. All contours must be closed before
  277. # D02 or G37.
  278. self.regionon_re = re.compile(r'^G36\*$')
  279. # Region mode off
  280. # Will end a region and come off region mode.
  281. # All contours must be closed before D02 or G37.
  282. self.regionoff_re = re.compile(r'^G37\*$')
  283. # End of file
  284. self.eof_re = re.compile(r'^M02\*')
  285. # IP - Image polarity
  286. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  287. # LP - Level polarity
  288. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  289. # TODO: This is bad.
  290. self.steps_per_circ = 40
  291. def scale(self, factor):
  292. """
  293. Scales the objects' geometry on the XY plane by a given factor.
  294. These are:
  295. * ``apertures``
  296. * ``paths``
  297. * ``regions``
  298. * ``flashes``
  299. Then ``buffered_paths``, ``flash_geometry`` and ``solid_geometry``
  300. are re-created with ``self.create_geometry()``.
  301. :param factor: Number by which to scale.
  302. :type factor: float
  303. :rtype : None
  304. """
  305. # Apertures
  306. #print "Scaling apertures..."
  307. #List of the non-dimension aperture parameters
  308. nonDimensions = ["type", "nVertices", "rotation"]
  309. for apid in self.apertures:
  310. for param in self.apertures[apid]:
  311. if param not in nonDimensions: # All others are dimensions.
  312. print "Tool:", apid, "Parameter:", param
  313. self.apertures[apid][param] *= factor
  314. # Paths
  315. #print "Scaling paths..."
  316. for path in self.paths:
  317. path['linestring'] = affinity.scale(path['linestring'],
  318. factor, factor, origin=(0, 0))
  319. # Flashes
  320. #print "Scaling flashes..."
  321. for fl in self.flashes:
  322. # TODO: Shouldn't 'loc' be a numpy.array()?
  323. fl['loc'][0] *= factor
  324. fl['loc'][1] *= factor
  325. # Regions
  326. #print "Scaling regions..."
  327. for reg in self.regions:
  328. reg['polygon'] = affinity.scale(reg['polygon'], factor, factor,
  329. origin=(0, 0))
  330. # Now buffered_paths, flash_geometry and solid_geometry
  331. self.create_geometry()
  332. def offset(self, vect):
  333. """
  334. Offsets the objects' geometry on the XY plane by a given vector.
  335. These are:
  336. * ``paths``
  337. * ``regions``
  338. * ``flashes``
  339. Then ``buffered_paths``, ``flash_geometry`` and ``solid_geometry``
  340. are re-created with ``self.create_geometry()``.
  341. :param vect: (x, y) offset vector.
  342. :type vect: tuple
  343. :return: None
  344. """
  345. dx, dy = vect
  346. # Paths
  347. #print "Shifting paths..."
  348. for path in self.paths:
  349. path['linestring'] = affinity.translate(path['linestring'],
  350. xoff=dx, yoff=dy)
  351. # Flashes
  352. #print "Shifting flashes..."
  353. for fl in self.flashes:
  354. # TODO: Shouldn't 'loc' be a numpy.array()?
  355. fl['loc'][0] += dx
  356. fl['loc'][1] += dy
  357. # Regions
  358. #print "Shifting regions..."
  359. for reg in self.regions:
  360. reg['polygon'] = affinity.translate(reg['polygon'],
  361. xoff=dx, yoff=dy)
  362. # Now buffered_paths, flash_geometry and solid_geometry
  363. self.create_geometry()
  364. def fix_regions(self):
  365. """
  366. Overwrites the region polygons with fixed
  367. versions if found to be invalid (according to Shapely).
  368. """
  369. for region in self.regions:
  370. if not region['polygon'].is_valid:
  371. region['polygon'] = region['polygon'].buffer(0)
  372. def buffer_paths(self):
  373. """
  374. This is part of the parsing process. "Thickens" the paths
  375. by their appertures. This will only work for circular appertures.
  376. :return: None
  377. """
  378. self.buffered_paths = []
  379. for path in self.paths:
  380. try:
  381. width = self.apertures[path["aperture"]]["size"]
  382. self.buffered_paths.append(path["linestring"].buffer(width/2))
  383. except KeyError:
  384. print "ERROR: Failed to buffer path: ", path
  385. print "Apertures: ", self.apertures
  386. def aperture_parse(self, apertureId, apertureType, apParameters):
  387. """
  388. Parse gerber aperture definition into dictionary of apertures.
  389. The following kinds and their attributes are supported:
  390. * *Circular (C)*: size (float)
  391. * *Rectangle (R)*: width (float), height (float)
  392. * *Obround (O)*: width (float), height (float).
  393. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  394. :param apertureId: Id of the aperture being defined.
  395. :param apertureType: Type of the aperture.
  396. :param apParameters: Parameters of the aperture.
  397. :type apertureId: str
  398. :type apertureType: str
  399. :type apParameters: str
  400. :return: Identifier of the aperture.
  401. :rtype: str
  402. """
  403. # Found some Gerber with a leading zero in the aperture id and the
  404. # referenced it without the zero, so this is a hack to handle that.
  405. apid = str(int(apertureId))
  406. paramList = apParameters.split('X')
  407. if apertureType == "C" : # Circle, example: %ADD11C,0.1*%
  408. self.apertures[apid] = {"type": "C",
  409. "size": float(paramList[0])}
  410. return apid
  411. if apertureType == "R" : # Rectangle, example: %ADD15R,0.05X0.12*%
  412. self.apertures[apid] = {"type": "R",
  413. "width": float(paramList[0]),
  414. "height": float(paramList[1])}
  415. return apid
  416. if apertureType == "O" : # Obround
  417. self.apertures[apid] = {"type": "O",
  418. "width": float(paramList[0]),
  419. "height": float(paramList[1])}
  420. return apid
  421. if apertureType == "P" :
  422. self.apertures[apid] = {"type": "P",
  423. "diam": float(paramList[0]),
  424. "nVertices": int(paramList[1])}
  425. if len(paramList) >= 3 :
  426. self.apertures[apid]["rotation"] = float(paramList[2])
  427. return apid
  428. print "WARNING: Aperture not implemented:", apertureType
  429. return None
  430. def parse_file(self, filename):
  431. """
  432. Calls Gerber.parse_lines() with array of lines
  433. read from the given file.
  434. """
  435. gfile = open(filename, 'r')
  436. gstr = gfile.readlines()
  437. gfile.close()
  438. self.parse_lines(gstr)
  439. def parse_lines(self, glines):
  440. """
  441. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  442. ``self.flashes``, ``self.regions`` and ``self.units``.
  443. :param glines: Gerber code as list of strings, each element being
  444. one line of the source file.
  445. :type glines: list
  446. :return: None
  447. :rtype: None
  448. """
  449. path = [] # Coordinates of the current path, each is [x, y]
  450. last_path_aperture = None
  451. current_aperture = None
  452. # 1,2 or 3 from "G01", "G02" or "G03"
  453. current_interpolation_mode = None
  454. # 1 or 2 from "D01" or "D02"
  455. # Note this is to support deprecated Gerber not putting
  456. # an operation code at the end of every coordinate line.
  457. current_operation_code = None
  458. # Current coordinates
  459. current_x = None
  460. current_y = None
  461. # How to interprest circular interpolation: SINGLE or MULTI
  462. quadrant_mode = None
  463. line_num = 0
  464. for gline in glines:
  465. line_num += 1
  466. ## G01 - Linear interpolation plus flashes
  467. # Operation code (D0x) missing is deprecated... oh well I will support it.
  468. match = self.lin_re.search(gline)
  469. if match:
  470. # Dxx alone? Will ignore for now.
  471. if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  472. try:
  473. current_operation_code = int(match.group(4))
  474. except:
  475. pass # A line with just * will match too.
  476. continue
  477. # Parse coordinates
  478. if match.group(2) is not None:
  479. current_x = parse_gerber_number(match.group(2), self.frac_digits)
  480. if match.group(3) is not None:
  481. current_y = parse_gerber_number(match.group(3), self.frac_digits)
  482. # Parse operation code
  483. if match.group(4) is not None:
  484. current_operation_code = int(match.group(4))
  485. # Pen down: add segment
  486. if current_operation_code == 1:
  487. path.append([current_x, current_y])
  488. last_path_aperture = current_aperture
  489. # Pen up: finish path
  490. elif current_operation_code == 2:
  491. if len(path) > 1:
  492. if last_path_aperture is None:
  493. print "Warning: No aperture defined for curent path. (%d)" % line_num
  494. self.paths.append({"linestring": LineString(path),
  495. "aperture": last_path_aperture})
  496. path = [[current_x, current_y]] # Start new path
  497. # Flash
  498. elif current_operation_code == 3:
  499. self.flashes.append({"loc": [current_x, current_y],
  500. "aperture": current_aperture})
  501. continue
  502. ## G02/3 - Circular interpolation
  503. # 2-clockwise, 3-counterclockwise
  504. match = self.circ_re.search(gline)
  505. if match:
  506. mode, x, y, i, j, d = match.groups()
  507. try:
  508. x = parse_gerber_number(x, self.frac_digits)
  509. except:
  510. x = current_x
  511. try:
  512. y = parse_gerber_number(y, self.frac_digits)
  513. except:
  514. y = current_y
  515. try:
  516. i = parse_gerber_number(i, self.frac_digits)
  517. except:
  518. i = 0
  519. try:
  520. j = parse_gerber_number(j, self.frac_digits)
  521. except:
  522. j = 0
  523. if quadrant_mode is None:
  524. print "ERROR: Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num
  525. print gline
  526. continue
  527. if mode is None and current_interpolation_mode not in [2, 3]:
  528. print "ERROR: Found arc without circular interpolation mode defined. (%d)" % line_num
  529. print gline
  530. continue
  531. elif mode is not None:
  532. current_interpolation_mode = int(mode)
  533. # Set operation code if provided
  534. if d is not None:
  535. current_operation_code = int(d)
  536. # Nothing created! Pen Up.
  537. if current_operation_code == 2:
  538. print "Warning: Arc with D2. (%d)" % line_num
  539. if len(path) > 1:
  540. if last_path_aperture is None:
  541. print "Warning: No aperture defined for curent path. (%d)" % line_num
  542. self.paths.append({"linestring": LineString(path),
  543. "aperture": last_path_aperture})
  544. current_x = x
  545. current_y = y
  546. path = [[current_x, current_y]] # Start new path
  547. continue
  548. # Flash should not happen here
  549. if current_operation_code == 3:
  550. print "ERROR: Trying to flash within arc. (%d)" % line_num
  551. continue
  552. if quadrant_mode == 'MULTI':
  553. center = [i + current_x, j + current_y]
  554. radius = sqrt(i**2 + j**2)
  555. start = arctan2(-j, -i)
  556. stop = arctan2(-center[1] + y, -center[0] + x)
  557. arcdir = [None, None, "cw", "ccw"]
  558. this_arc = arc(center, radius, start, stop,
  559. arcdir[current_interpolation_mode],
  560. self.steps_per_circ)
  561. # Last point in path is current point
  562. current_x = this_arc[-1][0]
  563. current_y = this_arc[-1][1]
  564. # Append
  565. path += this_arc
  566. last_path_aperture = current_aperture
  567. continue
  568. if quadrant_mode == 'SINGLE':
  569. print "Warning: Single quadrant arc are not implemented yet. (%d)" % line_num
  570. ## G74/75* - Single or multiple quadrant arcs
  571. match = self.quad_re.search(gline)
  572. if match:
  573. if match.group(1) == '4':
  574. quadrant_mode = 'SINGLE'
  575. else:
  576. quadrant_mode = 'MULTI'
  577. continue
  578. ## G37* - End region
  579. if self.regionoff_re.search(gline):
  580. # Only one path defines region?
  581. if len(path) < 3:
  582. print "ERROR: Path contains less than 3 points:"
  583. print path
  584. print "Line (%d): " % line_num, gline
  585. path = []
  586. continue
  587. # For regions we may ignore an aperture that is None
  588. self.regions.append({"polygon": Polygon(path),
  589. "aperture": last_path_aperture})
  590. #path = []
  591. path = [[current_x, current_y]] # Start new path
  592. continue
  593. #Parse an aperture.
  594. match = self.ad_re.search(gline)
  595. if match:
  596. self.aperture_parse(match.group(1),match.group(2),match.group(3))
  597. continue
  598. ## G01/2/3* - Interpolation mode change
  599. # Can occur along with coordinates and operation code but
  600. # sometimes by itself (handled here).
  601. # Example: G01*
  602. match = self.interp_re.search(gline)
  603. if match:
  604. current_interpolation_mode = int(match.group(1))
  605. continue
  606. ## Tool/aperture change
  607. # Example: D12*
  608. match = self.tool_re.search(gline)
  609. if match:
  610. current_aperture = match.group(1)
  611. continue
  612. ## Number format
  613. # Example: %FSLAX24Y24*%
  614. # TODO: This is ignoring most of the format. Implement the rest.
  615. match = self.fmt_re.search(gline)
  616. if match:
  617. self.int_digits = int(match.group(3))
  618. self.frac_digits = int(match.group(4))
  619. continue
  620. ## Mode (IN/MM)
  621. # Example: %MOIN*%
  622. match = self.mode_re.search(gline)
  623. if match:
  624. self.units = match.group(1)
  625. continue
  626. print "WARNING: Line ignored (%d):" % line_num, gline
  627. if len(path) > 1:
  628. # EOF, create shapely LineString if something still in path
  629. self.paths.append({"linestring": LineString(path),
  630. "aperture": last_path_aperture})
  631. def do_flashes(self):
  632. """
  633. Creates geometry for Gerber flashes (aperture on a single point).
  634. """
  635. self.flash_geometry = []
  636. for flash in self.flashes:
  637. try:
  638. aperture = self.apertures[flash['aperture']]
  639. except KeyError:
  640. print "ERROR: Trying to flash with unknown aperture: ", flash['aperture']
  641. continue
  642. if aperture['type'] == 'C': # Circles
  643. circle = Point(flash['loc']).buffer(aperture['size']/2)
  644. self.flash_geometry.append(circle)
  645. continue
  646. if aperture['type'] == 'R': # Rectangles
  647. loc = flash['loc']
  648. width = aperture['width']
  649. height = aperture['height']
  650. minx = loc[0] - width/2
  651. maxx = loc[0] + width/2
  652. miny = loc[1] - height/2
  653. maxy = loc[1] + height/2
  654. rectangle = shply_box(minx, miny, maxx, maxy)
  655. self.flash_geometry.append(rectangle)
  656. continue
  657. if aperture['type'] == 'O': # Obround
  658. loc = flash['loc']
  659. width = aperture['width']
  660. height = aperture['height']
  661. if width > height:
  662. p1 = Point(loc[0] + 0.5*(width-height), loc[1])
  663. p2 = Point(loc[0] - 0.5*(width-height), loc[1])
  664. c1 = p1.buffer(height*0.5)
  665. c2 = p2.buffer(height*0.5)
  666. else:
  667. p1 = Point(loc[0], loc[1] + 0.5*(height-width))
  668. p2 = Point(loc[0], loc[1] - 0.5*(height-width))
  669. c1 = p1.buffer(width*0.5)
  670. c2 = p2.buffer(width*0.5)
  671. obround = cascaded_union([c1, c2]).convex_hull
  672. self.flash_geometry.append(obround)
  673. continue
  674. if aperture['type'] == 'P': #Regular polygon
  675. loc = flash['loc']
  676. diam = aperture['diam']
  677. nVertices = aperture['nVertices']
  678. points = []
  679. for i in range(0,nVertices):
  680. x = loc[0] + diam * (cos(2 * pi * i / nVertices))
  681. y = loc[1] + diam * (sin(2 * pi * i / nVertices))
  682. points.append((x,y))
  683. ply = Polygon(points)
  684. if 'rotation' in aperture:
  685. ply = affinity.rotate(ply, aperture['rotation'])
  686. self.flash_geometry.append(ply)
  687. continue
  688. print "WARNING: Aperture type %s not implemented" % (aperture['type'])
  689. def create_geometry(self):
  690. """
  691. Geometry from a Gerber file is made up entirely of polygons.
  692. Every stroke (linear or circular) has an aperture which gives
  693. it thickness. Additionally, aperture strokes have non-zero area,
  694. and regions naturally do as well.
  695. :rtype : None
  696. :return: None
  697. """
  698. self.buffer_paths()
  699. self.fix_regions()
  700. self.do_flashes()
  701. self.solid_geometry = cascaded_union(self.buffered_paths +
  702. [poly['polygon'] for poly in self.regions] +
  703. self.flash_geometry)
  704. def get_bounding_box(self, margin=0.0, rounded=False):
  705. """
  706. Creates and returns a rectangular polygon bounding at a distance of
  707. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  708. can optionally have rounded corners of radius equal to margin.
  709. :param margin: Distance to enlarge the rectangular bounding
  710. box in both positive and negative, x and y axes.
  711. :type margin: float
  712. :param rounded: Wether or not to have rounded corners.
  713. :type rounded: bool
  714. :return: The bounding box.
  715. :rtype: Shapely.Polygon
  716. """
  717. bbox = self.solid_geometry.envelope.buffer(margin)
  718. if not rounded:
  719. bbox = bbox.envelope
  720. return bbox
  721. class Excellon(Geometry):
  722. """
  723. *ATTRIBUTES*
  724. * ``tools`` (dict): The key is the tool name and the value is
  725. the size (diameter).
  726. * ``drills`` (list): Each is a dictionary:
  727. ================ ====================================
  728. Key Value
  729. ================ ====================================
  730. point (Shapely.Point) Where to drill
  731. tool (str) A key in ``tools``
  732. ================ ====================================
  733. """
  734. def __init__(self):
  735. """
  736. The constructor takes no parameters.
  737. :return: Excellon object.
  738. :rtype: Excellon
  739. """
  740. Geometry.__init__(self)
  741. self.tools = {}
  742. self.drills = []
  743. # Trailing "T" or leading "L"
  744. self.zeros = ""
  745. # Attributes to be included in serialization
  746. # Always append to it because it carries contents
  747. # from Geometry.
  748. self.ser_attrs += ['tools', 'drills', 'zeros']
  749. #### Patterns ####
  750. # Regex basics:
  751. # ^ - beginning
  752. # $ - end
  753. # *: 0 or more, +: 1 or more, ?: 0 or 1
  754. # M48 - Beggining of Part Program Header
  755. self.hbegin_re = re.compile(r'^M48$')
  756. # M95 or % - End of Part Program Header
  757. # NOTE: % has different meaning in the body
  758. self.hend_re = re.compile(r'^(?:M95|%)$')
  759. # FMAT Excellon format
  760. self.fmat_re = re.compile(r'^FMAT,([12])$')
  761. # Number format and units
  762. # INCH uses 6 digits
  763. # METRIC uses 5/6
  764. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  765. # Tool definition/parameters (?= is look-ahead
  766. # NOTE: This might be an overkill!
  767. self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  768. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  769. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  770. r'(?=.*Z(-?\d*\.?\d*))?[CFSBHT]')
  771. # Tool select
  772. # Can have additional data after tool number but
  773. # is ignored if present in the header.
  774. # Warning: This will match toolset_re too.
  775. self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  776. # Comment
  777. self.comm_re = re.compile(r'^;(.*)$')
  778. # Absolute/Incremental G90/G91
  779. self.absinc_re = re.compile(r'^G9([01])$')
  780. # Modes of operation
  781. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  782. self.modes_re = re.compile(r'^G0([012345])')
  783. # Measuring mode
  784. # 1-metric, 2-inch
  785. self.meas_re = re.compile(r'^M7([12])$')
  786. # Coordinates
  787. #self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  788. #self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  789. self.coordsperiod_re = re.compile(r'(?=.*X(\d*\.\d*))?(?=.*Y(\d*\.\d*))?[XY]')
  790. self.coordsnoperiod_re = re.compile(r'(?!.*\.)(?=.*X(\d*))?(?=.*Y(\d*))?[XY]')
  791. # R - Repeat hole (# times, X offset, Y offset)
  792. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X(\d*\.?\d*))?(?:Y(\d*\.?\d*))?$')
  793. # Various stop/pause commands
  794. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  795. def parse_file(self, filename):
  796. """
  797. Reads the specified file as array of lines as
  798. passes it to ``parse_lines()``.
  799. :param filename: The file to be read and parsed.
  800. :type filename: str
  801. :return: None
  802. """
  803. efile = open(filename, 'r')
  804. estr = efile.readlines()
  805. efile.close()
  806. self.parse_lines(estr)
  807. def parse_lines(self, elines):
  808. """
  809. Main Excellon parser.
  810. :param elines: List of strings, each being a line of Excellon code.
  811. :type elines: list
  812. :return: None
  813. """
  814. # State variables
  815. current_tool = ""
  816. in_header = False
  817. current_x = None
  818. current_y = None
  819. i = 0 # Line number
  820. for eline in elines:
  821. i += 1
  822. ## Header Begin/End ##
  823. if self.hbegin_re.search(eline):
  824. in_header = True
  825. continue
  826. if self.hend_re.search(eline):
  827. in_header = False
  828. continue
  829. #### Body ####
  830. if not in_header:
  831. ## Tool change ##
  832. match = self.toolsel_re.search(eline)
  833. if match:
  834. current_tool = str(int(match.group(1)))
  835. continue
  836. ## Coordinates without period ##
  837. match = self.coordsnoperiod_re.search(eline)
  838. if match:
  839. try:
  840. x = float(match.group(1))/10000
  841. current_x = x
  842. except TypeError:
  843. x = current_x
  844. try:
  845. y = float(match.group(2))/10000
  846. current_y = y
  847. except TypeError:
  848. y = current_y
  849. if x is None or y is None:
  850. print "ERROR: Missing coordinates"
  851. continue
  852. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  853. continue
  854. ## Coordinates with period ##
  855. match = self.coordsperiod_re.search(eline)
  856. if match:
  857. try:
  858. x = float(match.group(1))
  859. current_x = x
  860. except TypeError:
  861. x = current_x
  862. try:
  863. y = float(match.group(2))
  864. current_y = y
  865. except TypeError:
  866. y = current_y
  867. if x is None or y is None:
  868. print "ERROR: Missing coordinates"
  869. continue
  870. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  871. continue
  872. #### Header ####
  873. if in_header:
  874. ## Tool definitions ##
  875. match = self.toolset_re.search(eline)
  876. if match:
  877. name = str(int(match.group(1)))
  878. spec = {
  879. "C": float(match.group(2)),
  880. # "F": float(match.group(3)),
  881. # "S": float(match.group(4)),
  882. # "B": float(match.group(5)),
  883. # "H": float(match.group(6)),
  884. # "Z": float(match.group(7))
  885. }
  886. self.tools[name] = spec
  887. continue
  888. ## Units and number format ##
  889. match = self.units_re.match(eline)
  890. if match:
  891. self.zeros = match.group(2) # "T" or "L"
  892. self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  893. continue
  894. print "WARNING: Line ignored:", eline
  895. def create_geometry(self):
  896. self.solid_geometry = []
  897. for drill in self.drills:
  898. poly = Point(drill['point']).buffer(self.tools[drill['tool']]["C"]/2.0)
  899. self.solid_geometry.append(poly)
  900. #self.solid_geometry = cascaded_union(self.solid_geometry)
  901. def scale(self, factor):
  902. """
  903. Scales geometry on the XY plane in the object by a given factor.
  904. Tool sizes, feedrates an Z-plane dimensions are untouched.
  905. :param factor: Number by which to scale the object.
  906. :type factor: float
  907. :return: None
  908. :rtype: NOne
  909. """
  910. # Drills
  911. for drill in self.drills:
  912. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  913. self.create_geometry()
  914. def offset(self, vect):
  915. """
  916. Offsets geometry on the XY plane in the object by a given vector.
  917. :param vect: (x, y) offset vector.
  918. :type vect: tuple
  919. :return: None
  920. """
  921. dx, dy = vect
  922. # Drills
  923. for drill in self.drills:
  924. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  925. self.create_geometry()
  926. def convert_units(self, units):
  927. factor = Geometry.convert_units(self, units)
  928. # Tools
  929. for tname in self.tools:
  930. self.tools[tname]["C"] *= factor
  931. self.create_geometry()
  932. return factor
  933. class CNCjob(Geometry):
  934. """
  935. Represents work to be done by a CNC machine.
  936. *ATTRIBUTES*
  937. * ``gcode_parsed`` (list): Each is a dictionary:
  938. ===================== =========================================
  939. Key Value
  940. ===================== =========================================
  941. geom (Shapely.LineString) Tool path (XY plane)
  942. kind (string) "AB", A is "T" (travel) or
  943. "C" (cut). B is "F" (fast) or "S" (slow).
  944. ===================== =========================================
  945. """
  946. def __init__(self, units="in", kind="generic", z_move=0.1,
  947. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  948. Geometry.__init__(self)
  949. self.kind = kind
  950. self.units = units
  951. self.z_cut = z_cut
  952. self.z_move = z_move
  953. self.feedrate = feedrate
  954. self.tooldia = tooldia
  955. self.unitcode = {"IN": "G20", "MM": "G21"}
  956. self.pausecode = "G04 P1"
  957. self.feedminutecode = "G94"
  958. self.absolutecode = "G90"
  959. self.gcode = ""
  960. self.input_geometry_bounds = None
  961. self.gcode_parsed = None
  962. self.steps_per_circ = 20 # Used when parsing G-code arcs
  963. # Attributes to be included in serialization
  964. # Always append to it because it carries contents
  965. # from Geometry.
  966. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  967. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  968. 'steps_per_circ']
  969. def convert_units(self, units):
  970. factor = Geometry.convert_units(self, units)
  971. print "CNCjob.convert_units()"
  972. self.z_cut *= factor
  973. self.z_move *= factor
  974. self.feedrate *= factor
  975. self.tooldia *= factor
  976. return factor
  977. def generate_from_excellon(self, exobj):
  978. """
  979. Generates G-code for drilling from Excellon object.
  980. self.gcode becomes a list, each element is a
  981. different job for each tool in the excellon code.
  982. """
  983. self.kind = "drill"
  984. self.gcode = []
  985. t = "G00 X%.4fY%.4f\n"
  986. down = "G01 Z%.4f\n" % self.z_cut
  987. up = "G01 Z%.4f\n" % self.z_move
  988. for tool in exobj.tools:
  989. points = []
  990. for drill in exobj.drill:
  991. if drill['tool'] == tool:
  992. points.append(drill['point'])
  993. gcode = self.unitcode[self.units.upper()] + "\n"
  994. gcode += self.absolutecode + "\n"
  995. gcode += self.feedminutecode + "\n"
  996. gcode += "F%.2f\n" % self.feedrate
  997. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  998. gcode += "M03\n" # Spindle start
  999. gcode += self.pausecode + "\n"
  1000. for point in points:
  1001. gcode += t % point
  1002. gcode += down + up
  1003. gcode += t % (0, 0)
  1004. gcode += "M05\n" # Spindle stop
  1005. self.gcode.append(gcode)
  1006. def generate_from_excellon_by_tool(self, exobj, tools="all"):
  1007. """
  1008. Creates gcode for this object from an Excellon object
  1009. for the specified tools.
  1010. :param exobj: Excellon object to process
  1011. :type exobj: Excellon
  1012. :param tools: Comma separated tool names
  1013. :type: tools: str
  1014. :return: None
  1015. :rtype: None
  1016. """
  1017. print "Creating CNC Job from Excellon..."
  1018. if tools == "all":
  1019. tools = [tool for tool in exobj.tools]
  1020. else:
  1021. tools = [x.strip() for x in tools.split(",")]
  1022. tools = filter(lambda y: y in exobj.tools, tools)
  1023. print "Tools are:", tools
  1024. points = []
  1025. for drill in exobj.drills:
  1026. if drill['tool'] in tools:
  1027. points.append(drill['point'])
  1028. print "Found %d drills." % len(points)
  1029. #self.kind = "drill"
  1030. self.gcode = []
  1031. t = "G00 X%.4fY%.4f\n"
  1032. down = "G01 Z%.4f\n" % self.z_cut
  1033. up = "G01 Z%.4f\n" % self.z_move
  1034. gcode = self.unitcode[self.units.upper()] + "\n"
  1035. gcode += self.absolutecode + "\n"
  1036. gcode += self.feedminutecode + "\n"
  1037. gcode += "F%.2f\n" % self.feedrate
  1038. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1039. gcode += "M03\n" # Spindle start
  1040. gcode += self.pausecode + "\n"
  1041. for point in points:
  1042. x, y = point.coords.xy
  1043. gcode += t % (x[0], y[0])
  1044. gcode += down + up
  1045. gcode += t % (0, 0)
  1046. gcode += "M05\n" # Spindle stop
  1047. self.gcode = gcode
  1048. def generate_from_geometry(self, geometry, append=True, tooldia=None, tolerance=0):
  1049. """
  1050. Generates G-Code from a Geometry object. Stores in ``self.gcode``.
  1051. :param geometry: Geometry defining the toolpath
  1052. :type geometry: Geometry
  1053. :param append: Wether to append to self.gcode or re-write it.
  1054. :type append: bool
  1055. :param tooldia: If given, sets the tooldia property but does
  1056. not affect the process in any other way.
  1057. :type tooldia: bool
  1058. :param tolerance: All points in the simplified object will be within the
  1059. tolerance distance of the original geometry.
  1060. :return: None
  1061. :rtype: None
  1062. """
  1063. if tooldia is not None:
  1064. self.tooldia = tooldia
  1065. self.input_geometry_bounds = geometry.bounds()
  1066. if not append:
  1067. self.gcode = ""
  1068. self.gcode = self.unitcode[self.units.upper()] + "\n"
  1069. self.gcode += self.absolutecode + "\n"
  1070. self.gcode += self.feedminutecode + "\n"
  1071. self.gcode += "F%.2f\n" % self.feedrate
  1072. self.gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1073. self.gcode += "M03\n" # Spindle start
  1074. self.gcode += self.pausecode + "\n"
  1075. for geo in geometry.solid_geometry:
  1076. if type(geo) == Polygon:
  1077. self.gcode += self.polygon2gcode(geo, tolerance=tolerance)
  1078. continue
  1079. if type(geo) == LineString or type(geo) == LinearRing:
  1080. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  1081. continue
  1082. if type(geo) == Point:
  1083. self.gcode += self.point2gcode(geo)
  1084. continue
  1085. if type(geo) == MultiPolygon:
  1086. for poly in geo:
  1087. self.gcode += self.polygon2gcode(poly, tolerance=tolerance)
  1088. continue
  1089. print "WARNING: G-code generation not implemented for %s" % (str(type(geo)))
  1090. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1091. self.gcode += "G00 X0Y0\n"
  1092. self.gcode += "M05\n" # Spindle stop
  1093. def pre_parse(self, gtext):
  1094. """
  1095. Separates parts of the G-Code text into a list of dictionaries.
  1096. Used by ``self.gcode_parse()``.
  1097. :param gtext: A single string with g-code
  1098. """
  1099. # Units: G20-inches, G21-mm
  1100. units_re = re.compile(r'^G2([01])')
  1101. # TODO: This has to be re-done
  1102. gcmds = []
  1103. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  1104. for line in lines:
  1105. # Clean up
  1106. line = line.strip()
  1107. # Remove comments
  1108. # NOTE: Limited to 1 bracket pair
  1109. op = line.find("(")
  1110. cl = line.find(")")
  1111. if op > -1 and cl > op:
  1112. #comment = line[op+1:cl]
  1113. line = line[:op] + line[(cl+1):]
  1114. # Units
  1115. match = units_re.match(line)
  1116. if match:
  1117. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  1118. # Parse GCode
  1119. # 0 4 12
  1120. # G01 X-0.007 Y-0.057
  1121. # --> codes_idx = [0, 4, 12]
  1122. codes = "NMGXYZIJFP"
  1123. codes_idx = []
  1124. i = 0
  1125. for ch in line:
  1126. if ch in codes:
  1127. codes_idx.append(i)
  1128. i += 1
  1129. n_codes = len(codes_idx)
  1130. if n_codes == 0:
  1131. continue
  1132. # Separate codes in line
  1133. parts = []
  1134. for p in range(n_codes-1):
  1135. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  1136. parts.append(line[codes_idx[-1]:].strip())
  1137. # Separate codes from values
  1138. cmds = {}
  1139. for part in parts:
  1140. cmds[part[0]] = float(part[1:])
  1141. gcmds.append(cmds)
  1142. return gcmds
  1143. def gcode_parse(self):
  1144. """
  1145. G-Code parser (from self.gcode). Generates dictionary with
  1146. single-segment LineString's and "kind" indicating cut or travel,
  1147. fast or feedrate speed.
  1148. """
  1149. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1150. # Results go here
  1151. geometry = []
  1152. # TODO: Merge into single parser?
  1153. gobjs = self.pre_parse(self.gcode)
  1154. # Last known instruction
  1155. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  1156. # Current path: temporary storage until tool is
  1157. # lifted or lowered.
  1158. path = []
  1159. # Process every instruction
  1160. for gobj in gobjs:
  1161. # Changing height:
  1162. if 'Z' in gobj:
  1163. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  1164. print "WARNING: Non-orthogonal motion: From", current
  1165. print " To:", gobj
  1166. current['Z'] = gobj['Z']
  1167. # Store the path into geometry and reset path
  1168. if len(path) > 1:
  1169. geometry.append({"geom": LineString(path),
  1170. "kind": kind})
  1171. path = [path[-1]] # Start with the last point of last path.
  1172. if 'G' in gobj:
  1173. current['G'] = int(gobj['G'])
  1174. if 'X' in gobj or 'Y' in gobj:
  1175. if 'X' in gobj:
  1176. x = gobj['X']
  1177. else:
  1178. x = current['X']
  1179. if 'Y' in gobj:
  1180. y = gobj['Y']
  1181. else:
  1182. y = current['Y']
  1183. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1184. if current['Z'] > 0:
  1185. kind[0] = 'T'
  1186. if current['G'] > 0:
  1187. kind[1] = 'S'
  1188. arcdir = [None, None, "cw", "ccw"]
  1189. if current['G'] in [0, 1]: # line
  1190. path.append((x, y))
  1191. if current['G'] in [2, 3]: # arc
  1192. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  1193. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  1194. start = arctan2(-gobj['J'], -gobj['I'])
  1195. stop = arctan2(-center[1]+y, -center[0]+x)
  1196. path += arc(center, radius, start, stop,
  1197. arcdir[current['G']],
  1198. self.steps_per_circ)
  1199. # Update current instruction
  1200. for code in gobj:
  1201. current[code] = gobj[code]
  1202. self.gcode_parsed = geometry
  1203. return geometry
  1204. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  1205. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1206. # alpha={"T": 0.3, "C": 1.0}):
  1207. # """
  1208. # Creates a Matplotlib figure with a plot of the
  1209. # G-code job.
  1210. # """
  1211. # if tooldia is None:
  1212. # tooldia = self.tooldia
  1213. #
  1214. # fig = Figure(dpi=dpi)
  1215. # ax = fig.add_subplot(111)
  1216. # ax.set_aspect(1)
  1217. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  1218. # ax.set_xlim(xmin-margin, xmax+margin)
  1219. # ax.set_ylim(ymin-margin, ymax+margin)
  1220. #
  1221. # if tooldia == 0:
  1222. # for geo in self.gcode_parsed:
  1223. # linespec = '--'
  1224. # linecolor = color[geo['kind'][0]][1]
  1225. # if geo['kind'][0] == 'C':
  1226. # linespec = 'k-'
  1227. # x, y = geo['geom'].coords.xy
  1228. # ax.plot(x, y, linespec, color=linecolor)
  1229. # else:
  1230. # for geo in self.gcode_parsed:
  1231. # poly = geo['geom'].buffer(tooldia/2.0)
  1232. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1233. # edgecolor=color[geo['kind'][0]][1],
  1234. # alpha=alpha[geo['kind'][0]], zorder=2)
  1235. # ax.add_patch(patch)
  1236. #
  1237. # return fig
  1238. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  1239. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1240. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005):
  1241. """
  1242. Plots the G-code job onto the given axes.
  1243. :param axes: Matplotlib axes on which to plot.
  1244. :param tooldia: Tool diameter.
  1245. :param dpi: Not used!
  1246. :param margin: Not used!
  1247. :param color: Color specification.
  1248. :param alpha: Transparency specification.
  1249. :param tool_tolerance: Tolerance when drawing the toolshape.
  1250. :return: None
  1251. """
  1252. if tooldia is None:
  1253. tooldia = self.tooldia
  1254. if tooldia == 0:
  1255. for geo in self.gcode_parsed:
  1256. linespec = '--'
  1257. linecolor = color[geo['kind'][0]][1]
  1258. if geo['kind'][0] == 'C':
  1259. linespec = 'k-'
  1260. x, y = geo['geom'].coords.xy
  1261. axes.plot(x, y, linespec, color=linecolor)
  1262. else:
  1263. for geo in self.gcode_parsed:
  1264. poly = geo['geom'].buffer(tooldia/2.0).simplify(tool_tolerance)
  1265. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1266. edgecolor=color[geo['kind'][0]][1],
  1267. alpha=alpha[geo['kind'][0]], zorder=2)
  1268. axes.add_patch(patch)
  1269. def create_geometry(self):
  1270. # TODO: This takes forever. Too much data?
  1271. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  1272. def polygon2gcode(self, polygon, tolerance=0):
  1273. """
  1274. Creates G-Code for the exterior and all interior paths
  1275. of a polygon.
  1276. :param polygon: A Shapely.Polygon
  1277. :type polygon: Shapely.Polygon
  1278. :param tolerance: All points in the simplified object will be within the
  1279. tolerance distance of the original geometry.
  1280. :type tolerance: float
  1281. :return: G-code to cut along polygon.
  1282. :rtype: str
  1283. """
  1284. if tolerance > 0:
  1285. target_polygon = polygon.simplify(tolerance)
  1286. else:
  1287. target_polygon = polygon
  1288. gcode = ""
  1289. t = "G0%d X%.4fY%.4f\n"
  1290. path = list(target_polygon.exterior.coords) # Polygon exterior
  1291. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1292. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1293. for pt in path[1:]:
  1294. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1295. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1296. for ints in target_polygon.interiors: # Polygon interiors
  1297. path = list(ints.coords)
  1298. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1299. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1300. for pt in path[1:]:
  1301. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1302. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1303. return gcode
  1304. def linear2gcode(self, linear, tolerance=0):
  1305. """
  1306. Generates G-code to cut along the linear feature.
  1307. :param linear: The path to cut along.
  1308. :type: Shapely.LinearRing or Shapely.Linear String
  1309. :param tolerance: All points in the simplified object will be within the
  1310. tolerance distance of the original geometry.
  1311. :type tolerance: float
  1312. :return: G-code to cut alon the linear feature.
  1313. :rtype: str
  1314. """
  1315. if tolerance > 0:
  1316. target_linear = linear.simplify(tolerance)
  1317. else:
  1318. target_linear = linear
  1319. gcode = ""
  1320. t = "G0%d X%.4fY%.4f\n"
  1321. path = list(target_linear.coords)
  1322. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1323. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1324. for pt in path[1:]:
  1325. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1326. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1327. return gcode
  1328. def point2gcode(self, point):
  1329. # TODO: This is not doing anything.
  1330. gcode = ""
  1331. t = "G0%d X%.4fY%.4f\n"
  1332. path = list(point.coords)
  1333. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1334. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1335. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1336. def scale(self, factor):
  1337. """
  1338. Scales all the geometry on the XY plane in the object by the
  1339. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  1340. not altered.
  1341. :param factor: Number by which to scale the object.
  1342. :type factor: float
  1343. :return: None
  1344. :rtype: None
  1345. """
  1346. for g in self.gcode_parsed:
  1347. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1348. self.create_geometry()
  1349. def offset(self, vect):
  1350. """
  1351. Offsets all the geometry on the XY plane in the object by the
  1352. given vector.
  1353. :param vect: (x, y) offset vector.
  1354. :type vect: tuple
  1355. :return: None
  1356. """
  1357. dx, dy = vect
  1358. for g in self.gcode_parsed:
  1359. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  1360. self.create_geometry()
  1361. def get_bounds(geometry_set):
  1362. xmin = Inf
  1363. ymin = Inf
  1364. xmax = -Inf
  1365. ymax = -Inf
  1366. #print "Getting bounds of:", str(geometry_set)
  1367. for gs in geometry_set:
  1368. try:
  1369. gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  1370. xmin = min([xmin, gxmin])
  1371. ymin = min([ymin, gymin])
  1372. xmax = max([xmax, gxmax])
  1373. ymax = max([ymax, gymax])
  1374. except:
  1375. print "DEV WARNING: Tried to get bounds of empty geometry."
  1376. return [xmin, ymin, xmax, ymax]
  1377. def arc(center, radius, start, stop, direction, steps_per_circ):
  1378. """
  1379. Creates a list of point along the specified arc.
  1380. :param center: Coordinates of the center [x, y]
  1381. :type center: list
  1382. :param radius: Radius of the arc.
  1383. :type radius: float
  1384. :param start: Starting angle in radians
  1385. :type start: float
  1386. :param stop: End angle in radians
  1387. :type stop: float
  1388. :param direction: Orientation of the arc, "CW" or "CCW"
  1389. :type direction: string
  1390. :param steps_per_circ: Number of straight line segments to
  1391. represent a circle.
  1392. :type steps_per_circ: int
  1393. :return: The desired arc, as list of tuples
  1394. :rtype: list
  1395. """
  1396. # TODO: Resolution should be established by fraction of total length, not angle.
  1397. da_sign = {"cw": -1.0, "ccw": 1.0}
  1398. points = []
  1399. if direction == "ccw" and stop <= start:
  1400. stop += 2*pi
  1401. if direction == "cw" and stop >= start:
  1402. stop -= 2*pi
  1403. angle = abs(stop - start)
  1404. #angle = stop-start
  1405. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  1406. delta_angle = da_sign[direction]*angle*1.0/steps
  1407. for i in range(steps+1):
  1408. theta = start + delta_angle*i
  1409. points.append((center[0]+radius*cos(theta), center[1]+radius*sin(theta)))
  1410. return points
  1411. def clear_poly(poly, tooldia, overlap=0.1):
  1412. """
  1413. Creates a list of Shapely geometry objects covering the inside
  1414. of a Shapely.Polygon. Use for removing all the copper in a region
  1415. or bed flattening.
  1416. :param poly: Target polygon
  1417. :type poly: Shapely.Polygon
  1418. :param tooldia: Diameter of the tool
  1419. :type tooldia: float
  1420. :param overlap: Fraction of the tool diameter to overlap
  1421. in each pass.
  1422. :type overlap: float
  1423. :return: list of Shapely.Polygon
  1424. :rtype: list
  1425. """
  1426. poly_cuts = [poly.buffer(-tooldia/2.0)]
  1427. while True:
  1428. poly = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  1429. if poly.area > 0:
  1430. poly_cuts.append(poly)
  1431. else:
  1432. break
  1433. return poly_cuts
  1434. def find_polygon(poly_set, point):
  1435. """
  1436. Return the first polygon in the list of polygons poly_set
  1437. that contains the given point.
  1438. """
  1439. p = Point(point)
  1440. for poly in poly_set:
  1441. if poly.contains(p):
  1442. return poly
  1443. return None
  1444. def to_dict(geo):
  1445. output = ''
  1446. if isinstance(geo, BaseGeometry):
  1447. return {
  1448. "__class__": "Shply",
  1449. "__inst__": sdumps(geo)
  1450. }
  1451. return geo
  1452. def dict2obj(d):
  1453. if '__class__' in d and '__inst__' in d:
  1454. # For now assume all classes are Shapely geometry.
  1455. return sloads(d['__inst__'])
  1456. else:
  1457. return d
  1458. def plotg(geo):
  1459. try:
  1460. _ = iter(geo)
  1461. except:
  1462. geo = [geo]
  1463. for g in geo:
  1464. if type(g) == Polygon:
  1465. x, y = g.exterior.coords.xy
  1466. plot(x, y)
  1467. for ints in g.interiors:
  1468. x, y = ints.coords.xy
  1469. plot(x, y)
  1470. continue
  1471. if type(g) == LineString or type(g) == LinearRing:
  1472. x, y = g.coords.xy
  1473. plot(x, y)
  1474. continue
  1475. if type(g) == Point:
  1476. x, y = g.coords.xy
  1477. plot(x, y, 'o')
  1478. continue
  1479. try:
  1480. _ = iter(g)
  1481. plotg(g)
  1482. except:
  1483. print "Cannot plot:", str(type(g))
  1484. continue
  1485. def parse_gerber_number(strnumber, frac_digits):
  1486. """
  1487. Parse a single number of Gerber coordinates.
  1488. :param strnumber: String containing a number in decimal digits
  1489. from a coordinate data block, possibly with a leading sign.
  1490. :type strnumber: str
  1491. :param frac_digits: Number of digits used for the fractional
  1492. part of the number
  1493. :type frac_digits: int
  1494. :return: The number in floating point.
  1495. :rtype: float
  1496. """
  1497. return int(strnumber)*(10**(-frac_digits))
  1498. def parse_gerber_coords(gstr, int_digits, frac_digits):
  1499. """
  1500. Parse Gerber coordinates
  1501. :param gstr: Line of G-Code containing coordinates.
  1502. :type gstr: str
  1503. :param int_digits: Number of digits in integer part of a number.
  1504. :type int_digits: int
  1505. :param frac_digits: Number of digits in frac_digits part of a number.
  1506. :type frac_digits: int
  1507. :return: [x, y] coordinates.
  1508. :rtype: list
  1509. """
  1510. global gerbx, gerby
  1511. xindex = gstr.find("X")
  1512. yindex = gstr.find("Y")
  1513. index = gstr.find("D")
  1514. if xindex == -1:
  1515. x = gerbx
  1516. y = int(gstr[(yindex+1):index])*(10**(-frac_digits))
  1517. elif yindex == -1:
  1518. y = gerby
  1519. x = int(gstr[(xindex+1):index])*(10**(-frac_digits))
  1520. else:
  1521. x = int(gstr[(xindex+1):yindex])*(10**(-frac_digits))
  1522. y = int(gstr[(yindex+1):index])*(10**(-frac_digits))
  1523. gerbx = x
  1524. gerby = y
  1525. return [x, y]