camlib.py 63 KB

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