camlib.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. ############################################################
  2. # Author: Juan Pablo Caram #
  3. # Date: 2/5/2014 #
  4. # caram.cl #
  5. ############################################################
  6. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos
  7. from matplotlib.figure import Figure
  8. import re
  9. # See: http://toblerity.org/shapely/manual.html
  10. from shapely.geometry import Polygon, LineString, Point, LinearRing
  11. from shapely.geometry import MultiPoint, MultiPolygon
  12. from shapely.geometry import box as shply_box
  13. from shapely.ops import cascaded_union
  14. import shapely.affinity as affinity
  15. from shapely.wkt import loads as sloads
  16. from shapely.wkt import dumps as sdumps
  17. from shapely.geometry.base import BaseGeometry
  18. # Used for solid polygons in Matplotlib
  19. from descartes.patch import PolygonPatch
  20. import simplejson as json
  21. from matplotlib.pyplot import plot
  22. class Geometry:
  23. def __init__(self):
  24. # Units (in or mm)
  25. self.units = 'in'
  26. # Final geometry: MultiPolygon
  27. self.solid_geometry = None
  28. # Attributes to be included in serialization
  29. self.ser_attrs = ['units', 'solid_geometry']
  30. def isolation_geometry(self, offset):
  31. """
  32. Creates contours around geometry at a given
  33. offset distance.
  34. """
  35. return self.solid_geometry.buffer(offset)
  36. def bounds(self):
  37. """
  38. Returns coordinates of rectangular bounds
  39. of geometry: (xmin, ymin, xmax, ymax).
  40. """
  41. if self.solid_geometry is None:
  42. print "Warning: solid_geometry not computed yet."
  43. return (0, 0, 0, 0)
  44. if type(self.solid_geometry) == list:
  45. # TODO: This can be done faster. See comment from Shapely mailing lists.
  46. return cascaded_union(self.solid_geometry).bounds
  47. else:
  48. return self.solid_geometry.bounds
  49. def size(self):
  50. """
  51. Returns (width, height) of rectangular
  52. bounds of geometry.
  53. """
  54. if self.solid_geometry is None:
  55. print "Warning: solid_geometry not computed yet."
  56. return 0
  57. bounds = self.bounds()
  58. return (bounds[2]-bounds[0], bounds[3]-bounds[1])
  59. def get_empty_area(self, boundary=None):
  60. """
  61. Returns the complement of self.solid_geometry within
  62. the given boundary polygon. If not specified, it defaults to
  63. the rectangular bounding box of self.solid_geometry.
  64. """
  65. if boundary is None:
  66. boundary = self.solid_geometry.envelope
  67. return boundary.difference(self.solid_geometry)
  68. def clear_polygon(self, polygon, tooldia, overlap=0.15):
  69. """
  70. Creates geometry inside a polygon for a tool to cover
  71. the whole area.
  72. """
  73. poly_cuts = [polygon.buffer(-tooldia/2.0)]
  74. while True:
  75. polygon = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  76. if polygon.area > 0:
  77. poly_cuts.append(polygon)
  78. else:
  79. break
  80. return poly_cuts
  81. def scale(self, factor):
  82. """
  83. Scales all of the object's geometry by a given factor. Override
  84. this method.
  85. :param factor: Number by which to scale.
  86. :type factor: float
  87. :return: None
  88. :rtype: None
  89. """
  90. return
  91. def convert_units(self, units):
  92. """
  93. Converts the units of the object to ``units`` by scaling all
  94. the geometry appropriately. This call ``scale()``. Don't call
  95. it again in descendents.
  96. :param units: "IN" or "MM"
  97. :type units: str
  98. :return: Scaling factor resulting from unit change.
  99. :rtype: float
  100. """
  101. print "Geometry.convert_units()"
  102. if units.upper() == self.units.upper():
  103. return 1.0
  104. if units.upper() == "MM":
  105. factor = 25.4
  106. elif units.upper() == "IN":
  107. factor = 1/25.4
  108. else:
  109. print "Unsupported units:", units
  110. return 1.0
  111. self.units = units
  112. self.scale(factor)
  113. return factor
  114. def to_dict(self):
  115. """
  116. Returns a respresentation of the object as a dictionary.
  117. Attributes to include are listed in ``self.ser_attrs``.
  118. :return: A dictionary-encoded copy of the object.
  119. :rtype: dict
  120. """
  121. d = {}
  122. for attr in self.ser_attrs:
  123. d[attr] = getattr(self, attr)
  124. return d
  125. def from_dict(self, d):
  126. """
  127. Sets object's attributes from a dictionary.
  128. Attributes to include are listed in ``self.ser_attrs``.
  129. """
  130. for attr in self.ser_attrs:
  131. setattr(self, attr, d[attr])
  132. class Gerber (Geometry):
  133. """
  134. **ATTRIBUTES**
  135. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  136. The values are dictionaries key/value pairs which describe the aperture. The
  137. type key is always present and the rest depend on the key:
  138. +-----------+-----------------------------------+
  139. | Key | Value |
  140. +===========+===================================+
  141. | type | (str) "C", "R", or "O" |
  142. +-----------+-----------------------------------+
  143. | others | Depend on ``type`` |
  144. +-----------+-----------------------------------+
  145. * ``paths`` (list): A path is described by a line an aperture that follows that
  146. line. Each paths[i] is a dictionary:
  147. +------------+------------------------------------------------+
  148. | Key | Value |
  149. +============+================================================+
  150. | linestring | (Shapely.LineString) The actual path. |
  151. +------------+------------------------------------------------+
  152. | aperture | (str) The key for an aperture in apertures. |
  153. +------------+------------------------------------------------+
  154. * ``flashes`` (list): Flashes are single-point strokes of an aperture. Each
  155. is a dictionary:
  156. +------------+------------------------------------------------+
  157. | Key | Value |
  158. +============+================================================+
  159. | loc | (list) [x (float), y (float)] coordinates. |
  160. +------------+------------------------------------------------+
  161. | aperture | (str) The key for an aperture in apertures. |
  162. +------------+------------------------------------------------+
  163. * ``regions`` (list): Are surfaces defined by a polygon (Shapely.Polygon),
  164. which have an exterior and zero or more interiors. An aperture is also
  165. associated with a region. Each is a dictionary:
  166. +------------+-----------------------------------------------------+
  167. | Key | Value |
  168. +============+=====================================================+
  169. | polygon | (Shapely.Polygon) The polygon defining the region. |
  170. +------------+-----------------------------------------------------+
  171. | aperture | (str) The key for an aperture in apertures. |
  172. +------------+-----------------------------------------------------+
  173. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  174. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  175. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  176. *buffering* (or thickening) the ``paths`` with the aperture. These are
  177. generated from ``paths`` in ``buffer_paths()``.
  178. **USAGE**
  179. """
  180. def __init__(self):
  181. """
  182. The constructor takes no parameters. Use ``gerber.parse_files()``
  183. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  184. :return: Gerber object
  185. :rtype: Gerber
  186. """
  187. # Initialize parent
  188. Geometry.__init__(self)
  189. # Number format
  190. self.digits = 3
  191. """Number of integer digits in Gerber numbers. Used during parsing."""
  192. self.fraction = 4
  193. """Number of fraction digits in Gerber numbers. Used during parsing."""
  194. ## Gerber elements ##
  195. # Apertures {'id':{'type':chr,
  196. # ['size':float], ['width':float],
  197. # ['height':float]}, ...}
  198. self.apertures = {}
  199. # Paths [{'linestring':LineString, 'aperture':str}]
  200. self.paths = []
  201. # Buffered Paths [Polygon]
  202. # Paths transformed into Polygons by
  203. # offsetting the aperture size/2
  204. self.buffered_paths = []
  205. # Polygon regions [{'polygon':Polygon, 'aperture':str}]
  206. self.regions = []
  207. # Flashes [{'loc':[float,float], 'aperture':str}]
  208. self.flashes = []
  209. # Geometry from flashes
  210. self.flash_geometry = []
  211. # Attributes to be included in serialization
  212. # Always append to it because it carries contents
  213. # from Geometry.
  214. self.ser_attrs += ['digits', 'fraction', 'apertures', 'paths',
  215. 'buffered_paths', 'regions', 'flashes',
  216. 'flash_geometry']
  217. def scale(self, factor):
  218. """
  219. Scales the objects' geometry on the XY plane by a given factor.
  220. These are:
  221. * ``apertures``
  222. * ``paths``
  223. * ``regions``
  224. * ``flashes``
  225. Then ``buffered_paths``, ``flash_geometry`` and ``solid_geometry``
  226. are re-created with ``self.create_geometry()``.
  227. :param factor: Number by which to scale.
  228. :type factor: float
  229. :rtype : None
  230. """
  231. # Apertures
  232. print "Scaling apertures..."
  233. for apid in self.apertures:
  234. for param in self.apertures[apid]:
  235. if param != "type": # All others are dimensions.
  236. print "Tool:", apid, "Parameter:", param
  237. self.apertures[apid][param] *= factor
  238. # Paths
  239. print "Scaling paths..."
  240. for path in self.paths:
  241. path['linestring'] = affinity.scale(path['linestring'],
  242. factor, factor, origin=(0, 0))
  243. # Flashes
  244. print "Scaling flashes..."
  245. for fl in self.flashes:
  246. # TODO: Shouldn't 'loc' be a numpy.array()?
  247. fl['loc'][0] *= factor
  248. fl['loc'][1] *= factor
  249. # Regions
  250. print "Scaling regions..."
  251. for reg in self.regions:
  252. reg['polygon'] = affinity.scale(reg['polygon'], factor, factor,
  253. origin=(0, 0))
  254. # Now buffered_paths, flash_geometry and solid_geometry
  255. self.create_geometry()
  256. def fix_regions(self):
  257. """
  258. Overwrites the region polygons with fixed
  259. versions if found to be invalid (according to Shapely).
  260. """
  261. for region in self.regions:
  262. if not region['polygon'].is_valid:
  263. region['polygon'] = region['polygon'].buffer(0)
  264. def buffer_paths(self):
  265. self.buffered_paths = []
  266. for path in self.paths:
  267. width = self.apertures[path["aperture"]]["size"]
  268. self.buffered_paths.append(path["linestring"].buffer(width/2))
  269. def aperture_parse(self, gline):
  270. """
  271. Parse gerber aperture definition into dictionary of apertures.
  272. The following kinds and their attributes are supported:
  273. * *Circular (C)*: size (float)
  274. * *Rectangle (R)*: width (float), height (float)
  275. * *Obround (O)*: width (float), height (float). NOTE: This can
  276. be parsed, but it is not supported further yet.
  277. """
  278. indexstar = gline.find("*")
  279. indexc = gline.find("C,")
  280. if indexc != -1: # Circle, example: %ADD11C,0.1*%
  281. apid = gline[4:indexc]
  282. self.apertures[apid] = {"type": "C",
  283. "size": float(gline[indexc+2:indexstar])}
  284. return apid
  285. indexr = gline.find("R,")
  286. if indexr != -1: # Rectangle, example: %ADD15R,0.05X0.12*%
  287. apid = gline[4:indexr]
  288. indexx = gline.find("X")
  289. self.apertures[apid] = {"type": "R",
  290. "width": float(gline[indexr+2:indexx]),
  291. "height": float(gline[indexx+1:indexstar])}
  292. return apid
  293. indexo = gline.find("O,")
  294. if indexo != -1: # Obround
  295. apid = gline[4:indexo]
  296. indexx = gline.find("X")
  297. self.apertures[apid] = {"type": "O",
  298. "width": float(gline[indexo+2:indexx]),
  299. "height": float(gline[indexx+1:indexstar])}
  300. return apid
  301. print "WARNING: Aperture not implemented:", gline
  302. return None
  303. def parse_file(self, filename):
  304. """
  305. Calls Gerber.parse_lines() with array of lines
  306. read from the given file.
  307. """
  308. gfile = open(filename, 'r')
  309. gstr = gfile.readlines()
  310. gfile.close()
  311. self.parse_lines(gstr)
  312. def parse_lines(self, glines):
  313. """
  314. Main Gerber parser.
  315. """
  316. # Mode (IN/MM)
  317. mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  318. path = [] # Coordinates of the current path
  319. last_path_aperture = None
  320. current_aperture = None
  321. for gline in glines:
  322. if gline.find("D01*") != -1: # pen down
  323. path.append(coord(gline, self.digits, self.fraction))
  324. last_path_aperture = current_aperture
  325. continue
  326. if gline.find("D02*") != -1: # pen up
  327. if len(path) > 1:
  328. # Path completed, create shapely LineString
  329. self.paths.append({"linestring": LineString(path),
  330. "aperture": last_path_aperture})
  331. path = [coord(gline, self.digits, self.fraction)]
  332. continue
  333. indexd3 = gline.find("D03*")
  334. if indexd3 > 0: # Flash
  335. self.flashes.append({"loc": coord(gline, self.digits, self.fraction),
  336. "aperture": current_aperture})
  337. continue
  338. if indexd3 == 0: # Flash?
  339. print "WARNING: Uninplemented flash style:", gline
  340. continue
  341. if gline.find("G37*") != -1: # end region
  342. # Only one path defines region?
  343. self.regions.append({"polygon": Polygon(path),
  344. "aperture": last_path_aperture})
  345. path = []
  346. continue
  347. if gline.find("%ADD") != -1: # aperture definition
  348. self.aperture_parse(gline) # adds element to apertures
  349. continue
  350. indexstar = gline.find("*")
  351. if gline.find("D") == 0: # Aperture change
  352. current_aperture = gline[1:indexstar]
  353. continue
  354. if gline.find("G54D") == 0: # Aperture change (deprecated)
  355. current_aperture = gline[4:indexstar]
  356. continue
  357. if gline.find("%FS") != -1: # Format statement
  358. indexx = gline.find("X")
  359. self.digits = int(gline[indexx + 1])
  360. self.fraction = int(gline[indexx + 2])
  361. continue
  362. # Mode (IN/MM)
  363. match = mode_re.search(gline)
  364. if match:
  365. self.units = match.group(1)
  366. continue
  367. print "WARNING: Line ignored:", gline
  368. if len(path) > 1:
  369. # EOF, create shapely LineString if something still in path
  370. self.paths.append({"linestring": LineString(path),
  371. "aperture": last_path_aperture})
  372. def do_flashes(self):
  373. """
  374. Creates geometry for Gerber flashes (aperture on a single point).
  375. """
  376. self.flash_geometry = []
  377. for flash in self.flashes:
  378. aperture = self.apertures[flash['aperture']]
  379. if aperture['type'] == 'C': # Circles
  380. circle = Point(flash['loc']).buffer(aperture['size']/2)
  381. self.flash_geometry.append(circle)
  382. continue
  383. if aperture['type'] == 'R': # Rectangles
  384. loc = flash['loc']
  385. width = aperture['width']
  386. height = aperture['height']
  387. minx = loc[0] - width/2
  388. maxx = loc[0] + width/2
  389. miny = loc[1] - height/2
  390. maxy = loc[1] + height/2
  391. rectangle = shply_box(minx, miny, maxx, maxy)
  392. self.flash_geometry.append(rectangle)
  393. continue
  394. #TODO: Add support for type='O'
  395. print "WARNING: Aperture type %s not implemented" % (aperture['type'])
  396. def create_geometry(self):
  397. """
  398. Geometry from a Gerber file is made up entirely of polygons.
  399. Every stroke (linear or circular) has an aperture which gives
  400. it thickness. Additionally, aperture strokes have non-zero area,
  401. and regions naturally do as well.
  402. :rtype : None
  403. :return: None
  404. """
  405. # if len(self.buffered_paths) == 0:
  406. # self.buffer_paths()
  407. self.buffer_paths()
  408. self.fix_regions()
  409. self.do_flashes()
  410. self.solid_geometry = cascaded_union(
  411. self.buffered_paths +
  412. [poly['polygon'] for poly in self.regions] +
  413. self.flash_geometry)
  414. def get_bounding_box(self, margin=0.0, rounded=False):
  415. """
  416. Creates and returns a rectangular polygon bounding at a distance of
  417. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  418. can optionally have rounded corners of radius equal to margin.
  419. :param margin: Distance to enlarge the rectangular bounding
  420. box in both positive and negative, x and y axes.
  421. :type margin: float
  422. :param rounded: Wether or not to have rounded corners.
  423. :type rounded: bool
  424. :return: The bounding box.
  425. :rtype: Shapely.Polygon
  426. """
  427. bbox = self.solid_geometry.envelope.buffer(margin)
  428. if not rounded:
  429. bbox = bbox.envelope
  430. return bbox
  431. class Excellon(Geometry):
  432. """
  433. *ATTRIBUTES*
  434. * ``tools`` (dict): The key is the tool name and the value is
  435. the size (diameter).
  436. * ``drills`` (list): Each is a dictionary:
  437. ================ ====================================
  438. Key Value
  439. ================ ====================================
  440. point (Shapely.Point) Where to drill
  441. tool (str) A key in ``tools``
  442. ================ ====================================
  443. """
  444. def __init__(self):
  445. """
  446. The constructor takes no parameters.
  447. :return: Excellon object.
  448. :rtype: Excellon
  449. """
  450. Geometry.__init__(self)
  451. self.tools = {}
  452. self.drills = []
  453. # Trailing "T" or leading "L"
  454. self.zeros = ""
  455. # Attributes to be included in serialization
  456. # Always append to it because it carries contents
  457. # from Geometry.
  458. self.ser_attrs += ['tools', 'drills', 'zeros']
  459. def parse_file(self, filename):
  460. efile = open(filename, 'r')
  461. estr = efile.readlines()
  462. efile.close()
  463. self.parse_lines(estr)
  464. def parse_lines(self, elines):
  465. """
  466. Main Excellon parser.
  467. """
  468. units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  469. current_tool = ""
  470. for eline in elines:
  471. ## Tool definitions ##
  472. # TODO: Verify all this
  473. indexT = eline.find("T")
  474. indexC = eline.find("C")
  475. indexF = eline.find("F")
  476. # Type 1
  477. if indexT != -1 and indexC > indexT and indexF > indexC:
  478. tool = eline[1:indexC]
  479. spec = eline[indexC+1:indexF]
  480. self.tools[tool] = float(spec)
  481. continue
  482. # Type 2
  483. # TODO: Is this inches?
  484. #indexsp = eline.find(" ")
  485. #indexin = eline.find("in")
  486. #if indexT != -1 and indexsp > indexT and indexin > indexsp:
  487. # tool = eline[1:indexsp]
  488. # spec = eline[indexsp+1:indexin]
  489. # self.tools[tool] = spec
  490. # continue
  491. # Type 3
  492. if indexT != -1 and indexC > indexT:
  493. tool = eline[1:indexC]
  494. spec = eline[indexC+1:-1]
  495. self.tools[tool] = float(spec)
  496. continue
  497. ## Tool change
  498. if indexT == 0:
  499. current_tool = eline[1:-1]
  500. continue
  501. ## Drill
  502. indexx = eline.find("X")
  503. indexy = eline.find("Y")
  504. if indexx != -1 and indexy != -1:
  505. x = float(int(eline[indexx+1:indexy])/10000.0)
  506. y = float(int(eline[indexy+1:-1])/10000.0)
  507. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  508. continue
  509. # Units and number format
  510. match = units_re.match(eline)
  511. if match:
  512. self.zeros = match.group(2) # "T" or "L"
  513. self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  514. print "WARNING: Line ignored:", eline
  515. def create_geometry(self):
  516. self.solid_geometry = []
  517. sizes = {}
  518. for tool in self.tools:
  519. sizes[tool] = float(self.tools[tool])
  520. for drill in self.drills:
  521. poly = Point(drill['point']).buffer(sizes[drill['tool']]/2.0)
  522. self.solid_geometry.append(poly)
  523. self.solid_geometry = cascaded_union(self.solid_geometry)
  524. def scale(self, factor):
  525. """
  526. Scales geometry on the XY plane in the object by a given factor.
  527. Tool sizes, feedrates an Z-plane dimensions are untouched.
  528. :param factor: Number by which to scale the object.
  529. :type factor: float
  530. :return: None
  531. :rtype: NOne
  532. """
  533. # Drills
  534. for drill in self.drills:
  535. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  536. def convert_units(self, units):
  537. factor = Geometry.convert_units(self, units)
  538. # Tools
  539. for tname in self.tools:
  540. self.tools[tname] *= factor
  541. return factor
  542. class CNCjob(Geometry):
  543. """
  544. Represents work to be done by a CNC machine.
  545. *ATTRIBUTES*
  546. * ``gcode_parsed`` (list): Each is a dictionary:
  547. ===================== =========================================
  548. Key Value
  549. ===================== =========================================
  550. geom (Shapely.LineString) Tool path (XY plane)
  551. kind (string) "AB", A is "T" (travel) or
  552. "C" (cut). B is "F" (fast) or "S" (slow).
  553. ===================== =========================================
  554. """
  555. def __init__(self, units="in", kind="generic", z_move=0.1,
  556. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  557. Geometry.__init__(self)
  558. self.kind = kind
  559. self.units = units
  560. self.z_cut = z_cut
  561. self.z_move = z_move
  562. self.feedrate = feedrate
  563. self.tooldia = tooldia
  564. self.unitcode = {"IN": "G20", "MM": "G21"}
  565. self.pausecode = "G04 P1"
  566. self.feedminutecode = "G94"
  567. self.absolutecode = "G90"
  568. self.gcode = ""
  569. self.input_geometry_bounds = None
  570. self.gcode_parsed = None
  571. self.steps_per_circ = 20 # Used when parsing G-code arcs
  572. # Attributes to be included in serialization
  573. # Always append to it because it carries contents
  574. # from Geometry.
  575. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  576. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  577. 'steps_per_circ']
  578. def convert_units(self, units):
  579. factor = Geometry.convert_units(self, units)
  580. print "CNCjob.convert_units()"
  581. self.z_cut *= factor
  582. self.z_move *= factor
  583. self.feedrate *= factor
  584. self.tooldia *= factor
  585. return factor
  586. def generate_from_excellon(self, exobj):
  587. """
  588. Generates G-code for drilling from Excellon object.
  589. self.gcode becomes a list, each element is a
  590. different job for each tool in the excellon code.
  591. """
  592. self.kind = "drill"
  593. self.gcode = []
  594. t = "G00 X%.4fY%.4f\n"
  595. down = "G01 Z%.4f\n" % self.z_cut
  596. up = "G01 Z%.4f\n" % self.z_move
  597. for tool in exobj.tools:
  598. points = []
  599. for drill in exobj.drill:
  600. if drill['tool'] == tool:
  601. points.append(drill['point'])
  602. gcode = self.unitcode[self.units.upper()] + "\n"
  603. gcode += self.absolutecode + "\n"
  604. gcode += self.feedminutecode + "\n"
  605. gcode += "F%.2f\n" % self.feedrate
  606. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  607. gcode += "M03\n" # Spindle start
  608. gcode += self.pausecode + "\n"
  609. for point in points:
  610. gcode += t % point
  611. gcode += down + up
  612. gcode += t % (0, 0)
  613. gcode += "M05\n" # Spindle stop
  614. self.gcode.append(gcode)
  615. def generate_from_excellon_by_tool(self, exobj, tools="all"):
  616. """
  617. Creates gcode for this object from an Excellon object
  618. for the specified tools.
  619. @param exobj: Excellon object to process
  620. @type exobj: Excellon
  621. @param tools: Comma separated tool names
  622. @type: tools: str
  623. @return: None
  624. """
  625. print "Creating CNC Job from Excellon..."
  626. if tools == "all":
  627. tools = [tool for tool in exobj.tools]
  628. else:
  629. tools = [x.strip() for x in tools.split(",")]
  630. tools = filter(lambda y: y in exobj.tools, tools)
  631. print "Tools are:", tools
  632. points = []
  633. for drill in exobj.drills:
  634. if drill['tool'] in tools:
  635. points.append(drill['point'])
  636. print "Found %d drills." % len(points)
  637. #self.kind = "drill"
  638. self.gcode = []
  639. t = "G00 X%.4fY%.4f\n"
  640. down = "G01 Z%.4f\n" % self.z_cut
  641. up = "G01 Z%.4f\n" % self.z_move
  642. gcode = self.unitcode[self.units.upper()] + "\n"
  643. gcode += self.absolutecode + "\n"
  644. gcode += self.feedminutecode + "\n"
  645. gcode += "F%.2f\n" % self.feedrate
  646. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  647. gcode += "M03\n" # Spindle start
  648. gcode += self.pausecode + "\n"
  649. for point in points:
  650. x, y = point.coords.xy
  651. gcode += t % (x[0], y[0])
  652. gcode += down + up
  653. gcode += t % (0, 0)
  654. gcode += "M05\n" # Spindle stop
  655. self.gcode = gcode
  656. def generate_from_geometry(self, geometry, append=True, tooldia=None):
  657. """
  658. Generates G-Code from a Geometry object.
  659. """
  660. if tooldia is not None:
  661. self.tooldia = tooldia
  662. self.input_geometry_bounds = geometry.bounds()
  663. if not append:
  664. self.gcode = ""
  665. self.gcode = self.unitcode[self.units.upper()] + "\n"
  666. self.gcode += self.absolutecode + "\n"
  667. self.gcode += self.feedminutecode + "\n"
  668. self.gcode += "F%.2f\n" % self.feedrate
  669. self.gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  670. self.gcode += "M03\n" # Spindle start
  671. self.gcode += self.pausecode + "\n"
  672. for geo in geometry.solid_geometry:
  673. if type(geo) == Polygon:
  674. self.gcode += self.polygon2gcode(geo)
  675. continue
  676. if type(geo) == LineString or type(geo) == LinearRing:
  677. self.gcode += self.linear2gcode(geo)
  678. continue
  679. if type(geo) == Point:
  680. self.gcode += self.point2gcode(geo)
  681. continue
  682. if type(geo) == MultiPolygon:
  683. for poly in geo:
  684. self.gcode += self.polygon2gcode(poly)
  685. continue
  686. print "WARNING: G-code generation not implemented for %s" % (str(type(geo)))
  687. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  688. self.gcode += "G00 X0Y0\n"
  689. self.gcode += "M05\n" # Spindle stop
  690. def pre_parse(self, gtext):
  691. """
  692. gtext is a single string with g-code
  693. """
  694. # Units: G20-inches, G21-mm
  695. units_re = re.compile(r'^G2([01])')
  696. # TODO: This has to be re-done
  697. gcmds = []
  698. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  699. for line in lines:
  700. # Clean up
  701. line = line.strip()
  702. # Remove comments
  703. # NOTE: Limited to 1 bracket pair
  704. op = line.find("(")
  705. cl = line.find(")")
  706. if op > -1 and cl > op:
  707. #comment = line[op+1:cl]
  708. line = line[:op] + line[(cl+1):]
  709. # Units
  710. match = units_re.match(line)
  711. if match:
  712. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  713. # Parse GCode
  714. # 0 4 12
  715. # G01 X-0.007 Y-0.057
  716. # --> codes_idx = [0, 4, 12]
  717. codes = "NMGXYZIJFP"
  718. codes_idx = []
  719. i = 0
  720. for ch in line:
  721. if ch in codes:
  722. codes_idx.append(i)
  723. i += 1
  724. n_codes = len(codes_idx)
  725. if n_codes == 0:
  726. continue
  727. # Separate codes in line
  728. parts = []
  729. for p in range(n_codes-1):
  730. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  731. parts.append(line[codes_idx[-1]:].strip())
  732. # Separate codes from values
  733. cmds = {}
  734. for part in parts:
  735. cmds[part[0]] = float(part[1:])
  736. gcmds.append(cmds)
  737. return gcmds
  738. def gcode_parse(self):
  739. """
  740. G-Code parser (from self.gcode). Generates dictionary with
  741. single-segment LineString's and "kind" indicating cut or travel,
  742. fast or feedrate speed.
  743. """
  744. # Results go here
  745. geometry = []
  746. # TODO: Merge into single parser?
  747. gobjs = self.pre_parse(self.gcode)
  748. # Last known instruction
  749. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  750. # Process every instruction
  751. for gobj in gobjs:
  752. if 'Z' in gobj:
  753. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  754. print "WARNING: Non-orthogonal motion: From", current
  755. print " To:", gobj
  756. current['Z'] = gobj['Z']
  757. if 'G' in gobj:
  758. current['G'] = int(gobj['G'])
  759. if 'X' in gobj or 'Y' in gobj:
  760. x = 0
  761. y = 0
  762. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  763. if 'X' in gobj:
  764. x = gobj['X']
  765. else:
  766. x = current['X']
  767. if 'Y' in gobj:
  768. y = gobj['Y']
  769. else:
  770. y = current['Y']
  771. if current['Z'] > 0:
  772. kind[0] = 'T'
  773. if current['G'] > 0:
  774. kind[1] = 'S'
  775. arcdir = [None, None, "cw", "ccw"]
  776. if current['G'] in [0, 1]: # line
  777. geometry.append({'geom': LineString([(current['X'], current['Y']),
  778. (x, y)]), 'kind': kind})
  779. if current['G'] in [2, 3]: # arc
  780. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  781. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  782. start = arctan2(-gobj['J'], -gobj['I'])
  783. stop = arctan2(-center[1]+y, -center[0]+x)
  784. geometry.append({'geom': arc(center, radius, start, stop,
  785. arcdir[current['G']],
  786. self.steps_per_circ),
  787. 'kind': kind})
  788. # Update current instruction
  789. for code in gobj:
  790. current[code] = gobj[code]
  791. #self.G_geometry = geometry
  792. self.gcode_parsed = geometry
  793. return geometry
  794. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  795. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  796. # alpha={"T": 0.3, "C": 1.0}):
  797. # """
  798. # Creates a Matplotlib figure with a plot of the
  799. # G-code job.
  800. # """
  801. # if tooldia is None:
  802. # tooldia = self.tooldia
  803. #
  804. # fig = Figure(dpi=dpi)
  805. # ax = fig.add_subplot(111)
  806. # ax.set_aspect(1)
  807. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  808. # ax.set_xlim(xmin-margin, xmax+margin)
  809. # ax.set_ylim(ymin-margin, ymax+margin)
  810. #
  811. # if tooldia == 0:
  812. # for geo in self.gcode_parsed:
  813. # linespec = '--'
  814. # linecolor = color[geo['kind'][0]][1]
  815. # if geo['kind'][0] == 'C':
  816. # linespec = 'k-'
  817. # x, y = geo['geom'].coords.xy
  818. # ax.plot(x, y, linespec, color=linecolor)
  819. # else:
  820. # for geo in self.gcode_parsed:
  821. # poly = geo['geom'].buffer(tooldia/2.0)
  822. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  823. # edgecolor=color[geo['kind'][0]][1],
  824. # alpha=alpha[geo['kind'][0]], zorder=2)
  825. # ax.add_patch(patch)
  826. #
  827. # return fig
  828. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  829. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  830. alpha={"T": 0.3, "C": 1.0}):
  831. """
  832. Plots the G-code job onto the given axes.
  833. """
  834. if tooldia is None:
  835. tooldia = self.tooldia
  836. if tooldia == 0:
  837. for geo in self.gcode_parsed:
  838. linespec = '--'
  839. linecolor = color[geo['kind'][0]][1]
  840. if geo['kind'][0] == 'C':
  841. linespec = 'k-'
  842. x, y = geo['geom'].coords.xy
  843. axes.plot(x, y, linespec, color=linecolor)
  844. else:
  845. for geo in self.gcode_parsed:
  846. poly = geo['geom'].buffer(tooldia/2.0)
  847. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  848. edgecolor=color[geo['kind'][0]][1],
  849. alpha=alpha[geo['kind'][0]], zorder=2)
  850. axes.add_patch(patch)
  851. def create_geometry(self):
  852. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  853. def polygon2gcode(self, polygon):
  854. """
  855. Creates G-Code for the exterior and all interior paths
  856. of a polygon.
  857. :param polygon: A Shapely.Polygon
  858. :type polygon: Shapely.Polygon
  859. """
  860. gcode = ""
  861. t = "G0%d X%.4fY%.4f\n"
  862. path = list(polygon.exterior.coords) # Polygon exterior
  863. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  864. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  865. for pt in path[1:]:
  866. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  867. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  868. for ints in polygon.interiors: # Polygon interiors
  869. path = list(ints.coords)
  870. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  871. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  872. for pt in path[1:]:
  873. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  874. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  875. return gcode
  876. def linear2gcode(self, linear):
  877. gcode = ""
  878. t = "G0%d X%.4fY%.4f\n"
  879. path = list(linear.coords)
  880. gcode += t%(0, path[0][0], path[0][1]) # Move to first point
  881. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  882. for pt in path[1:]:
  883. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  884. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  885. return gcode
  886. def point2gcode(self, point):
  887. # TODO: This is not doing anything.
  888. gcode = ""
  889. t = "G0%d X%.4fY%.4f\n"
  890. path = list(point.coords)
  891. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  892. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  893. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  894. def scale(self, factor):
  895. """
  896. Scales all the geometry on the XY plane in the object by the
  897. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  898. not altered.
  899. :param factor: Number by which to scale the object.
  900. :type factor: float
  901. :return: None
  902. :rtype: None
  903. """
  904. for g in self.gcode_parsed:
  905. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  906. self.create_geometry()
  907. def get_bounds(geometry_set):
  908. xmin = Inf
  909. ymin = Inf
  910. xmax = -Inf
  911. ymax = -Inf
  912. print "Getting bounds of:", str(geometry_set)
  913. for gs in geometry_set:
  914. try:
  915. gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  916. xmin = min([xmin, gxmin])
  917. ymin = min([ymin, gymin])
  918. xmax = max([xmax, gxmax])
  919. ymax = max([ymax, gymax])
  920. except:
  921. print "DEV WARNING: Tried to get bounds of empty geometry."
  922. return [xmin, ymin, xmax, ymax]
  923. def arc(center, radius, start, stop, direction, steps_per_circ):
  924. """
  925. Creates a Shapely.LineString for the specified arc.
  926. @param center: Coordinates of the center [x, y]
  927. @type center: list
  928. @param radius: Radius of the arc.
  929. @type radius: float
  930. @param start: Starting angle in radians
  931. @type start: float
  932. @param stop: End angle in radians
  933. @type stop: float
  934. @param direction: Orientation of the arc, "CW" or "CCW"
  935. @type direction: string
  936. @param steps_per_circ: Number of straight line segments to
  937. represent a circle.
  938. @type steps_per_circ: int
  939. """
  940. da_sign = {"cw": -1.0, "ccw": 1.0}
  941. points = []
  942. if direction == "ccw" and stop <= start:
  943. stop += 2*pi
  944. if direction == "cw" and stop >= start:
  945. stop -= 2*pi
  946. angle = abs(stop - start)
  947. #angle = stop-start
  948. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  949. delta_angle = da_sign[direction]*angle*1.0/steps
  950. for i in range(steps+1):
  951. theta = start + delta_angle*i
  952. points.append([center[0]+radius*cos(theta), center[1]+radius*sin(theta)])
  953. return LineString(points)
  954. def clear_poly(poly, tooldia, overlap=0.1):
  955. """
  956. Creates a list of Shapely geometry objects covering the inside
  957. of a Shapely.Polygon. Use for removing all the copper in a region
  958. or bed flattening.
  959. @param poly: Target polygon
  960. @type poly: Shapely.Polygon
  961. @param tooldia: Diameter of the tool
  962. @type tooldia: float
  963. @param overlap: Fraction of the tool diameter to overlap
  964. in each pass.
  965. @type overlap: float
  966. @return list of Shapely.Polygon
  967. """
  968. poly_cuts = [poly.buffer(-tooldia/2.0)]
  969. while True:
  970. poly = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  971. if poly.area > 0:
  972. poly_cuts.append(poly)
  973. else:
  974. break
  975. return poly_cuts
  976. def find_polygon(poly_set, point):
  977. """
  978. Return the first polygon in the list of polygons poly_set
  979. that contains the given point.
  980. """
  981. p = Point(point)
  982. for poly in poly_set:
  983. if poly.contains(p):
  984. return poly
  985. return None
  986. def to_dict(geo):
  987. output = ''
  988. if isinstance(geo, BaseGeometry):
  989. return {
  990. "__class__": "Shply",
  991. "__inst__": sdumps(geo)
  992. }
  993. return geo
  994. def dict2obj(d):
  995. if '__class__' in d and '__inst__' in d:
  996. # For now assume all classes are Shapely geometry.
  997. return sloads(d['__inst__'])
  998. else:
  999. return d
  1000. def plotg(geo):
  1001. try:
  1002. _ = iter(geo)
  1003. except:
  1004. geo = [geo]
  1005. for g in geo:
  1006. if type(g) == Polygon:
  1007. x, y = g.exterior.coords.xy
  1008. plot(x, y)
  1009. for ints in g.interiors:
  1010. x, y = ints.coords.xy
  1011. plot(x, y)
  1012. continue
  1013. if type(g) == LineString or type(g) == LinearRing:
  1014. x, y = g.coords.xy
  1015. plot(x, y)
  1016. continue
  1017. if type(g) == Point:
  1018. x, y = g.coords.xy
  1019. plot(x, y, 'o')
  1020. continue
  1021. try:
  1022. _ = iter(g)
  1023. plotg(g)
  1024. except:
  1025. print "Cannot plot:", str(type(g))
  1026. continue
  1027. ############### cam.py ####################
  1028. def coord(gstr, digits, fraction):
  1029. """
  1030. Parse Gerber coordinates
  1031. """
  1032. global gerbx, gerby
  1033. xindex = gstr.find("X")
  1034. yindex = gstr.find("Y")
  1035. index = gstr.find("D")
  1036. if xindex == -1:
  1037. x = gerbx
  1038. y = int(gstr[(yindex+1):index])*(10**(-fraction))
  1039. elif yindex == -1:
  1040. y = gerby
  1041. x = int(gstr[(xindex+1):index])*(10**(-fraction))
  1042. else:
  1043. x = int(gstr[(xindex+1):yindex])*(10**(-fraction))
  1044. y = int(gstr[(yindex+1):index])*(10**(-fraction))
  1045. gerbx = x
  1046. gerby = y
  1047. return [x, y]
  1048. ################ end of cam.py #############