camlib.py 81 KB

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