camlib.py 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413
  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(object):
  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 ApertureMacro:
  155. ## Regular expressions
  156. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  157. am2_re = re.compile(r'(.*)%$')
  158. amcomm_re = re.compile(r'^0(.*)')
  159. amprim_re = re.compile(r'^[1-9].*')
  160. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  161. def __init__(self, name=None):
  162. self.name = name
  163. self.raw = ""
  164. ## These below are recomputed for every aperture
  165. ## definition, in other words, are temporary variables.
  166. self.primitives = []
  167. self.locvars = {}
  168. self.geometry = None
  169. def to_dict(self):
  170. """
  171. Returns the object in a serializable form. Only the name and
  172. raw are required.
  173. :return: Dictionary representing the object. JSON ready.
  174. :rtype: dict
  175. """
  176. return {
  177. 'name': self.name,
  178. 'raw': self.raw
  179. }
  180. def from_dict(self, d):
  181. """
  182. Populates the object from a serial representation created
  183. with ``self.to_dict()``.
  184. :param d: Serial representation of an ApertureMacro object.
  185. :return: None
  186. """
  187. for attr in ['name', 'raw']:
  188. setattr(self, attr, d[attr])
  189. def parse_content(self):
  190. """
  191. Creates numerical lists for all primitives in the aperture
  192. macro (in ``self.raw``) by replacing all variables by their
  193. values iteratively and evaluating expressions. Results
  194. are stored in ``self.primitives``.
  195. :return: None
  196. """
  197. # Cleanup
  198. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  199. self.primitives = []
  200. # Separate parts
  201. parts = self.raw.split('*')
  202. #### Every part in the macro ####
  203. for part in parts:
  204. ### Comments. Ignored.
  205. match = ApertureMacro.amcomm_re.search(part)
  206. if match:
  207. continue
  208. ### Variables
  209. # These are variables defined locally inside the macro. They can be
  210. # numerical constant or defind in terms of previously define
  211. # variables, which can be defined locally or in an aperture
  212. # definition. All replacements ocurr here.
  213. match = ApertureMacro.amvar_re.search(part)
  214. if match:
  215. var = match.group(1)
  216. val = match.group(2)
  217. # Replace variables in value
  218. for v in self.locvars:
  219. val = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), val)
  220. # Make all others 0
  221. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  222. # Change x with *
  223. val = re.sub(r'[xX]', "*", val)
  224. # Eval() and store.
  225. self.locvars[var] = eval(val)
  226. continue
  227. ### Primitives
  228. # Each is an array. The first identifies the primitive, while the
  229. # rest depend on the primitive. All are strings representing a
  230. # number and may contain variable definition. The values of these
  231. # variables are defined in an aperture definition.
  232. match = ApertureMacro.amprim_re.search(part)
  233. if match:
  234. ## Replace all variables
  235. for v in self.locvars:
  236. part = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  237. # Make all others 0
  238. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  239. # Change x with *
  240. part = re.sub(r'[xX]', "*", part)
  241. ## Store
  242. elements = part.split(",")
  243. self.primitives.append([eval(x) for x in elements])
  244. continue
  245. print "WARNING: Unknown syntax of aperture macro part:", part
  246. def append(self, data):
  247. """
  248. Appends a string to the raw macro.
  249. :param data: Part of the macro.
  250. :type data: str
  251. :return: None
  252. """
  253. self.raw += data
  254. @staticmethod
  255. def default2zero(n, mods):
  256. """
  257. Pads the ``mods`` list with zeros resulting in an
  258. list of length n.
  259. :param n: Length of the resulting list.
  260. :type n: int
  261. :param mods: List to be padded.
  262. :type mods: list
  263. :return: Zero-padded list.
  264. :rtype: list
  265. """
  266. x = [0.0]*n
  267. na = len(mods)
  268. x[0:na] = mods
  269. return x
  270. @staticmethod
  271. def make_circle(mods):
  272. """
  273. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  274. :return:
  275. """
  276. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  277. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  278. @staticmethod
  279. def make_vectorline(mods):
  280. """
  281. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  282. rotation angle around origin in degrees)
  283. :return:
  284. """
  285. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  286. line = LineString([(xs, ys), (xe, ye)])
  287. box = line.buffer(width/2, cap_style=2)
  288. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  289. return {"pol": int(pol), "geometry": box_rotated}
  290. @staticmethod
  291. def make_centerline(mods):
  292. """
  293. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  294. rotation angle around origin in degrees)
  295. :return:
  296. """
  297. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  298. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  299. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  300. return {"pol": int(pol), "geometry": box_rotated}
  301. @staticmethod
  302. def make_lowerleftline(mods):
  303. """
  304. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  305. rotation angle around origin in degrees)
  306. :return:
  307. """
  308. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  309. box = shply_box(x, y, x+width, y+height)
  310. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  311. return {"pol": int(pol), "geometry": box_rotated}
  312. @staticmethod
  313. def make_outline(mods):
  314. """
  315. :param mods:
  316. :return:
  317. """
  318. pol = mods[0]
  319. n = mods[1]
  320. points = [(0, 0)]*(n+1)
  321. for i in range(n+1):
  322. points[i] = mods[2*i + 2:2*i + 4]
  323. angle = mods[2*n + 4]
  324. poly = Polygon(points)
  325. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  326. return {"pol": int(pol), "geometry": poly_rotated}
  327. @staticmethod
  328. def make_polygon(mods):
  329. """
  330. Note: Specs indicate that rotation is only allowed if the center
  331. (x, y) == (0, 0). I will tolerate breaking this rule.
  332. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  333. diameter of circumscribed circle >=0, rotation angle around origin)
  334. :return:
  335. """
  336. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  337. points = [(0, 0)]*nverts
  338. for i in range(nverts):
  339. points[i] = (x + 0.5 * dia * cos(2*pi * i/nverts),
  340. y + 0.5 * dia * sin(2*pi * i/nverts))
  341. poly = Polygon(points)
  342. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  343. return {"pol": int(pol), "geometry": poly_rotated}
  344. @staticmethod
  345. def make_moire(mods):
  346. """
  347. Note: Specs indicate that rotation is only allowed if the center
  348. (x, y) == (0, 0). I will tolerate breaking this rule.
  349. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  350. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  351. angle around origin in degrees)
  352. :return:
  353. """
  354. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  355. r = dia/2 - thickness/2
  356. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  357. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  358. i = 1 # Number of rings created so far
  359. ## If the ring does not have an interior it means that it is
  360. ## a disk. Then stop.
  361. while len(ring.interiors) > 0 and i < nrings:
  362. r -= thickness + gap
  363. if r <= 0:
  364. break
  365. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  366. result = cascaded_union([result, ring])
  367. i += 1
  368. ## Crosshair
  369. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  370. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  371. result = cascaded_union([result, hor, ver])
  372. return {"pol": 1, "geometry": result}
  373. @staticmethod
  374. def make_thermal(mods):
  375. """
  376. Note: Specs indicate that rotation is only allowed if the center
  377. (x, y) == (0, 0). I will tolerate breaking this rule.
  378. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  379. gap-thickness, rotation angle around origin]
  380. :return:
  381. """
  382. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  383. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  384. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  385. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  386. thermal = ring.difference(hline.union(vline))
  387. return {"pol": 1, "geometry": thermal}
  388. def make_geometry(self, modifiers):
  389. """
  390. Runs the macro for the given modifiers and generates
  391. the corresponding geometry.
  392. :param modifiers: Modifiers (parameters) for this macro
  393. :type modifiers: list
  394. """
  395. ## Primitive makers
  396. makers = {
  397. "1": ApertureMacro.make_circle,
  398. "2": ApertureMacro.make_vectorline,
  399. "20": ApertureMacro.make_vectorline,
  400. "21": ApertureMacro.make_centerline,
  401. "22": ApertureMacro.make_lowerleftline,
  402. "4": ApertureMacro.make_outline,
  403. "5": ApertureMacro.make_polygon,
  404. "6": ApertureMacro.make_moire,
  405. "7": ApertureMacro.make_thermal
  406. }
  407. ## Store modifiers as local variables
  408. modifiers = modifiers or []
  409. modifiers = [float(m) for m in modifiers]
  410. self.locvars = {}
  411. for i in range(0, len(modifiers)):
  412. self.locvars[str(i+1)] = modifiers[i]
  413. ## Parse
  414. self.primitives = [] # Cleanup
  415. self.geometry = None
  416. self.parse_content()
  417. ## Make the geometry
  418. for primitive in self.primitives:
  419. # Make the primitive
  420. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  421. # Add it (according to polarity)
  422. if self.geometry is None and prim_geo['pol'] == 1:
  423. self.geometry = prim_geo['geometry']
  424. continue
  425. if prim_geo['pol'] == 1:
  426. self.geometry = self.geometry.union(prim_geo['geometry'])
  427. continue
  428. if prim_geo['pol'] == 0:
  429. self.geometry = self.geometry.difference(prim_geo['geometry'])
  430. continue
  431. return self.geometry
  432. class Gerber (Geometry):
  433. """
  434. **ATTRIBUTES**
  435. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  436. The values are dictionaries key/value pairs which describe the aperture. The
  437. type key is always present and the rest depend on the key:
  438. +-----------+-----------------------------------+
  439. | Key | Value |
  440. +===========+===================================+
  441. | type | (str) "C", "R", "O", "P", or "AP" |
  442. +-----------+-----------------------------------+
  443. | others | Depend on ``type`` |
  444. +-----------+-----------------------------------+
  445. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  446. that can be instanciated with different parameters in an aperture
  447. definition. See ``apertures`` above. The key is the name of the macro,
  448. and the macro itself, the value, is a ``Aperture_Macro`` object.
  449. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  450. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  451. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  452. *buffering* (or thickening) the ``paths`` with the aperture. These are
  453. generated from ``paths`` in ``buffer_paths()``.
  454. **USAGE**::
  455. g = Gerber()
  456. g.parse_file(filename)
  457. g.create_geometry()
  458. do_something(s.solid_geometry)
  459. """
  460. def __init__(self):
  461. """
  462. The constructor takes no parameters. Use ``gerber.parse_files()``
  463. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  464. :return: Gerber object
  465. :rtype: Gerber
  466. """
  467. # Initialize parent
  468. Geometry.__init__(self)
  469. self.solid_geometry = Polygon()
  470. # Number format
  471. self.int_digits = 3
  472. """Number of integer digits in Gerber numbers. Used during parsing."""
  473. self.frac_digits = 4
  474. """Number of fraction digits in Gerber numbers. Used during parsing."""
  475. ## Gerber elements ##
  476. # Apertures {'id':{'type':chr,
  477. # ['size':float], ['width':float],
  478. # ['height':float]}, ...}
  479. self.apertures = {}
  480. # Aperture Macros
  481. self.aperture_macros = {}
  482. # Attributes to be included in serialization
  483. # Always append to it because it carries contents
  484. # from Geometry.
  485. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures',
  486. 'aperture_macros', 'solid_geometry']
  487. #### Parser patterns ####
  488. # FS - Format Specification
  489. # The format of X and Y must be the same!
  490. # L-omit leading zeros, T-omit trailing zeros
  491. # A-absolute notation, I-incremental notation
  492. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  493. # Mode (IN/MM)
  494. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  495. # Comment G04|G4
  496. self.comm_re = re.compile(r'^G0?4(.*)$')
  497. # AD - Aperture definition
  498. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z0-9]*)(?:,(.*))?\*%$')
  499. # AM - Aperture Macro
  500. # Beginning of macro (Ends with *%):
  501. self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  502. # Tool change
  503. # May begin with G54 but that is deprecated
  504. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  505. # G01... - Linear interpolation plus flashes with coordinates
  506. # Operation code (D0x) missing is deprecated... oh well I will support it.
  507. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X(-?\d+))?(?=.*Y(-?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  508. # Operation code alone, usually just D03 (Flash)
  509. self.opcode_re = re.compile(r'^D0?([123])\*$')
  510. # G02/3... - Circular interpolation with coordinates
  511. # 2-clockwise, 3-counterclockwise
  512. # Operation code (D0x) missing is deprecated... oh well I will support it.
  513. # Optional start with G02 or G03, optional end with D01 or D02 with
  514. # optional coordinates but at least one in any order.
  515. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X(-?\d+))?(?=.*Y(-?\d+))' +
  516. '?(?=.*I(-?\d+))?(?=.*J(-?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  517. # G01/2/3 Occurring without coordinates
  518. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  519. # Single D74 or multi D75 quadrant for circular interpolation
  520. self.quad_re = re.compile(r'^G7([45])\*$')
  521. # Region mode on
  522. # In region mode, D01 starts a region
  523. # and D02 ends it. A new region can be started again
  524. # with D01. All contours must be closed before
  525. # D02 or G37.
  526. self.regionon_re = re.compile(r'^G36\*$')
  527. # Region mode off
  528. # Will end a region and come off region mode.
  529. # All contours must be closed before D02 or G37.
  530. self.regionoff_re = re.compile(r'^G37\*$')
  531. # End of file
  532. self.eof_re = re.compile(r'^M02\*')
  533. # IP - Image polarity
  534. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  535. # LP - Level polarity
  536. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  537. # Units (OBSOLETE)
  538. self.units_re = re.compile(r'^G7([01])\*$')
  539. # Absolute/Relative G90/1 (OBSOLETE)
  540. self.absrel_re = re.compile(r'^G9([01])\*$')
  541. # Aperture macros
  542. self.am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  543. self.am2_re = re.compile(r'(.*)%$')
  544. # TODO: This is bad.
  545. self.steps_per_circ = 40
  546. def scale(self, factor):
  547. """
  548. Scales the objects' geometry on the XY plane by a given factor.
  549. These are:
  550. * ``buffered_paths``
  551. * ``flash_geometry``
  552. * ``solid_geometry``
  553. * ``regions``
  554. NOTE:
  555. Does not modify the data used to create these elements. If these
  556. are recreated, the scaling will be lost. This behavior was modified
  557. because of the complexity reached in this class.
  558. :param factor: Number by which to scale.
  559. :type factor: float
  560. :rtype : None
  561. """
  562. ## solid_geometry ???
  563. # It's a cascaded union of objects.
  564. self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  565. factor, origin=(0, 0))
  566. # # Now buffered_paths, flash_geometry and solid_geometry
  567. # self.create_geometry()
  568. def offset(self, vect):
  569. """
  570. Offsets the objects' geometry on the XY plane by a given vector.
  571. These are:
  572. * ``buffered_paths``
  573. * ``flash_geometry``
  574. * ``solid_geometry``
  575. * ``regions``
  576. NOTE:
  577. Does not modify the data used to create these elements. If these
  578. are recreated, the scaling will be lost. This behavior was modified
  579. because of the complexity reached in this class.
  580. :param vect: (x, y) offset vector.
  581. :type vect: tuple
  582. :return: None
  583. """
  584. dx, dy = vect
  585. ## Solid geometry
  586. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  587. def mirror(self, axis, point):
  588. """
  589. Mirrors the object around a specified axis passign through
  590. the given point. What is affected:
  591. * ``buffered_paths``
  592. * ``flash_geometry``
  593. * ``solid_geometry``
  594. * ``regions``
  595. NOTE:
  596. Does not modify the data used to create these elements. If these
  597. are recreated, the scaling will be lost. This behavior was modified
  598. because of the complexity reached in this class.
  599. :param axis: "X" or "Y" indicates around which axis to mirror.
  600. :type axis: str
  601. :param point: [x, y] point belonging to the mirror axis.
  602. :type point: list
  603. :return: None
  604. """
  605. px, py = point
  606. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  607. ## solid_geometry ???
  608. # It's a cascaded union of objects.
  609. self.solid_geometry = affinity.scale(self.solid_geometry,
  610. xscale, yscale, origin=(px, py))
  611. def aperture_parse(self, apertureId, apertureType, apParameters):
  612. """
  613. Parse gerber aperture definition into dictionary of apertures.
  614. The following kinds and their attributes are supported:
  615. * *Circular (C)*: size (float)
  616. * *Rectangle (R)*: width (float), height (float)
  617. * *Obround (O)*: width (float), height (float).
  618. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  619. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  620. :param apertureId: Id of the aperture being defined.
  621. :param apertureType: Type of the aperture.
  622. :param apParameters: Parameters of the aperture.
  623. :type apertureId: str
  624. :type apertureType: str
  625. :type apParameters: str
  626. :return: Identifier of the aperture.
  627. :rtype: str
  628. """
  629. # Found some Gerber with a leading zero in the aperture id and the
  630. # referenced it without the zero, so this is a hack to handle that.
  631. apid = str(int(apertureId))
  632. try: # Could be empty for aperture macros
  633. paramList = apParameters.split('X')
  634. except:
  635. paramList = None
  636. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  637. self.apertures[apid] = {"type": "C",
  638. "size": float(paramList[0])}
  639. return apid
  640. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  641. self.apertures[apid] = {"type": "R",
  642. "width": float(paramList[0]),
  643. "height": float(paramList[1])}
  644. return apid
  645. if apertureType == "O": # Obround
  646. self.apertures[apid] = {"type": "O",
  647. "width": float(paramList[0]),
  648. "height": float(paramList[1])}
  649. return apid
  650. if apertureType == "P": # Polygon (regular)
  651. self.apertures[apid] = {"type": "P",
  652. "diam": float(paramList[0]),
  653. "nVertices": int(paramList[1])}
  654. if len(paramList) >= 3:
  655. self.apertures[apid]["rotation"] = float(paramList[2])
  656. return apid
  657. if apertureType in self.aperture_macros:
  658. self.apertures[apid] = {"type": "AM",
  659. "macro": self.aperture_macros[apertureType],
  660. "modifiers": paramList}
  661. return apid
  662. print "WARNING: Aperture not implemented:", apertureType
  663. return None
  664. def parse_file(self, filename):
  665. """
  666. Calls Gerber.parse_lines() with array of lines
  667. read from the given file.
  668. :param filename: Gerber file to parse.
  669. :type filename: str
  670. :return: None
  671. """
  672. gfile = open(filename, 'r')
  673. gstr = gfile.readlines()
  674. gfile.close()
  675. self.parse_lines(gstr)
  676. def parse_lines(self, glines):
  677. """
  678. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  679. ``self.flashes``, ``self.regions`` and ``self.units``.
  680. :param glines: Gerber code as list of strings, each element being
  681. one line of the source file.
  682. :type glines: list
  683. :return: None
  684. :rtype: None
  685. """
  686. # Coordinates of the current path, each is [x, y]
  687. path = []
  688. # Polygons are stored here until there is a change in polarity.
  689. # Only then they are combined via cascaded_union and added or
  690. # subtracted from solid_geometry. This is ~100 times faster than
  691. # applyng a union for every new polygon.
  692. poly_buffer = []
  693. last_path_aperture = None
  694. current_aperture = None
  695. # 1,2 or 3 from "G01", "G02" or "G03"
  696. current_interpolation_mode = None
  697. # 1 or 2 from "D01" or "D02"
  698. # Note this is to support deprecated Gerber not putting
  699. # an operation code at the end of every coordinate line.
  700. current_operation_code = None
  701. # Current coordinates
  702. current_x = None
  703. current_y = None
  704. # Absolute or Relative/Incremental coordinates
  705. # Not implemented
  706. absolute = True
  707. # How to interpret circular interpolation: SINGLE or MULTI
  708. quadrant_mode = None
  709. # Indicates we are parsing an aperture macro
  710. current_macro = None
  711. # Indicates the current polarity: D-Dark, C-Clear
  712. current_polarity = 'D'
  713. # If a region is being defined
  714. making_region = False
  715. #### Parsing starts here ####
  716. line_num = 0
  717. for gline in glines:
  718. line_num += 1
  719. ### Cleanup
  720. gline = gline.strip(' \r\n')
  721. ### Aperture Macros
  722. # Having this at the beggining will slow things down
  723. # but macros can have complicated statements than could
  724. # be caught by other ptterns.
  725. if current_macro is None: # No macro started yet
  726. match = self.am1_re.search(gline)
  727. # Start macro if match, else not an AM, carry on.
  728. if match:
  729. current_macro = match.group(1)
  730. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  731. if match.group(2): # Append
  732. self.aperture_macros[current_macro].append(match.group(2))
  733. if match.group(3): # Finish macro
  734. #self.aperture_macros[current_macro].parse_content()
  735. current_macro = None
  736. continue
  737. else: # Continue macro
  738. match = self.am2_re.search(gline)
  739. if match: # Finish macro
  740. self.aperture_macros[current_macro].append(match.group(1))
  741. #self.aperture_macros[current_macro].parse_content()
  742. current_macro = None
  743. else: # Append
  744. self.aperture_macros[current_macro].append(gline)
  745. continue
  746. ### G01 - Linear interpolation plus flashes
  747. # Operation code (D0x) missing is deprecated... oh well I will support it.
  748. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  749. match = self.lin_re.search(gline)
  750. if match:
  751. # Dxx alone?
  752. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  753. # try:
  754. # current_operation_code = int(match.group(4))
  755. # except:
  756. # pass # A line with just * will match too.
  757. # continue
  758. # NOTE: Letting it continue allows it to react to the
  759. # operation code.
  760. # Parse coordinates
  761. if match.group(2) is not None:
  762. current_x = parse_gerber_number(match.group(2), self.frac_digits)
  763. if match.group(3) is not None:
  764. current_y = parse_gerber_number(match.group(3), self.frac_digits)
  765. # Parse operation code
  766. if match.group(4) is not None:
  767. current_operation_code = int(match.group(4))
  768. # Pen down: add segment
  769. if current_operation_code == 1:
  770. path.append([current_x, current_y])
  771. last_path_aperture = current_aperture
  772. elif current_operation_code == 2:
  773. if len(path) > 1:
  774. ## --- BUFFERED ---
  775. if making_region:
  776. geo = Polygon(path)
  777. else:
  778. if last_path_aperture is None:
  779. print "Warning: No aperture defined for curent path. (%d)" % line_num
  780. width = self.apertures[last_path_aperture]["size"]
  781. geo = LineString(path).buffer(width/2)
  782. poly_buffer.append(geo)
  783. path = [[current_x, current_y]] # Start new path
  784. # Flash
  785. elif current_operation_code == 3:
  786. # --- BUFFERED ---
  787. flash = Gerber.create_flash_geometry(Point([current_x, current_y]),
  788. self.apertures[current_aperture])
  789. poly_buffer.append(flash)
  790. continue
  791. ### G02/3 - Circular interpolation
  792. # 2-clockwise, 3-counterclockwise
  793. match = self.circ_re.search(gline)
  794. if match:
  795. mode, x, y, i, j, d = match.groups()
  796. try:
  797. x = parse_gerber_number(x, self.frac_digits)
  798. except:
  799. x = current_x
  800. try:
  801. y = parse_gerber_number(y, self.frac_digits)
  802. except:
  803. y = current_y
  804. try:
  805. i = parse_gerber_number(i, self.frac_digits)
  806. except:
  807. i = 0
  808. try:
  809. j = parse_gerber_number(j, self.frac_digits)
  810. except:
  811. j = 0
  812. if quadrant_mode is None:
  813. print "ERROR: Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num
  814. print gline
  815. continue
  816. if mode is None and current_interpolation_mode not in [2, 3]:
  817. print "ERROR: Found arc without circular interpolation mode defined. (%d)" % line_num
  818. print gline
  819. continue
  820. elif mode is not None:
  821. current_interpolation_mode = int(mode)
  822. # Set operation code if provided
  823. if d is not None:
  824. current_operation_code = int(d)
  825. # Nothing created! Pen Up.
  826. if current_operation_code == 2:
  827. print "Warning: Arc with D2. (%d)" % line_num
  828. if len(path) > 1:
  829. if last_path_aperture is None:
  830. print "Warning: No aperture defined for curent path. (%d)" % line_num
  831. # --- BUFFERED ---
  832. width = self.apertures[last_path_aperture]["size"]
  833. buffered = LineString(path).buffer(width/2)
  834. poly_buffer.append(buffered)
  835. current_x = x
  836. current_y = y
  837. path = [[current_x, current_y]] # Start new path
  838. continue
  839. # Flash should not happen here
  840. if current_operation_code == 3:
  841. print "ERROR: Trying to flash within arc. (%d)" % line_num
  842. continue
  843. if quadrant_mode == 'MULTI':
  844. center = [i + current_x, j + current_y]
  845. radius = sqrt(i**2 + j**2)
  846. start = arctan2(-j, -i)
  847. stop = arctan2(-center[1] + y, -center[0] + x)
  848. arcdir = [None, None, "cw", "ccw"]
  849. this_arc = arc(center, radius, start, stop,
  850. arcdir[current_interpolation_mode],
  851. self.steps_per_circ)
  852. # Last point in path is current point
  853. current_x = this_arc[-1][0]
  854. current_y = this_arc[-1][1]
  855. # Append
  856. path += this_arc
  857. last_path_aperture = current_aperture
  858. continue
  859. if quadrant_mode == 'SINGLE':
  860. print "Warning: Single quadrant arc are not implemented yet. (%d)" % line_num
  861. ### Operation code alone
  862. match = self.opcode_re.search(gline)
  863. if match:
  864. current_operation_code = int(match.group(1))
  865. if current_operation_code == 3:
  866. ## --- Buffered ---
  867. flash = Gerber.create_flash_geometry(Point(path[-1]),
  868. self.apertures[current_aperture])
  869. poly_buffer.append(flash)
  870. continue
  871. ### G74/75* - Single or multiple quadrant arcs
  872. match = self.quad_re.search(gline)
  873. if match:
  874. if match.group(1) == '4':
  875. quadrant_mode = 'SINGLE'
  876. else:
  877. quadrant_mode = 'MULTI'
  878. continue
  879. ### G36* - Begin region
  880. if self.regionon_re.search(gline):
  881. if len(path) > 1:
  882. # Take care of what is left in the path
  883. ## --- Buffered ---
  884. width = self.apertures[last_path_aperture]["size"]
  885. geo = LineString(path).buffer(width/2)
  886. poly_buffer.append(geo)
  887. path = [path[-1]]
  888. making_region = True
  889. continue
  890. ### G37* - End region
  891. if self.regionoff_re.search(gline):
  892. making_region = False
  893. # Only one path defines region?
  894. # This can happen if D02 happened before G37 and
  895. # is not and error.
  896. if len(path) < 3:
  897. # print "ERROR: Path contains less than 3 points:"
  898. # print path
  899. # print "Line (%d): " % line_num, gline
  900. # path = []
  901. #path = [[current_x, current_y]]
  902. continue
  903. # For regions we may ignore an aperture that is None
  904. # self.regions.append({"polygon": Polygon(path),
  905. # "aperture": last_path_aperture})
  906. # --- Buffered ---
  907. region = Polygon(path)
  908. if not region.is_valid:
  909. region = region.buffer(0)
  910. poly_buffer.append(region)
  911. path = [[current_x, current_y]] # Start new path
  912. continue
  913. ### Aperture definitions %ADD...
  914. match = self.ad_re.search(gline)
  915. if match:
  916. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  917. continue
  918. ### G01/2/3* - Interpolation mode change
  919. # Can occur along with coordinates and operation code but
  920. # sometimes by itself (handled here).
  921. # Example: G01*
  922. match = self.interp_re.search(gline)
  923. if match:
  924. current_interpolation_mode = int(match.group(1))
  925. continue
  926. ### Tool/aperture change
  927. # Example: D12*
  928. match = self.tool_re.search(gline)
  929. if match:
  930. current_aperture = match.group(1)
  931. continue
  932. ### Polarity change
  933. # Example: %LPD*% or %LPC*%
  934. match = self.lpol_re.search(gline)
  935. if match:
  936. if len(path) > 1 and current_polarity != match.group(1):
  937. # --- Buffered ----
  938. width = self.apertures[last_path_aperture]["size"]
  939. geo = LineString(path).buffer(width/2)
  940. poly_buffer.append(geo)
  941. path = [path[-1]]
  942. # --- Apply buffer ---
  943. if current_polarity == 'D':
  944. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  945. else:
  946. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  947. poly_buffer = []
  948. current_polarity = match.group(1)
  949. continue
  950. ### Number format
  951. # Example: %FSLAX24Y24*%
  952. # TODO: This is ignoring most of the format. Implement the rest.
  953. match = self.fmt_re.search(gline)
  954. if match:
  955. absolute = {'A': True, 'I': False}
  956. self.int_digits = int(match.group(3))
  957. self.frac_digits = int(match.group(4))
  958. continue
  959. ### Mode (IN/MM)
  960. # Example: %MOIN*%
  961. match = self.mode_re.search(gline)
  962. if match:
  963. self.units = match.group(1)
  964. continue
  965. ### Units (G70/1) OBSOLETE
  966. match = self.units_re.search(gline)
  967. if match:
  968. self.units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  969. continue
  970. ### Absolute/relative coordinates G90/1 OBSOLETE
  971. match = self.absrel_re.search(gline)
  972. if match:
  973. absolute = {'0': True, '1': False}[match.group(1)]
  974. continue
  975. #### Ignored lines
  976. ## Comments
  977. match = self.comm_re.search(gline)
  978. if match:
  979. continue
  980. ## EOF
  981. match = self.eof_re.search(gline)
  982. if match:
  983. continue
  984. ### Line did not match any pattern. Warn user.
  985. print "WARNING: Line ignored (%d):" % line_num, gline
  986. if len(path) > 1:
  987. # EOF, create shapely LineString if something still in path
  988. ## --- Buffered ---
  989. width = self.apertures[last_path_aperture]["size"]
  990. geo = LineString(path).buffer(width/2)
  991. poly_buffer.append(geo)
  992. # --- Apply buffer ---
  993. if current_polarity == 'D':
  994. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  995. else:
  996. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  997. @staticmethod
  998. def create_flash_geometry(location, aperture):
  999. if type(location) == list:
  1000. location = Point(location)
  1001. if aperture['type'] == 'C': # Circles
  1002. return location.buffer(aperture['size']/2)
  1003. if aperture['type'] == 'R': # Rectangles
  1004. loc = location.coords[0]
  1005. width = aperture['width']
  1006. height = aperture['height']
  1007. minx = loc[0] - width/2
  1008. maxx = loc[0] + width/2
  1009. miny = loc[1] - height/2
  1010. maxy = loc[1] + height/2
  1011. return shply_box(minx, miny, maxx, maxy)
  1012. if aperture['type'] == 'O': # Obround
  1013. loc = location.coords[0]
  1014. width = aperture['width']
  1015. height = aperture['height']
  1016. if width > height:
  1017. p1 = Point(loc[0] + 0.5*(width-height), loc[1])
  1018. p2 = Point(loc[0] - 0.5*(width-height), loc[1])
  1019. c1 = p1.buffer(height*0.5)
  1020. c2 = p2.buffer(height*0.5)
  1021. else:
  1022. p1 = Point(loc[0], loc[1] + 0.5*(height-width))
  1023. p2 = Point(loc[0], loc[1] - 0.5*(height-width))
  1024. c1 = p1.buffer(width*0.5)
  1025. c2 = p2.buffer(width*0.5)
  1026. return cascaded_union([c1, c2]).convex_hull
  1027. if aperture['type'] == 'P': # Regular polygon
  1028. loc = location.coords[0]
  1029. diam = aperture['diam']
  1030. n_vertices = aperture['nVertices']
  1031. points = []
  1032. for i in range(0, n_vertices):
  1033. x = loc[0] + diam * (cos(2 * pi * i / n_vertices))
  1034. y = loc[1] + diam * (sin(2 * pi * i / n_vertices))
  1035. points.append((x, y))
  1036. ply = Polygon(points)
  1037. if 'rotation' in aperture:
  1038. ply = affinity.rotate(ply, aperture['rotation'])
  1039. return ply
  1040. if aperture['type'] == 'AM': # Aperture Macro
  1041. loc = location.coords[0]
  1042. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1043. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1044. return None
  1045. def create_geometry(self):
  1046. """
  1047. Geometry from a Gerber file is made up entirely of polygons.
  1048. Every stroke (linear or circular) has an aperture which gives
  1049. it thickness. Additionally, aperture strokes have non-zero area,
  1050. and regions naturally do as well.
  1051. :rtype : None
  1052. :return: None
  1053. """
  1054. # self.buffer_paths()
  1055. #
  1056. # self.fix_regions()
  1057. #
  1058. # self.do_flashes()
  1059. #
  1060. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1061. # [poly['polygon'] for poly in self.regions] +
  1062. # self.flash_geometry)
  1063. def get_bounding_box(self, margin=0.0, rounded=False):
  1064. """
  1065. Creates and returns a rectangular polygon bounding at a distance of
  1066. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1067. can optionally have rounded corners of radius equal to margin.
  1068. :param margin: Distance to enlarge the rectangular bounding
  1069. box in both positive and negative, x and y axes.
  1070. :type margin: float
  1071. :param rounded: Wether or not to have rounded corners.
  1072. :type rounded: bool
  1073. :return: The bounding box.
  1074. :rtype: Shapely.Polygon
  1075. """
  1076. bbox = self.solid_geometry.envelope.buffer(margin)
  1077. if not rounded:
  1078. bbox = bbox.envelope
  1079. return bbox
  1080. class Excellon(Geometry):
  1081. """
  1082. *ATTRIBUTES*
  1083. * ``tools`` (dict): The key is the tool name and the value is
  1084. a dictionary specifying the tool:
  1085. ================ ====================================
  1086. Key Value
  1087. ================ ====================================
  1088. C Diameter of the tool
  1089. Others Not supported (Ignored).
  1090. ================ ====================================
  1091. * ``drills`` (list): Each is a dictionary:
  1092. ================ ====================================
  1093. Key Value
  1094. ================ ====================================
  1095. point (Shapely.Point) Where to drill
  1096. tool (str) A key in ``tools``
  1097. ================ ====================================
  1098. """
  1099. def __init__(self):
  1100. """
  1101. The constructor takes no parameters.
  1102. :return: Excellon object.
  1103. :rtype: Excellon
  1104. """
  1105. Geometry.__init__(self)
  1106. self.tools = {}
  1107. self.drills = []
  1108. # Trailing "T" or leading "L" (default)
  1109. self.zeros = "L"
  1110. # Attributes to be included in serialization
  1111. # Always append to it because it carries contents
  1112. # from Geometry.
  1113. self.ser_attrs += ['tools', 'drills', 'zeros']
  1114. #### Patterns ####
  1115. # Regex basics:
  1116. # ^ - beginning
  1117. # $ - end
  1118. # *: 0 or more, +: 1 or more, ?: 0 or 1
  1119. # M48 - Beggining of Part Program Header
  1120. self.hbegin_re = re.compile(r'^M48$')
  1121. # M95 or % - End of Part Program Header
  1122. # NOTE: % has different meaning in the body
  1123. self.hend_re = re.compile(r'^(?:M95|%)$')
  1124. # FMAT Excellon format
  1125. self.fmat_re = re.compile(r'^FMAT,([12])$')
  1126. # Number format and units
  1127. # INCH uses 6 digits
  1128. # METRIC uses 5/6
  1129. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  1130. # Tool definition/parameters (?= is look-ahead
  1131. # NOTE: This might be an overkill!
  1132. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  1133. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1134. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1135. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1136. self.toolset_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))?' +
  1137. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1138. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1139. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1140. # Tool select
  1141. # Can have additional data after tool number but
  1142. # is ignored if present in the header.
  1143. # Warning: This will match toolset_re too.
  1144. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  1145. self.toolsel_re = re.compile(r'^T(\d+)')
  1146. # Comment
  1147. self.comm_re = re.compile(r'^;(.*)$')
  1148. # Absolute/Incremental G90/G91
  1149. self.absinc_re = re.compile(r'^G9([01])$')
  1150. # Modes of operation
  1151. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  1152. self.modes_re = re.compile(r'^G0([012345])')
  1153. # Measuring mode
  1154. # 1-metric, 2-inch
  1155. self.meas_re = re.compile(r'^M7([12])$')
  1156. # Coordinates
  1157. #self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  1158. #self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  1159. self.coordsperiod_re = re.compile(r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]')
  1160. self.coordsnoperiod_re = re.compile(r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]')
  1161. # R - Repeat hole (# times, X offset, Y offset)
  1162. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  1163. # Various stop/pause commands
  1164. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  1165. # Parse coordinates
  1166. self.leadingzeros_re = re.compile(r'^(0*)(\d*)')
  1167. def parse_file(self, filename):
  1168. """
  1169. Reads the specified file as array of lines as
  1170. passes it to ``parse_lines()``.
  1171. :param filename: The file to be read and parsed.
  1172. :type filename: str
  1173. :return: None
  1174. """
  1175. efile = open(filename, 'r')
  1176. estr = efile.readlines()
  1177. efile.close()
  1178. self.parse_lines(estr)
  1179. def parse_lines(self, elines):
  1180. """
  1181. Main Excellon parser.
  1182. :param elines: List of strings, each being a line of Excellon code.
  1183. :type elines: list
  1184. :return: None
  1185. """
  1186. # State variables
  1187. current_tool = ""
  1188. in_header = False
  1189. current_x = None
  1190. current_y = None
  1191. line_num = 0 # Line number
  1192. for eline in elines:
  1193. line_num += 1
  1194. ### Cleanup lines
  1195. eline = eline.strip(' \r\n')
  1196. ## Header Begin/End ##
  1197. if self.hbegin_re.search(eline):
  1198. in_header = True
  1199. continue
  1200. if self.hend_re.search(eline):
  1201. in_header = False
  1202. continue
  1203. #### Body ####
  1204. if not in_header:
  1205. ## Tool change ##
  1206. match = self.toolsel_re.search(eline)
  1207. if match:
  1208. current_tool = str(int(match.group(1)))
  1209. continue
  1210. ## Coordinates without period ##
  1211. match = self.coordsnoperiod_re.search(eline)
  1212. if match:
  1213. try:
  1214. #x = float(match.group(1))/10000
  1215. x = self.parse_number(match.group(1))
  1216. current_x = x
  1217. except TypeError:
  1218. x = current_x
  1219. try:
  1220. #y = float(match.group(2))/10000
  1221. y = self.parse_number(match.group(2))
  1222. current_y = y
  1223. except TypeError:
  1224. y = current_y
  1225. if x is None or y is None:
  1226. print "ERROR: Missing coordinates"
  1227. continue
  1228. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1229. continue
  1230. ## Coordinates with period: Use literally. ##
  1231. match = self.coordsperiod_re.search(eline)
  1232. if match:
  1233. try:
  1234. x = float(match.group(1))
  1235. current_x = x
  1236. except TypeError:
  1237. x = current_x
  1238. try:
  1239. y = float(match.group(2))
  1240. current_y = y
  1241. except TypeError:
  1242. y = current_y
  1243. if x is None or y is None:
  1244. print "ERROR: Missing coordinates"
  1245. continue
  1246. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1247. continue
  1248. #### Header ####
  1249. if in_header:
  1250. ## Tool definitions ##
  1251. match = self.toolset_re.search(eline)
  1252. if match:
  1253. name = str(int(match.group(1)))
  1254. spec = {
  1255. "C": float(match.group(2)),
  1256. # "F": float(match.group(3)),
  1257. # "S": float(match.group(4)),
  1258. # "B": float(match.group(5)),
  1259. # "H": float(match.group(6)),
  1260. # "Z": float(match.group(7))
  1261. }
  1262. self.tools[name] = spec
  1263. continue
  1264. ## Units and number format ##
  1265. match = self.units_re.match(eline)
  1266. if match:
  1267. self.zeros = match.group(2) # "T" or "L"
  1268. self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  1269. continue
  1270. print "WARNING: Line ignored:", eline
  1271. def parse_number(self, number_str):
  1272. """
  1273. Parses coordinate numbers without period.
  1274. :param number_str: String representing the numerical value.
  1275. :type number_str: str
  1276. :return: Floating point representation of the number
  1277. :rtype: foat
  1278. """
  1279. if self.zeros == "L":
  1280. match = self.leadingzeros_re.search(number_str)
  1281. return float(number_str)/(10**(len(match.group(2))-2+len(match.group(1))))
  1282. else: # Trailing
  1283. return float(number_str)/10000
  1284. def create_geometry(self):
  1285. """
  1286. Creates circles of the tool diameter at every point
  1287. specified in ``self.drills``.
  1288. :return: None
  1289. """
  1290. self.solid_geometry = []
  1291. for drill in self.drills:
  1292. #poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  1293. tooldia = self.tools[drill['tool']]['C']
  1294. poly = drill['point'].buffer(tooldia/2.0)
  1295. self.solid_geometry.append(poly)
  1296. def scale(self, factor):
  1297. """
  1298. Scales geometry on the XY plane in the object by a given factor.
  1299. Tool sizes, feedrates an Z-plane dimensions are untouched.
  1300. :param factor: Number by which to scale the object.
  1301. :type factor: float
  1302. :return: None
  1303. :rtype: NOne
  1304. """
  1305. # Drills
  1306. for drill in self.drills:
  1307. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  1308. self.create_geometry()
  1309. def offset(self, vect):
  1310. """
  1311. Offsets geometry on the XY plane in the object by a given vector.
  1312. :param vect: (x, y) offset vector.
  1313. :type vect: tuple
  1314. :return: None
  1315. """
  1316. dx, dy = vect
  1317. # Drills
  1318. for drill in self.drills:
  1319. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  1320. # Recreate geometry
  1321. self.create_geometry()
  1322. def mirror(self, axis, point):
  1323. """
  1324. :param axis: "X" or "Y" indicates around which axis to mirror.
  1325. :type axis: str
  1326. :param point: [x, y] point belonging to the mirror axis.
  1327. :type point: list
  1328. :return: None
  1329. """
  1330. px, py = point
  1331. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1332. # Modify data
  1333. for drill in self.drills:
  1334. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  1335. # Recreate geometry
  1336. self.create_geometry()
  1337. def convert_units(self, units):
  1338. factor = Geometry.convert_units(self, units)
  1339. # Tools
  1340. for tname in self.tools:
  1341. self.tools[tname]["C"] *= factor
  1342. self.create_geometry()
  1343. return factor
  1344. class CNCjob(Geometry):
  1345. """
  1346. Represents work to be done by a CNC machine.
  1347. *ATTRIBUTES*
  1348. * ``gcode_parsed`` (list): Each is a dictionary:
  1349. ===================== =========================================
  1350. Key Value
  1351. ===================== =========================================
  1352. geom (Shapely.LineString) Tool path (XY plane)
  1353. kind (string) "AB", A is "T" (travel) or
  1354. "C" (cut). B is "F" (fast) or "S" (slow).
  1355. ===================== =========================================
  1356. """
  1357. def __init__(self, units="in", kind="generic", z_move=0.1,
  1358. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  1359. Geometry.__init__(self)
  1360. self.kind = kind
  1361. self.units = units
  1362. self.z_cut = z_cut
  1363. self.z_move = z_move
  1364. self.feedrate = feedrate
  1365. self.tooldia = tooldia
  1366. self.unitcode = {"IN": "G20", "MM": "G21"}
  1367. self.pausecode = "G04 P1"
  1368. self.feedminutecode = "G94"
  1369. self.absolutecode = "G90"
  1370. self.gcode = ""
  1371. self.input_geometry_bounds = None
  1372. self.gcode_parsed = None
  1373. self.steps_per_circ = 20 # Used when parsing G-code arcs
  1374. # Attributes to be included in serialization
  1375. # Always append to it because it carries contents
  1376. # from Geometry.
  1377. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  1378. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  1379. 'steps_per_circ']
  1380. def convert_units(self, units):
  1381. factor = Geometry.convert_units(self, units)
  1382. print "CNCjob.convert_units()"
  1383. self.z_cut *= factor
  1384. self.z_move *= factor
  1385. self.feedrate *= factor
  1386. self.tooldia *= factor
  1387. return factor
  1388. def generate_from_excellon(self, exobj):
  1389. """
  1390. Generates G-code for drilling from Excellon object.
  1391. self.gcode becomes a list, each element is a
  1392. different job for each tool in the excellon code.
  1393. """
  1394. self.kind = "drill"
  1395. self.gcode = []
  1396. t = "G00 X%.4fY%.4f\n"
  1397. down = "G01 Z%.4f\n" % self.z_cut
  1398. up = "G01 Z%.4f\n" % self.z_move
  1399. for tool in exobj.tools:
  1400. points = []
  1401. for drill in exobj.drill:
  1402. if drill['tool'] == tool:
  1403. points.append(drill['point'])
  1404. gcode = self.unitcode[self.units.upper()] + "\n"
  1405. gcode += self.absolutecode + "\n"
  1406. gcode += self.feedminutecode + "\n"
  1407. gcode += "F%.2f\n" % self.feedrate
  1408. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1409. gcode += "M03\n" # Spindle start
  1410. gcode += self.pausecode + "\n"
  1411. for point in points:
  1412. gcode += t % point
  1413. gcode += down + up
  1414. gcode += t % (0, 0)
  1415. gcode += "M05\n" # Spindle stop
  1416. self.gcode.append(gcode)
  1417. def generate_from_excellon_by_tool(self, exobj, tools="all"):
  1418. """
  1419. Creates gcode for this object from an Excellon object
  1420. for the specified tools.
  1421. :param exobj: Excellon object to process
  1422. :type exobj: Excellon
  1423. :param tools: Comma separated tool names
  1424. :type: tools: str
  1425. :return: None
  1426. :rtype: None
  1427. """
  1428. print "Creating CNC Job from Excellon..."
  1429. if tools == "all":
  1430. tools = [tool for tool in exobj.tools]
  1431. else:
  1432. tools = [x.strip() for x in tools.split(",")]
  1433. tools = filter(lambda i: i in exobj.tools, tools)
  1434. print "Tools are:", tools
  1435. points = []
  1436. for drill in exobj.drills:
  1437. if drill['tool'] in tools:
  1438. points.append(drill['point'])
  1439. print "Found %d drills." % len(points)
  1440. #self.kind = "drill"
  1441. self.gcode = []
  1442. t = "G00 X%.4fY%.4f\n"
  1443. down = "G01 Z%.4f\n" % self.z_cut
  1444. up = "G01 Z%.4f\n" % self.z_move
  1445. gcode = self.unitcode[self.units.upper()] + "\n"
  1446. gcode += self.absolutecode + "\n"
  1447. gcode += self.feedminutecode + "\n"
  1448. gcode += "F%.2f\n" % self.feedrate
  1449. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1450. gcode += "M03\n" # Spindle start
  1451. gcode += self.pausecode + "\n"
  1452. for point in points:
  1453. x, y = point.coords.xy
  1454. gcode += t % (x[0], y[0])
  1455. gcode += down + up
  1456. gcode += t % (0, 0)
  1457. gcode += "M05\n" # Spindle stop
  1458. self.gcode = gcode
  1459. def generate_from_geometry(self, geometry, append=True, tooldia=None, tolerance=0):
  1460. """
  1461. Generates G-Code from a Geometry object. Stores in ``self.gcode``.
  1462. :param geometry: Geometry defining the toolpath
  1463. :type geometry: Geometry
  1464. :param append: Wether to append to self.gcode or re-write it.
  1465. :type append: bool
  1466. :param tooldia: If given, sets the tooldia property but does
  1467. not affect the process in any other way.
  1468. :type tooldia: bool
  1469. :param tolerance: All points in the simplified object will be within the
  1470. tolerance distance of the original geometry.
  1471. :return: None
  1472. :rtype: None
  1473. """
  1474. if tooldia is not None:
  1475. self.tooldia = tooldia
  1476. self.input_geometry_bounds = geometry.bounds()
  1477. if not append:
  1478. self.gcode = ""
  1479. self.gcode = self.unitcode[self.units.upper()] + "\n"
  1480. self.gcode += self.absolutecode + "\n"
  1481. self.gcode += self.feedminutecode + "\n"
  1482. self.gcode += "F%.2f\n" % self.feedrate
  1483. self.gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1484. self.gcode += "M03\n" # Spindle start
  1485. self.gcode += self.pausecode + "\n"
  1486. for geo in geometry.solid_geometry:
  1487. if type(geo) == Polygon:
  1488. self.gcode += self.polygon2gcode(geo, tolerance=tolerance)
  1489. continue
  1490. if type(geo) == LineString or type(geo) == LinearRing:
  1491. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  1492. continue
  1493. if type(geo) == Point:
  1494. self.gcode += self.point2gcode(geo)
  1495. continue
  1496. if type(geo) == MultiPolygon:
  1497. for poly in geo:
  1498. self.gcode += self.polygon2gcode(poly, tolerance=tolerance)
  1499. continue
  1500. print "WARNING: G-code generation not implemented for %s" % (str(type(geo)))
  1501. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1502. self.gcode += "G00 X0Y0\n"
  1503. self.gcode += "M05\n" # Spindle stop
  1504. def pre_parse(self, gtext):
  1505. """
  1506. Separates parts of the G-Code text into a list of dictionaries.
  1507. Used by ``self.gcode_parse()``.
  1508. :param gtext: A single string with g-code
  1509. """
  1510. # Units: G20-inches, G21-mm
  1511. units_re = re.compile(r'^G2([01])')
  1512. # TODO: This has to be re-done
  1513. gcmds = []
  1514. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  1515. for line in lines:
  1516. # Clean up
  1517. line = line.strip()
  1518. # Remove comments
  1519. # NOTE: Limited to 1 bracket pair
  1520. op = line.find("(")
  1521. cl = line.find(")")
  1522. #if op > -1 and cl > op:
  1523. if cl > op > -1:
  1524. #comment = line[op+1:cl]
  1525. line = line[:op] + line[(cl+1):]
  1526. # Units
  1527. match = units_re.match(line)
  1528. if match:
  1529. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  1530. # Parse GCode
  1531. # 0 4 12
  1532. # G01 X-0.007 Y-0.057
  1533. # --> codes_idx = [0, 4, 12]
  1534. codes = "NMGXYZIJFP"
  1535. codes_idx = []
  1536. i = 0
  1537. for ch in line:
  1538. if ch in codes:
  1539. codes_idx.append(i)
  1540. i += 1
  1541. n_codes = len(codes_idx)
  1542. if n_codes == 0:
  1543. continue
  1544. # Separate codes in line
  1545. parts = []
  1546. for p in range(n_codes-1):
  1547. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  1548. parts.append(line[codes_idx[-1]:].strip())
  1549. # Separate codes from values
  1550. cmds = {}
  1551. for part in parts:
  1552. cmds[part[0]] = float(part[1:])
  1553. gcmds.append(cmds)
  1554. return gcmds
  1555. def gcode_parse(self):
  1556. """
  1557. G-Code parser (from self.gcode). Generates dictionary with
  1558. single-segment LineString's and "kind" indicating cut or travel,
  1559. fast or feedrate speed.
  1560. """
  1561. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1562. # Results go here
  1563. geometry = []
  1564. # TODO: Merge into single parser?
  1565. gobjs = self.pre_parse(self.gcode)
  1566. # Last known instruction
  1567. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  1568. # Current path: temporary storage until tool is
  1569. # lifted or lowered.
  1570. path = [(0, 0)]
  1571. # Process every instruction
  1572. for gobj in gobjs:
  1573. ## Changing height
  1574. if 'Z' in gobj:
  1575. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  1576. print "WARNING: Non-orthogonal motion: From", current
  1577. print " To:", gobj
  1578. current['Z'] = gobj['Z']
  1579. # Store the path into geometry and reset path
  1580. if len(path) > 1:
  1581. geometry.append({"geom": LineString(path),
  1582. "kind": kind})
  1583. path = [path[-1]] # Start with the last point of last path.
  1584. if 'G' in gobj:
  1585. current['G'] = int(gobj['G'])
  1586. if 'X' in gobj or 'Y' in gobj:
  1587. if 'X' in gobj:
  1588. x = gobj['X']
  1589. else:
  1590. x = current['X']
  1591. if 'Y' in gobj:
  1592. y = gobj['Y']
  1593. else:
  1594. y = current['Y']
  1595. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1596. if current['Z'] > 0:
  1597. kind[0] = 'T'
  1598. if current['G'] > 0:
  1599. kind[1] = 'S'
  1600. arcdir = [None, None, "cw", "ccw"]
  1601. if current['G'] in [0, 1]: # line
  1602. path.append((x, y))
  1603. if current['G'] in [2, 3]: # arc
  1604. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  1605. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  1606. start = arctan2(-gobj['J'], -gobj['I'])
  1607. stop = arctan2(-center[1]+y, -center[0]+x)
  1608. path += arc(center, radius, start, stop,
  1609. arcdir[current['G']],
  1610. self.steps_per_circ)
  1611. # Update current instruction
  1612. for code in gobj:
  1613. current[code] = gobj[code]
  1614. # There might not be a change in height at the
  1615. # end, therefore, see here too if there is
  1616. # a final path.
  1617. if len(path) > 1:
  1618. geometry.append({"geom": LineString(path),
  1619. "kind": kind})
  1620. self.gcode_parsed = geometry
  1621. return geometry
  1622. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  1623. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1624. # alpha={"T": 0.3, "C": 1.0}):
  1625. # """
  1626. # Creates a Matplotlib figure with a plot of the
  1627. # G-code job.
  1628. # """
  1629. # if tooldia is None:
  1630. # tooldia = self.tooldia
  1631. #
  1632. # fig = Figure(dpi=dpi)
  1633. # ax = fig.add_subplot(111)
  1634. # ax.set_aspect(1)
  1635. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  1636. # ax.set_xlim(xmin-margin, xmax+margin)
  1637. # ax.set_ylim(ymin-margin, ymax+margin)
  1638. #
  1639. # if tooldia == 0:
  1640. # for geo in self.gcode_parsed:
  1641. # linespec = '--'
  1642. # linecolor = color[geo['kind'][0]][1]
  1643. # if geo['kind'][0] == 'C':
  1644. # linespec = 'k-'
  1645. # x, y = geo['geom'].coords.xy
  1646. # ax.plot(x, y, linespec, color=linecolor)
  1647. # else:
  1648. # for geo in self.gcode_parsed:
  1649. # poly = geo['geom'].buffer(tooldia/2.0)
  1650. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1651. # edgecolor=color[geo['kind'][0]][1],
  1652. # alpha=alpha[geo['kind'][0]], zorder=2)
  1653. # ax.add_patch(patch)
  1654. #
  1655. # return fig
  1656. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  1657. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1658. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005):
  1659. """
  1660. Plots the G-code job onto the given axes.
  1661. :param axes: Matplotlib axes on which to plot.
  1662. :param tooldia: Tool diameter.
  1663. :param dpi: Not used!
  1664. :param margin: Not used!
  1665. :param color: Color specification.
  1666. :param alpha: Transparency specification.
  1667. :param tool_tolerance: Tolerance when drawing the toolshape.
  1668. :return: None
  1669. """
  1670. if tooldia is None:
  1671. tooldia = self.tooldia
  1672. if tooldia == 0:
  1673. for geo in self.gcode_parsed:
  1674. linespec = '--'
  1675. linecolor = color[geo['kind'][0]][1]
  1676. if geo['kind'][0] == 'C':
  1677. linespec = 'k-'
  1678. x, y = geo['geom'].coords.xy
  1679. axes.plot(x, y, linespec, color=linecolor)
  1680. else:
  1681. for geo in self.gcode_parsed:
  1682. poly = geo['geom'].buffer(tooldia/2.0).simplify(tool_tolerance)
  1683. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1684. edgecolor=color[geo['kind'][0]][1],
  1685. alpha=alpha[geo['kind'][0]], zorder=2)
  1686. axes.add_patch(patch)
  1687. def create_geometry(self):
  1688. # TODO: This takes forever. Too much data?
  1689. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  1690. def polygon2gcode(self, polygon, tolerance=0):
  1691. """
  1692. Creates G-Code for the exterior and all interior paths
  1693. of a polygon.
  1694. :param polygon: A Shapely.Polygon
  1695. :type polygon: Shapely.Polygon
  1696. :param tolerance: All points in the simplified object will be within the
  1697. tolerance distance of the original geometry.
  1698. :type tolerance: float
  1699. :return: G-code to cut along polygon.
  1700. :rtype: str
  1701. """
  1702. if tolerance > 0:
  1703. target_polygon = polygon.simplify(tolerance)
  1704. else:
  1705. target_polygon = polygon
  1706. gcode = ""
  1707. t = "G0%d X%.4fY%.4f\n"
  1708. path = list(target_polygon.exterior.coords) # Polygon exterior
  1709. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1710. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1711. for pt in path[1:]:
  1712. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1713. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1714. for ints in target_polygon.interiors: # Polygon interiors
  1715. path = list(ints.coords)
  1716. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1717. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1718. for pt in path[1:]:
  1719. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1720. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1721. return gcode
  1722. def linear2gcode(self, linear, tolerance=0):
  1723. """
  1724. Generates G-code to cut along the linear feature.
  1725. :param linear: The path to cut along.
  1726. :type: Shapely.LinearRing or Shapely.Linear String
  1727. :param tolerance: All points in the simplified object will be within the
  1728. tolerance distance of the original geometry.
  1729. :type tolerance: float
  1730. :return: G-code to cut alon the linear feature.
  1731. :rtype: str
  1732. """
  1733. if tolerance > 0:
  1734. target_linear = linear.simplify(tolerance)
  1735. else:
  1736. target_linear = linear
  1737. gcode = ""
  1738. t = "G0%d X%.4fY%.4f\n"
  1739. path = list(target_linear.coords)
  1740. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1741. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1742. for pt in path[1:]:
  1743. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1744. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1745. return gcode
  1746. def point2gcode(self, point):
  1747. # TODO: This is not doing anything.
  1748. gcode = ""
  1749. t = "G0%d X%.4fY%.4f\n"
  1750. path = list(point.coords)
  1751. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1752. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1753. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1754. def scale(self, factor):
  1755. """
  1756. Scales all the geometry on the XY plane in the object by the
  1757. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  1758. not altered.
  1759. :param factor: Number by which to scale the object.
  1760. :type factor: float
  1761. :return: None
  1762. :rtype: None
  1763. """
  1764. for g in self.gcode_parsed:
  1765. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1766. self.create_geometry()
  1767. def offset(self, vect):
  1768. """
  1769. Offsets all the geometry on the XY plane in the object by the
  1770. given vector.
  1771. :param vect: (x, y) offset vector.
  1772. :type vect: tuple
  1773. :return: None
  1774. """
  1775. dx, dy = vect
  1776. for g in self.gcode_parsed:
  1777. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  1778. self.create_geometry()
  1779. # def get_bounds(geometry_set):
  1780. # xmin = Inf
  1781. # ymin = Inf
  1782. # xmax = -Inf
  1783. # ymax = -Inf
  1784. #
  1785. # #print "Getting bounds of:", str(geometry_set)
  1786. # for gs in geometry_set:
  1787. # try:
  1788. # gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  1789. # xmin = min([xmin, gxmin])
  1790. # ymin = min([ymin, gymin])
  1791. # xmax = max([xmax, gxmax])
  1792. # ymax = max([ymax, gymax])
  1793. # except:
  1794. # print "DEV WARNING: Tried to get bounds of empty geometry."
  1795. #
  1796. # return [xmin, ymin, xmax, ymax]
  1797. def get_bounds(geometry_list):
  1798. xmin = Inf
  1799. ymin = Inf
  1800. xmax = -Inf
  1801. ymax = -Inf
  1802. #print "Getting bounds of:", str(geometry_set)
  1803. for gs in geometry_list:
  1804. try:
  1805. gxmin, gymin, gxmax, gymax = gs.bounds()
  1806. xmin = min([xmin, gxmin])
  1807. ymin = min([ymin, gymin])
  1808. xmax = max([xmax, gxmax])
  1809. ymax = max([ymax, gymax])
  1810. except:
  1811. print "DEV WARNING: Tried to get bounds of empty geometry."
  1812. return [xmin, ymin, xmax, ymax]
  1813. def arc(center, radius, start, stop, direction, steps_per_circ):
  1814. """
  1815. Creates a list of point along the specified arc.
  1816. :param center: Coordinates of the center [x, y]
  1817. :type center: list
  1818. :param radius: Radius of the arc.
  1819. :type radius: float
  1820. :param start: Starting angle in radians
  1821. :type start: float
  1822. :param stop: End angle in radians
  1823. :type stop: float
  1824. :param direction: Orientation of the arc, "CW" or "CCW"
  1825. :type direction: string
  1826. :param steps_per_circ: Number of straight line segments to
  1827. represent a circle.
  1828. :type steps_per_circ: int
  1829. :return: The desired arc, as list of tuples
  1830. :rtype: list
  1831. """
  1832. # TODO: Resolution should be established by fraction of total length, not angle.
  1833. da_sign = {"cw": -1.0, "ccw": 1.0}
  1834. points = []
  1835. if direction == "ccw" and stop <= start:
  1836. stop += 2*pi
  1837. if direction == "cw" and stop >= start:
  1838. stop -= 2*pi
  1839. angle = abs(stop - start)
  1840. #angle = stop-start
  1841. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  1842. delta_angle = da_sign[direction]*angle*1.0/steps
  1843. for i in range(steps+1):
  1844. theta = start + delta_angle*i
  1845. points.append((center[0]+radius*cos(theta), center[1]+radius*sin(theta)))
  1846. return points
  1847. def clear_poly(poly, tooldia, overlap=0.1):
  1848. """
  1849. Creates a list of Shapely geometry objects covering the inside
  1850. of a Shapely.Polygon. Use for removing all the copper in a region
  1851. or bed flattening.
  1852. :param poly: Target polygon
  1853. :type poly: Shapely.Polygon
  1854. :param tooldia: Diameter of the tool
  1855. :type tooldia: float
  1856. :param overlap: Fraction of the tool diameter to overlap
  1857. in each pass.
  1858. :type overlap: float
  1859. :return: list of Shapely.Polygon
  1860. :rtype: list
  1861. """
  1862. poly_cuts = [poly.buffer(-tooldia/2.0)]
  1863. while True:
  1864. poly = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  1865. if poly.area > 0:
  1866. poly_cuts.append(poly)
  1867. else:
  1868. break
  1869. return poly_cuts
  1870. def find_polygon(poly_set, point):
  1871. """
  1872. Return the first polygon in the list of polygons poly_set
  1873. that contains the given point.
  1874. """
  1875. p = Point(point)
  1876. for poly in poly_set:
  1877. if poly.contains(p):
  1878. return poly
  1879. return None
  1880. def to_dict(obj):
  1881. """
  1882. Makes a Shapely geometry object into serializeable form.
  1883. :param obj: Shapely geometry.
  1884. :type obj: BaseGeometry
  1885. :return: Dictionary with serializable form if ``obj`` was
  1886. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  1887. """
  1888. if isinstance(obj, ApertureMacro):
  1889. return {
  1890. "__class__": "ApertureMacro",
  1891. "__inst__": obj.to_dict()
  1892. }
  1893. if isinstance(obj, BaseGeometry):
  1894. return {
  1895. "__class__": "Shply",
  1896. "__inst__": sdumps(obj)
  1897. }
  1898. return obj
  1899. def dict2obj(d):
  1900. """
  1901. Default deserializer.
  1902. :param d: Serializable dictionary representation of an object
  1903. to be reconstructed.
  1904. :return: Reconstructed object.
  1905. """
  1906. if '__class__' in d and '__inst__' in d:
  1907. if d['__class__'] == "Shply":
  1908. return sloads(d['__inst__'])
  1909. if d['__class__'] == "ApertureMacro":
  1910. am = ApertureMacro()
  1911. am.from_dict(d['__inst__'])
  1912. return am
  1913. return d
  1914. else:
  1915. return d
  1916. def plotg(geo):
  1917. try:
  1918. _ = iter(geo)
  1919. except:
  1920. geo = [geo]
  1921. for g in geo:
  1922. if type(g) == Polygon:
  1923. x, y = g.exterior.coords.xy
  1924. plot(x, y)
  1925. for ints in g.interiors:
  1926. x, y = ints.coords.xy
  1927. plot(x, y)
  1928. continue
  1929. if type(g) == LineString or type(g) == LinearRing:
  1930. x, y = g.coords.xy
  1931. plot(x, y)
  1932. continue
  1933. if type(g) == Point:
  1934. x, y = g.coords.xy
  1935. plot(x, y, 'o')
  1936. continue
  1937. try:
  1938. _ = iter(g)
  1939. plotg(g)
  1940. except:
  1941. print "Cannot plot:", str(type(g))
  1942. continue
  1943. def parse_gerber_number(strnumber, frac_digits):
  1944. """
  1945. Parse a single number of Gerber coordinates.
  1946. :param strnumber: String containing a number in decimal digits
  1947. from a coordinate data block, possibly with a leading sign.
  1948. :type strnumber: str
  1949. :param frac_digits: Number of digits used for the fractional
  1950. part of the number
  1951. :type frac_digits: int
  1952. :return: The number in floating point.
  1953. :rtype: float
  1954. """
  1955. return int(strnumber)*(10**(-frac_digits))