camlib.py 84 KB

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