camlib.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos
  2. from matplotlib.figure import Figure
  3. # See: http://toblerity.org/shapely/manual.html
  4. from shapely.geometry import Polygon, LineString, Point, LinearRing
  5. from shapely.geometry import MultiPoint, MultiPolygon
  6. from shapely.geometry import box as shply_box
  7. from shapely.ops import cascaded_union
  8. # Used for solid polygons in Matplotlib
  9. from descartes.patch import PolygonPatch
  10. class Geometry:
  11. def __init__(self):
  12. # Units (in or mm)
  13. self.units = 'in'
  14. # Final geometry: MultiPolygon
  15. self.solid_geometry = None
  16. def isolation_geometry(self, offset):
  17. """
  18. Creates contours around geometry at a given
  19. offset distance.
  20. """
  21. return self.solid_geometry.buffer(offset)
  22. def bounds(self):
  23. """
  24. Returns coordinates of rectangular bounds
  25. of geometry: (xmin, ymin, xmax, ymax).
  26. """
  27. if self.solid_geometry is None:
  28. print "Warning: solid_geometry not computed yet."
  29. return (0, 0, 0, 0)
  30. if type(self.solid_geometry) == list:
  31. return cascaded_union(self.solid_geometry).bounds
  32. else:
  33. return self.solid_geometry.bounds
  34. def size(self):
  35. """
  36. Returns (width, height) of rectangular
  37. bounds of geometry.
  38. """
  39. if self.solid_geometry is None:
  40. print "Warning: solid_geometry not computed yet."
  41. return 0
  42. bounds = self.bounds()
  43. return (bounds[2]-bounds[0], bounds[3]-bounds[1])
  44. def get_empty_area(self, boundary=None):
  45. """
  46. Returns the complement of self.solid_geometry within
  47. the given boundary polygon. If not specified, it defaults to
  48. the rectangular bounding box of self.solid_geometry.
  49. """
  50. if boundary is None:
  51. boundary = self.solid_geometry.envelope
  52. return boundary.difference(self.solid_geometry)
  53. def clear_polygon(self, polygon, tooldia, overlap=0.15):
  54. """
  55. Creates geometry inside a polygon for a tool to cover
  56. the whole area.
  57. """
  58. poly_cuts = [polygon.buffer(-tooldia/2.0)]
  59. while True:
  60. polygon = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  61. if polygon.area > 0:
  62. poly_cuts.append(polygon)
  63. else:
  64. break
  65. return poly_cuts
  66. class Gerber (Geometry):
  67. def __init__(self):
  68. # Initialize parent
  69. Geometry.__init__(self)
  70. # Number format
  71. self.digits = 3
  72. self.fraction = 4
  73. ## Gerber elements ##
  74. # Apertures {'id':{'type':chr,
  75. # ['size':float], ['width':float],
  76. # ['height':float]}, ...}
  77. self.apertures = {}
  78. # Paths [{'linestring':LineString, 'aperture':dict}]
  79. self.paths = []
  80. # Buffered Paths [Polygon]
  81. # Paths transformed into Polygons by
  82. # offsetting the aperture size/2
  83. self.buffered_paths = []
  84. # Polygon regions [{'polygon':Polygon, 'aperture':dict}]
  85. self.regions = []
  86. # Flashes [{'loc':[float,float], 'aperture':dict}]
  87. self.flashes = []
  88. # Geometry from flashes
  89. self.flash_geometry = []
  90. def fix_regions(self):
  91. """
  92. Overwrites the region polygons with fixed
  93. versions if found to be invalid (according to Shapely).
  94. """
  95. for region in self.regions:
  96. if not region['polygon'].is_valid:
  97. region['polygon'] = region['polygon'].buffer(0)
  98. def buffer_paths(self):
  99. self.buffered_paths = []
  100. for path in self.paths:
  101. width = self.apertures[path["aperture"]]["size"]
  102. self.buffered_paths.append(path["linestring"].buffer(width/2))
  103. def aperture_parse(self, gline):
  104. """
  105. Parse gerber aperture definition
  106. into dictionary of apertures.
  107. """
  108. indexstar = gline.find("*")
  109. indexC = gline.find("C,")
  110. if indexC != -1: # Circle, example: %ADD11C,0.1*%
  111. apid = gline[4:indexC]
  112. self.apertures[apid] = {"type": "C",
  113. "size": float(gline[indexC+2:indexstar])}
  114. return apid
  115. indexR = gline.find("R,")
  116. if indexR != -1: # Rectangle, example: %ADD15R,0.05X0.12*%
  117. apid = gline[4:indexR]
  118. indexX = gline.find("X")
  119. self.apertures[apid] = {"type": "R",
  120. "width": float(gline[indexR+2:indexX]),
  121. "height": float(gline[indexX+1:indexstar])}
  122. return apid
  123. indexO = gline.find("O,")
  124. if indexO != -1: # Obround
  125. apid = gline[4:indexO]
  126. indexX = gline.find("X")
  127. self.apertures[apid] = {"type": "O",
  128. "width": float(gline[indexO+2:indexX]),
  129. "height": float(gline[indexX+1:indexstar])}
  130. return apid
  131. print "WARNING: Aperture not implemented:", gline
  132. return None
  133. def parse_file(self, filename):
  134. """
  135. Calls Gerber.parse_lines() with array of lines
  136. read from the given file.
  137. """
  138. gfile = open(filename, 'r')
  139. gstr = gfile.readlines()
  140. gfile.close()
  141. self.parse_lines(gstr)
  142. def parse_lines(self, glines):
  143. """
  144. Main Gerber parser.
  145. """
  146. path = [] # Coordinates of the current path
  147. last_path_aperture = None
  148. current_aperture = None
  149. for gline in glines:
  150. if gline.find("D01*") != -1: # pen down
  151. path.append(coord(gline, self.digits, self.fraction))
  152. last_path_aperture = current_aperture
  153. continue
  154. if gline.find("D02*") != -1: # pen up
  155. if len(path) > 1:
  156. # Path completed, create shapely LineString
  157. self.paths.append({"linestring": LineString(path),
  158. "aperture": last_path_aperture})
  159. path = [coord(gline, self.digits, self.fraction)]
  160. continue
  161. indexD3 = gline.find("D03*")
  162. if indexD3 > 0: # Flash
  163. self.flashes.append({"loc": coord(gline, self.digits, self.fraction),
  164. "aperture": current_aperture})
  165. continue
  166. if indexD3 == 0: # Flash?
  167. print "WARNING: Uninplemented flash style:", gline
  168. continue
  169. if gline.find("G37*") != -1: # end region
  170. # Only one path defines region?
  171. self.regions.append({"polygon": Polygon(path),
  172. "aperture": last_path_aperture})
  173. path = []
  174. continue
  175. if gline.find("%ADD") != -1: # aperture definition
  176. self.aperture_parse(gline) # adds element to apertures
  177. continue
  178. indexstar = gline.find("*")
  179. if gline.find("D") == 0: # Aperture change
  180. current_aperture = gline[1:indexstar]
  181. continue
  182. if gline.find("G54D") == 0: # Aperture change (deprecated)
  183. current_aperture = gline[4:indexstar]
  184. continue
  185. if gline.find("%FS") != -1: # Format statement
  186. indexX = gline.find("X")
  187. self.digits = int(gline[indexX + 1])
  188. self.fraction = int(gline[indexX + 2])
  189. continue
  190. print "WARNING: Line ignored:", gline
  191. if len(path) > 1:
  192. # EOF, create shapely LineString if something in path
  193. self.paths.append({"linestring":LineString(path),
  194. "aperture":last_path_aperture})
  195. def do_flashes(self):
  196. """
  197. Creates geometry for Gerber flashes (aperture on a single point).
  198. """
  199. self.flash_geometry = []
  200. for flash in self.flashes:
  201. aperture = self.apertures[flash['aperture']]
  202. if aperture['type'] == 'C': # Circles
  203. circle = Point(flash['loc']).buffer(aperture['size']/2)
  204. self.flash_geometry.append(circle)
  205. continue
  206. if aperture['type'] == 'R': # Rectangles
  207. loc = flash['loc']
  208. width = aperture['width']
  209. height = aperture['height']
  210. minx = loc[0] - width/2
  211. maxx = loc[0] + width/2
  212. miny = loc[1] - height/2
  213. maxy = loc[1] + height/2
  214. rectangle = shply_box(minx, miny, maxx, maxy)
  215. self.flash_geometry.append(rectangle)
  216. continue
  217. #TODO: Add support for type='O'
  218. print "WARNING: Aperture type %s not implemented"%(aperture['type'])
  219. def create_geometry(self):
  220. if len(self.buffered_paths) == 0:
  221. self.buffer_paths()
  222. self.fix_regions()
  223. self.do_flashes()
  224. self.solid_geometry = cascaded_union(
  225. self.buffered_paths +
  226. [poly['polygon'] for poly in self.regions] +
  227. self.flash_geometry)
  228. class Excellon(Geometry):
  229. def __init__(self):
  230. Geometry.__init__(self)
  231. self.tools = {}
  232. self.drills = []
  233. def parse_file(self, filename):
  234. efile = open(filename, 'r')
  235. estr = efile.readlines()
  236. efile.close()
  237. self.parse_lines(estr)
  238. def parse_lines(self, elines):
  239. """
  240. Main Excellon parser.
  241. """
  242. current_tool = ""
  243. for eline in elines:
  244. ## Tool definitions ##
  245. # TODO: Verify all this
  246. indexT = eline.find("T")
  247. indexC = eline.find("C")
  248. indexF = eline.find("F")
  249. # Type 1
  250. if indexT != -1 and indexC > indexT and indexF > indexF:
  251. tool = eline[1:indexC]
  252. spec = eline[indexC+1:indexF]
  253. self.tools[tool] = spec
  254. continue
  255. # Type 2
  256. # TODO: Is this inches?
  257. #indexsp = eline.find(" ")
  258. #indexin = eline.find("in")
  259. #if indexT != -1 and indexsp > indexT and indexin > indexsp:
  260. # tool = eline[1:indexsp]
  261. # spec = eline[indexsp+1:indexin]
  262. # self.tools[tool] = spec
  263. # continue
  264. # Type 3
  265. if indexT != -1 and indexC > indexT:
  266. tool = eline[1:indexC]
  267. spec = eline[indexC+1:-1]
  268. self.tools[tool] = spec
  269. continue
  270. ## Tool change
  271. if indexT == 0:
  272. current_tool = eline[1:-1]
  273. continue
  274. ## Drill
  275. indexX = eline.find("X")
  276. indexY = eline.find("Y")
  277. if indexX != -1 and indexY != -1:
  278. x = float(int(eline[indexX+1:indexY])/10000.0)
  279. y = float(int(eline[indexY+1:-1])/10000.0)
  280. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  281. continue
  282. print "WARNING: Line ignored:", eline
  283. def create_geometry(self):
  284. self.solid_geometry = []
  285. sizes = {}
  286. for tool in self.tools:
  287. sizes[tool] = float(self.tools[tool])
  288. for drill in self.drills:
  289. poly = Point(drill['point']).buffer(sizes[drill['tool']]/2.0)
  290. self.solid_geometry.append(poly)
  291. self.solid_geometry = cascaded_union(self.solid_geometry)
  292. class CNCjob(Geometry):
  293. def __init__(self, units="in", kind="generic", z_move=0.1,
  294. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  295. # Options
  296. self.kind = kind
  297. self.units = units
  298. self.z_cut = z_cut
  299. self.z_move = z_move
  300. self.feedrate = feedrate
  301. self.tooldia = tooldia
  302. # Constants
  303. self.unitcode = {"in": "G20", "mm": "G21"}
  304. self.pausecode = "G04 P1"
  305. self.feedminutecode = "G94"
  306. self.absolutecode = "G90"
  307. # Input/Output G-Code
  308. self.gcode = ""
  309. # Bounds of geometry given to CNCjob.generate_from_geometry()
  310. self.input_geometry_bounds = None
  311. # Output generated by CNCjob.create_gcode_geometry()
  312. #self.G_geometry = None
  313. self.gcode_parsed = None
  314. def generate_from_excellon(self, exobj):
  315. """
  316. Generates G-code for drilling from excellon text.
  317. self.gcode becomes a list, each element is a
  318. different job for each tool in the excellon code.
  319. """
  320. self.kind = "drill"
  321. self.gcode = []
  322. t = "G00 X%.4fY%.4f\n"
  323. down = "G01 Z%.4f\n"%self.z_cut
  324. up = "G01 Z%.4f\n"%self.z_move
  325. for tool in exobj.tools:
  326. points = []
  327. gcode = ""
  328. for drill in exobj.drill:
  329. if drill['tool'] == tool:
  330. points.append(drill['point'])
  331. gcode = self.unitcode[self.units] + "\n"
  332. gcode += self.absolutecode + "\n"
  333. gcode += self.feedminutecode + "\n"
  334. gcode += "F%.2f\n"%self.feedrate
  335. gcode += "G00 Z%.4f\n"%self.z_move # Move to travel height
  336. gcode += "M03\n" # Spindle start
  337. gcode += self.pausecode + "\n"
  338. for point in points:
  339. gcode += t%point
  340. gcode += down + up
  341. gcode += t%(0, 0)
  342. gcode += "M05\n" # Spindle stop
  343. self.gcode.append(gcode)
  344. def generate_from_geometry(self, geometry, append=True, tooldia=None):
  345. """
  346. Generates G-Code for geometry (Shapely collection).
  347. """
  348. if tooldia is None:
  349. tooldia = self.tooldia
  350. else:
  351. self.tooldia = tooldia
  352. self.input_geometry_bounds = geometry.bounds
  353. if not append:
  354. self.gcode = ""
  355. t = "G0%d X%.4fY%.4f\n"
  356. self.gcode = self.unitcode[self.units] + "\n"
  357. self.gcode += self.absolutecode + "\n"
  358. self.gcode += self.feedminutecode + "\n"
  359. self.gcode += "F%.2f\n"%self.feedrate
  360. self.gcode += "G00 Z%.4f\n"%self.z_move # Move to travel height
  361. self.gcode += "M03\n" # Spindle start
  362. self.gcode += self.pausecode + "\n"
  363. for geo in geometry:
  364. if type(geo) == Polygon:
  365. path = list(geo.exterior.coords) # Polygon exterior
  366. self.gcode += t%(0, path[0][0], path[0][1]) # Move to first point
  367. self.gcode += "G01 Z%.4f\n"%self.z_cut # Start cutting
  368. for pt in path[1:]:
  369. self.gcode += t%(1, pt[0], pt[1]) # Linear motion to point
  370. self.gcode += "G00 Z%.4f\n"%self.z_move # Stop cutting
  371. for ints in geo.interiors: # Polygon interiors
  372. path = list(ints.coords)
  373. self.gcode += t%(0, path[0][0], path[0][1]) # Move to first point
  374. self.gcode += "G01 Z%.4f\n"%self.z_cut # Start cutting
  375. for pt in path[1:]:
  376. self.gcode += t%(1, pt[0], pt[1]) # Linear motion to point
  377. self.gcode += "G00 Z%.4f\n"%self.z_move # Stop cutting
  378. continue
  379. if type(geo) == LineString or type(geo) == LinearRing:
  380. path = list(geo.coords)
  381. self.gcode += t%(0, path[0][0], path[0][1]) # Move to first point
  382. self.gcode += "G01 Z%.4f\n"%self.z_cut # Start cutting
  383. for pt in path[1:]:
  384. self.gcode += t%(1, pt[0], pt[1]) # Linear motion to point
  385. self.gcode += "G00 Z%.4f\n"%self.z_move # Stop cutting
  386. continue
  387. if type(geo) == Point:
  388. path = list(geo.coords)
  389. self.gcode += t%(0, path[0][0], path[0][1]) # Move to first point
  390. self.gcode += "G01 Z%.4f\n"%self.z_cut # Start cutting
  391. self.gcode += "G00 Z%.4f\n"%self.z_move # Stop cutting
  392. continue
  393. print "WARNING: G-code generation not implemented for %s"%(str(type(geo)))
  394. self.gcode += "G00 Z%.4f\n"%self.z_move # Stop cutting
  395. self.gcode += "G00 X0Y0\n"
  396. self.gcode += "M05\n" # Spindle stop
  397. def gcode_parse(self):
  398. """
  399. G-Code parser (from self.gcode). Generates dictionary with
  400. single-segment LineString's and "kind" indicating cut or travel,
  401. fast or feedrate speed.
  402. """
  403. steps_per_circ = 20
  404. geometry = []
  405. # TODO: ???? bring this into the class??
  406. gobjs = gparse1b(self.gcode)
  407. # Last known instruction
  408. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  409. # Process every instruction
  410. for gobj in gobjs:
  411. if 'Z' in gobj:
  412. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  413. print "WARNING: Non-orthogonal motion: From", current
  414. print " To:", gobj
  415. current['Z'] = gobj['Z']
  416. if 'G' in gobj:
  417. current['G'] = int(gobj['G'])
  418. if 'X' in gobj or 'Y' in gobj:
  419. x = 0
  420. y = 0
  421. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  422. if 'X' in gobj:
  423. x = gobj['X']
  424. else:
  425. x = current['X']
  426. if 'Y' in gobj:
  427. y = gobj['Y']
  428. else:
  429. y = current['Y']
  430. if current['Z'] > 0:
  431. kind[0] = 'T'
  432. if current['G'] > 0:
  433. kind[1] = 'S'
  434. arcdir = [None, None, "cw", "ccw"]
  435. if current['G'] in [0, 1]: # line
  436. geometry.append({'geom': LineString([(current['X'], current['Y']),
  437. (x, y)]), 'kind': kind})
  438. if current['G'] in [2, 3]: # arc
  439. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  440. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  441. start = arctan2( -gobj['J'], -gobj['I'])
  442. stop = arctan2(-center[1]+y, -center[0]+x)
  443. geometry.append({'geom': arc(center, radius, start, stop,
  444. arcdir[current['G']],
  445. steps_per_circ),
  446. 'kind': kind})
  447. # Update current instruction
  448. for code in gobj:
  449. current[code] = gobj[code]
  450. #self.G_geometry = geometry
  451. self.gcode_parsed = geometry
  452. return geometry
  453. def plot(self, tooldia=None, dpi=75, margin=0.1,
  454. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  455. alpha={"T": 0.3, "C": 1.0}):
  456. """
  457. Creates a Matplotlib figure with a plot of the
  458. G-code job.
  459. """
  460. if tooldia is None:
  461. tooldia = self.tooldia
  462. fig = Figure(dpi=dpi)
  463. ax = fig.add_subplot(111)
  464. ax.set_aspect(1)
  465. xmin, ymin, xmax, ymax = self.input_geometry_bounds
  466. ax.set_xlim(xmin-margin, xmax+margin)
  467. ax.set_ylim(ymin-margin, ymax+margin)
  468. if tooldia == 0:
  469. for geo in self.gcode_parsed:
  470. linespec = '--'
  471. linecolor = color[geo['kind'][0]][1]
  472. if geo['kind'][0] == 'C':
  473. linespec = 'k-'
  474. x, y = geo['geom'].coords.xy
  475. ax.plot(x, y, linespec, color=linecolor)
  476. else:
  477. for geo in self.gcode_parsed:
  478. poly = geo['geom'].buffer(tooldia/2.0)
  479. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  480. edgecolor=color[geo['kind'][0]][1],
  481. alpha=alpha[geo['kind'][0]], zorder=2)
  482. ax.add_patch(patch)
  483. return fig
  484. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  485. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  486. alpha={"T": 0.3, "C":1.0}):
  487. """
  488. Plots the G-code job onto the given axes.
  489. """
  490. if tooldia is None:
  491. tooldia = self.tooldia
  492. if tooldia == 0:
  493. for geo in self.gcode_parsed:
  494. linespec = '--'
  495. linecolor = color[geo['kind'][0]][1]
  496. if geo['kind'][0] == 'C':
  497. linespec = 'k-'
  498. x, y = geo['geom'].coords.xy
  499. axes.plot(x, y, linespec, color=linecolor)
  500. else:
  501. for geo in self.gcode_parsed:
  502. poly = geo['geom'].buffer(tooldia/2.0)
  503. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  504. edgecolor=color[geo['kind'][0]][1],
  505. alpha=alpha[geo['kind'][0]], zorder=2)
  506. axes.add_patch(patch)
  507. def create_geometry(self):
  508. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  509. def gparse1b(gtext):
  510. """
  511. gtext is a single string with g-code
  512. """
  513. gcmds = []
  514. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  515. for line in lines:
  516. line = line.strip()
  517. # Remove comments
  518. # NOTE: Limited to 1 bracket pair
  519. op = line.find("(")
  520. cl = line.find(")")
  521. if op > -1 and cl > op:
  522. #comment = line[op+1:cl]
  523. line = line[:op] + line[(cl+1):]
  524. # Parse GCode
  525. # 0 4 12
  526. # G01 X-0.007 Y-0.057
  527. # --> codes_idx = [0, 4, 12]
  528. codes = "NMGXYZIJFP"
  529. codes_idx = []
  530. i = 0
  531. for ch in line:
  532. if ch in codes:
  533. codes_idx.append(i)
  534. i += 1
  535. n_codes = len(codes_idx)
  536. if n_codes == 0:
  537. continue
  538. # Separate codes in line
  539. parts = []
  540. for p in range(n_codes-1):
  541. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  542. parts.append(line[codes_idx[-1]:].strip())
  543. # Separate codes from values
  544. cmds = {}
  545. for part in parts:
  546. cmds[part[0]] = float(part[1:])
  547. gcmds.append(cmds)
  548. return gcmds
  549. def get_bounds(geometry_set):
  550. xmin = Inf
  551. ymin = Inf
  552. xmax = -Inf
  553. ymax = -Inf
  554. for gs in geometry_set:
  555. gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  556. xmin = min([xmin, gxmin])
  557. ymin = min([ymin, gymin])
  558. xmax = max([xmax, gxmax])
  559. ymax = max([ymax, gymax])
  560. return [xmin, ymin, xmax, ymax]
  561. def arc(center, radius, start, stop, direction, steps_per_circ):
  562. da_sign = {"cw": -1.0, "ccw": 1.0}
  563. points = []
  564. if direction == "ccw" and stop <= start:
  565. stop += 2*pi
  566. if direction == "cw" and stop >= start:
  567. stop -= 2*pi
  568. angle = abs(stop - start)
  569. #angle = stop-start
  570. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  571. delta_angle = da_sign[direction]*angle*1.0/steps
  572. for i in range(steps+1):
  573. theta = start + delta_angle*i
  574. points.append([center[0]+radius*cos(theta), center[1]+radius*sin(theta)])
  575. return LineString(points)
  576. ############### cam.py ####################
  577. def coord(gstr, digits, fraction):
  578. """
  579. Parse Gerber coordinates
  580. """
  581. global gerbx, gerby
  582. xindex = gstr.find("X")
  583. yindex = gstr.find("Y")
  584. index = gstr.find("D")
  585. if xindex == -1:
  586. x = gerbx
  587. y = int(gstr[(yindex+1):index])*(10**(-fraction))
  588. elif yindex == -1:
  589. y = gerby
  590. x = int(gstr[(xindex+1):index])*(10**(-fraction))
  591. else:
  592. x = int(gstr[(xindex+1):yindex])*(10**(-fraction))
  593. y = int(gstr[(yindex+1):index])*(10**(-fraction))
  594. gerbx = x
  595. gerby = y
  596. return [x, y]
  597. ################ end of cam.py #############