camlib.py 62 KB

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