camlib.py 91 KB

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