ParseGerber.py 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202
  1. from camlib import Geometry, arc, arc_angle, ApertureMacro
  2. import FlatCAMApp
  3. import numpy as np
  4. import re
  5. import logging
  6. import traceback
  7. from copy import deepcopy
  8. import sys
  9. from shapely.ops import cascaded_union, unary_union
  10. from shapely.geometry import Polygon, MultiPolygon, LineString, Point
  11. import shapely.affinity as affinity
  12. from shapely.geometry import box as shply_box
  13. from lxml import etree as ET
  14. from flatcamParsers.ParseSVG import *
  15. import FlatCAMTranslation as fcTranslate
  16. import gettext
  17. import builtins
  18. if '_' not in builtins.__dict__:
  19. _ = gettext.gettext
  20. log = logging.getLogger('base')
  21. class Gerber(Geometry):
  22. """
  23. Here it is done all the Gerber parsing.
  24. **ATTRIBUTES**
  25. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  26. The values are dictionaries key/value pairs which describe the aperture. The
  27. type key is always present and the rest depend on the key:
  28. +-----------+-----------------------------------+
  29. | Key | Value |
  30. +===========+===================================+
  31. | type | (str) "C", "R", "O", "P", or "AP" |
  32. +-----------+-----------------------------------+
  33. | others | Depend on ``type`` |
  34. +-----------+-----------------------------------+
  35. | solid_geometry | (list) |
  36. +-----------+-----------------------------------+
  37. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  38. that can be instantiated with different parameters in an aperture
  39. definition. See ``apertures`` above. The key is the name of the macro,
  40. and the macro itself, the value, is a ``Aperture_Macro`` object.
  41. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  42. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  43. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  44. *buffering* (or thickening) the ``paths`` with the aperture. These are
  45. generated from ``paths`` in ``buffer_paths()``.
  46. **USAGE**::
  47. g = Gerber()
  48. g.parse_file(filename)
  49. g.create_geometry()
  50. do_something(s.solid_geometry)
  51. """
  52. # defaults = {
  53. # "steps_per_circle": 128,
  54. # "use_buffer_for_union": True
  55. # }
  56. app = None
  57. def __init__(self, steps_per_circle=None):
  58. """
  59. The constructor takes no parameters. Use ``gerber.parse_files()``
  60. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  61. :return: Gerber object
  62. :rtype: Gerber
  63. """
  64. # How to approximate a circle with lines.
  65. self.steps_per_circle = int(self.app.defaults["gerber_circle_steps"])
  66. self.decimals = self.app.decimals
  67. # Initialize parent
  68. Geometry.__init__(self, geo_steps_per_circle=self.steps_per_circle)
  69. # Number format
  70. self.int_digits = 3
  71. """Number of integer digits in Gerber numbers. Used during parsing."""
  72. self.frac_digits = 4
  73. """Number of fraction digits in Gerber numbers. Used during parsing."""
  74. self.gerber_zeros = self.app.defaults['gerber_def_zeros']
  75. """Zeros in Gerber numbers. If 'L' then remove leading zeros, if 'T' remove trailing zeros. Used during parsing.
  76. """
  77. # ## Gerber elements # ##
  78. '''
  79. apertures = {
  80. 'id':{
  81. 'type':string,
  82. 'size':float,
  83. 'width':float,
  84. 'height':float,
  85. 'geometry': [],
  86. }
  87. }
  88. apertures['geometry'] list elements are dicts
  89. dict = {
  90. 'solid': [],
  91. 'follow': [],
  92. 'clear': []
  93. }
  94. '''
  95. # store the file units here:
  96. self.units = self.app.defaults['gerber_def_units']
  97. # aperture storage
  98. self.apertures = {}
  99. # Aperture Macros
  100. self.aperture_macros = {}
  101. # will store the Gerber geometry's as solids
  102. self.solid_geometry = Polygon()
  103. # will store the Gerber geometry's as paths
  104. self.follow_geometry = []
  105. # made True when the LPC command is encountered in Gerber parsing
  106. # it allows adding data into the clear_geometry key of the self.apertures[aperture] dict
  107. self.is_lpc = False
  108. self.source_file = ''
  109. # Attributes to be included in serialization
  110. # Always append to it because it carries contents
  111. # from Geometry.
  112. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures',
  113. 'aperture_macros', 'solid_geometry', 'source_file']
  114. # ### Parser patterns ## ##
  115. # FS - Format Specification
  116. # The format of X and Y must be the same!
  117. # L-omit leading zeros, T-omit trailing zeros, D-no zero supression
  118. # A-absolute notation, I-incremental notation
  119. self.fmt_re = re.compile(r'%?FS([LTD])?([AI])X(\d)(\d)Y\d\d\*%?$')
  120. self.fmt_re_alt = re.compile(r'%FS([LTD])?([AI])X(\d)(\d)Y\d\d\*MO(IN|MM)\*%$')
  121. self.fmt_re_orcad = re.compile(r'(G\d+)*\**%FS([LTD])?([AI]).*X(\d)(\d)Y\d\d\*%$')
  122. # Mode (IN/MM)
  123. self.mode_re = re.compile(r'^%?MO(IN|MM)\*%?$')
  124. # Comment G04|G4
  125. self.comm_re = re.compile(r'^G0?4(.*)$')
  126. # AD - Aperture definition
  127. # Aperture Macro names: Name = [a-zA-Z_.$]{[a-zA-Z_.0-9]+}
  128. # NOTE: Adding "-" to support output from Upverter.
  129. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z_$\.][a-zA-Z0-9_$\.\-]*)(?:,(.*))?\*%$')
  130. # AM - Aperture Macro
  131. # Beginning of macro (Ends with *%):
  132. # self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  133. # Tool change
  134. # May begin with G54 but that is deprecated
  135. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  136. # G01... - Linear interpolation plus flashes with coordinates
  137. # Operation code (D0x) missing is deprecated... oh well I will support it.
  138. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  139. # Operation code alone, usually just D03 (Flash)
  140. self.opcode_re = re.compile(r'^D0?([123])\*$')
  141. # G02/3... - Circular interpolation with coordinates
  142. # 2-clockwise, 3-counterclockwise
  143. # Operation code (D0x) missing is deprecated... oh well I will support it.
  144. # Optional start with G02 or G03, optional end with D01 or D02 with
  145. # optional coordinates but at least one in any order.
  146. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))' +
  147. '?(?=.*I([\+-]?\d+))?(?=.*J([\+-]?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  148. # G01/2/3 Occurring without coordinates
  149. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  150. # Single G74 or multi G75 quadrant for circular interpolation
  151. self.quad_re = re.compile(r'^G7([45]).*\*$')
  152. # Region mode on
  153. # In region mode, D01 starts a region
  154. # and D02 ends it. A new region can be started again
  155. # with D01. All contours must be closed before
  156. # D02 or G37.
  157. self.regionon_re = re.compile(r'^G36\*$')
  158. # Region mode off
  159. # Will end a region and come off region mode.
  160. # All contours must be closed before D02 or G37.
  161. self.regionoff_re = re.compile(r'^G37\*$')
  162. # End of file
  163. self.eof_re = re.compile(r'^M02\*')
  164. # IP - Image polarity
  165. self.pol_re = re.compile(r'^%?IP(POS|NEG)\*%?$')
  166. # LP - Level polarity
  167. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  168. # Units (OBSOLETE)
  169. self.units_re = re.compile(r'^G7([01])\*$')
  170. # Absolute/Relative G90/1 (OBSOLETE)
  171. self.absrel_re = re.compile(r'^G9([01])\*$')
  172. # Aperture macros
  173. self.am1_re = re.compile(r'^%AM([^\*]+)\*([^%]+)?(%)?$')
  174. self.am2_re = re.compile(r'(.*)%$')
  175. # flag to store if a conversion was done. It is needed because multiple units declarations can be found
  176. # in a Gerber file (normal or obsolete ones)
  177. self.conversion_done = False
  178. self.use_buffer_for_union = self.app.defaults["gerber_use_buffer_for_union"]
  179. def aperture_parse(self, apertureId, apertureType, apParameters):
  180. """
  181. Parse gerber aperture definition into dictionary of apertures.
  182. The following kinds and their attributes are supported:
  183. * *Circular (C)*: size (float)
  184. * *Rectangle (R)*: width (float), height (float)
  185. * *Obround (O)*: width (float), height (float).
  186. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  187. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  188. :param apertureId: Id of the aperture being defined.
  189. :param apertureType: Type of the aperture.
  190. :param apParameters: Parameters of the aperture.
  191. :type apertureId: str
  192. :type apertureType: str
  193. :type apParameters: str
  194. :return: Identifier of the aperture.
  195. :rtype: str
  196. """
  197. if self.app.abort_flag:
  198. # graceful abort requested by the user
  199. raise FlatCAMApp.GracefulException
  200. # Found some Gerber with a leading zero in the aperture id and the
  201. # referenced it without the zero, so this is a hack to handle that.
  202. apid = str(int(apertureId))
  203. try: # Could be empty for aperture macros
  204. paramList = apParameters.split('X')
  205. except Exception:
  206. paramList = None
  207. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  208. self.apertures[apid] = {"type": "C",
  209. "size": float(paramList[0])}
  210. return apid
  211. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  212. self.apertures[apid] = {"type": "R",
  213. "width": float(paramList[0]),
  214. "height": float(paramList[1]),
  215. "size": np.sqrt(float(paramList[0]) ** 2 + float(paramList[1]) ** 2)} # Hack
  216. return apid
  217. if apertureType == "O": # Obround
  218. self.apertures[apid] = {"type": "O",
  219. "width": float(paramList[0]),
  220. "height": float(paramList[1]),
  221. "size": np.sqrt(float(paramList[0]) ** 2 + float(paramList[1]) ** 2)} # Hack
  222. return apid
  223. if apertureType == "P": # Polygon (regular)
  224. self.apertures[apid] = {"type": "P",
  225. "diam": float(paramList[0]),
  226. "nVertices": int(paramList[1]),
  227. "size": float(paramList[0])} # Hack
  228. if len(paramList) >= 3:
  229. self.apertures[apid]["rotation"] = float(paramList[2])
  230. return apid
  231. if apertureType in self.aperture_macros:
  232. self.apertures[apid] = {"type": "AM",
  233. "macro": self.aperture_macros[apertureType],
  234. "modifiers": paramList}
  235. return apid
  236. log.warning("Aperture not implemented: %s" % str(apertureType))
  237. return None
  238. def parse_file(self, filename, follow=False):
  239. """
  240. Calls Gerber.parse_lines() with generator of lines
  241. read from the given file. Will split the lines if multiple
  242. statements are found in a single original line.
  243. The following line is split into two::
  244. G54D11*G36*
  245. First is ``G54D11*`` and seconds is ``G36*``.
  246. :param filename: Gerber file to parse.
  247. :type filename: str
  248. :param follow: If true, will not create polygons, just lines
  249. following the gerber path.
  250. :type follow: bool
  251. :return: None
  252. """
  253. with open(filename, 'r') as gfile:
  254. def line_generator():
  255. for line in gfile:
  256. line = line.strip(' \r\n')
  257. while len(line) > 0:
  258. # If ends with '%' leave as is.
  259. if line[-1] == '%':
  260. yield line
  261. break
  262. # Split after '*' if any.
  263. starpos = line.find('*')
  264. if starpos > -1:
  265. cleanline = line[:starpos + 1]
  266. yield cleanline
  267. line = line[starpos + 1:]
  268. # Otherwise leave as is.
  269. else:
  270. # yield clean line
  271. yield line
  272. break
  273. processed_lines = list(line_generator())
  274. self.parse_lines(processed_lines)
  275. # @profile
  276. def parse_lines(self, glines):
  277. """
  278. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  279. ``self.flashes``, ``self.regions`` and ``self.units``.
  280. :param glines: Gerber code as list of strings, each element being
  281. one line of the source file.
  282. :type glines: list
  283. :return: None
  284. :rtype: None
  285. """
  286. # Coordinates of the current path, each is [x, y]
  287. path = []
  288. # this is for temporary storage of solid geometry until it is added to poly_buffer
  289. geo_s = None
  290. # this is for temporary storage of follow geometry until it is added to follow_buffer
  291. geo_f = None
  292. # Polygons are stored here until there is a change in polarity.
  293. # Only then they are combined via cascaded_union and added or
  294. # subtracted from solid_geometry. This is ~100 times faster than
  295. # applying a union for every new polygon.
  296. poly_buffer = []
  297. # store here the follow geometry
  298. follow_buffer = []
  299. last_path_aperture = None
  300. current_aperture = None
  301. # 1,2 or 3 from "G01", "G02" or "G03"
  302. current_interpolation_mode = None
  303. # 1 or 2 from "D01" or "D02"
  304. # Note this is to support deprecated Gerber not putting
  305. # an operation code at the end of every coordinate line.
  306. current_operation_code = None
  307. # Current coordinates
  308. current_x = None
  309. current_y = None
  310. previous_x = None
  311. previous_y = None
  312. current_d = None
  313. # Absolute or Relative/Incremental coordinates
  314. # Not implemented
  315. absolute = True
  316. # How to interpret circular interpolation: SINGLE or MULTI
  317. quadrant_mode = None
  318. # Indicates we are parsing an aperture macro
  319. current_macro = None
  320. # Indicates the current polarity: D-Dark, C-Clear
  321. current_polarity = 'D'
  322. # If a region is being defined
  323. making_region = False
  324. # ### Parsing starts here ## ##
  325. line_num = 0
  326. gline = ""
  327. s_tol = float(self.app.defaults["gerber_simp_tolerance"])
  328. self.app.inform.emit('%s %d %s.' % (_("Gerber processing. Parsing"), len(glines), _("lines")))
  329. try:
  330. for gline in glines:
  331. if self.app.abort_flag:
  332. # graceful abort requested by the user
  333. raise FlatCAMApp.GracefulException
  334. line_num += 1
  335. self.source_file += gline + '\n'
  336. # Cleanup #
  337. gline = gline.strip(' \r\n')
  338. # log.debug("Line=%3s %s" % (line_num, gline))
  339. # ###################
  340. # Ignored lines #####
  341. # Comments #####
  342. # ###################
  343. match = self.comm_re.search(gline)
  344. if match:
  345. continue
  346. # Polarity change ###### ##
  347. # Example: %LPD*% or %LPC*%
  348. # If polarity changes, creates geometry from current
  349. # buffer, then adds or subtracts accordingly.
  350. match = self.lpol_re.search(gline)
  351. if match:
  352. new_polarity = match.group(1)
  353. # log.info("Polarity CHANGE, LPC = %s, poly_buff = %s" % (self.is_lpc, poly_buffer))
  354. self.is_lpc = True if new_polarity == 'C' else False
  355. if len(path) > 1 and current_polarity != new_polarity:
  356. # finish the current path and add it to the storage
  357. # --- Buffered ----
  358. width = self.apertures[last_path_aperture]["size"]
  359. geo_dict = dict()
  360. geo_f = LineString(path)
  361. if not geo_f.is_empty:
  362. follow_buffer.append(geo_f)
  363. geo_dict['follow'] = geo_f
  364. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  365. if not geo_s.is_empty and geo_s.is_valid:
  366. if self.app.defaults['gerber_simplification']:
  367. poly_buffer.append(geo_s.simplify(s_tol))
  368. else:
  369. poly_buffer.append(geo_s)
  370. if self.is_lpc is True:
  371. geo_dict['clear'] = geo_s
  372. else:
  373. geo_dict['solid'] = geo_s
  374. if last_path_aperture not in self.apertures:
  375. self.apertures[last_path_aperture] = dict()
  376. if 'geometry' not in self.apertures[last_path_aperture]:
  377. self.apertures[last_path_aperture]['geometry'] = []
  378. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  379. path = [path[-1]]
  380. # --- Apply buffer ---
  381. # If added for testing of bug #83
  382. # TODO: Remove when bug fixed
  383. if len(poly_buffer) > 0:
  384. if current_polarity == 'D':
  385. # self.follow_geometry = self.follow_geometry.union(cascaded_union(follow_buffer))
  386. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  387. else:
  388. # self.follow_geometry = self.follow_geometry.difference(cascaded_union(follow_buffer))
  389. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  390. # follow_buffer = []
  391. poly_buffer = []
  392. current_polarity = new_polarity
  393. continue
  394. # ############################################################# ##
  395. # Number format ############################################### ##
  396. # Example: %FSLAX24Y24*%
  397. # ############################################################# ##
  398. # TODO: This is ignoring most of the format. Implement the rest.
  399. match = self.fmt_re.search(gline)
  400. if match:
  401. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(2)]
  402. if match.group(1) is not None:
  403. self.gerber_zeros = match.group(1)
  404. self.int_digits = int(match.group(3))
  405. self.frac_digits = int(match.group(4))
  406. log.debug("Gerber format found. (%s) " % str(gline))
  407. log.debug(
  408. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros, "
  409. "D-no zero supression)" % self.gerber_zeros)
  410. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  411. continue
  412. # ## Mode (IN/MM)
  413. # Example: %MOIN*%
  414. match = self.mode_re.search(gline)
  415. if match:
  416. self.units = match.group(1)
  417. log.debug("Gerber units found = %s" % self.units)
  418. # Changed for issue #80
  419. # self.convert_units(match.group(1))
  420. self.conversion_done = True
  421. continue
  422. # ############################################################# ##
  423. # Combined Number format and Mode --- Allegro does this ####### ##
  424. # ############################################################# ##
  425. match = self.fmt_re_alt.search(gline)
  426. if match:
  427. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(2)]
  428. if match.group(1) is not None:
  429. self.gerber_zeros = match.group(1)
  430. self.int_digits = int(match.group(3))
  431. self.frac_digits = int(match.group(4))
  432. log.debug("Gerber format found. (%s) " % str(gline))
  433. log.debug(
  434. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros, "
  435. "D-no zero suppression)" % self.gerber_zeros)
  436. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  437. self.units = match.group(5)
  438. log.debug("Gerber units found = %s" % self.units)
  439. # Changed for issue #80
  440. # self.convert_units(match.group(5))
  441. self.conversion_done = True
  442. continue
  443. # ############################################################# ##
  444. # Search for OrCAD way for having Number format
  445. # ############################################################# ##
  446. match = self.fmt_re_orcad.search(gline)
  447. if match:
  448. if match.group(1) is not None:
  449. if match.group(1) == 'G74':
  450. quadrant_mode = 'SINGLE'
  451. elif match.group(1) == 'G75':
  452. quadrant_mode = 'MULTI'
  453. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(3)]
  454. if match.group(2) is not None:
  455. self.gerber_zeros = match.group(2)
  456. self.int_digits = int(match.group(4))
  457. self.frac_digits = int(match.group(5))
  458. log.debug("Gerber format found. (%s) " % str(gline))
  459. log.debug(
  460. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros, "
  461. "D-no zerosuppressionn)" % self.gerber_zeros)
  462. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  463. self.units = match.group(1)
  464. log.debug("Gerber units found = %s" % self.units)
  465. # Changed for issue #80
  466. # self.convert_units(match.group(5))
  467. self.conversion_done = True
  468. continue
  469. # ############################################################# ##
  470. # Units (G70/1) OBSOLETE
  471. # ############################################################# ##
  472. match = self.units_re.search(gline)
  473. if match:
  474. obs_gerber_units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  475. log.warning("Gerber obsolete units found = %s" % obs_gerber_units)
  476. # Changed for issue #80
  477. # self.convert_units({'0': 'IN', '1': 'MM'}[match.group(1)])
  478. self.conversion_done = True
  479. continue
  480. # ############################################################# ##
  481. # Absolute/relative coordinates G90/1 OBSOLETE ######## ##
  482. # ##################################################### ##
  483. match = self.absrel_re.search(gline)
  484. if match:
  485. absolute = {'0': "Absolute", '1': "Relative"}[match.group(1)]
  486. log.warning("Gerber obsolete coordinates type found = %s (Absolute or Relative) " % absolute)
  487. continue
  488. # ############################################################# ##
  489. # Aperture Macros ##################################### ##
  490. # Having this at the beginning will slow things down
  491. # but macros can have complicated statements than could
  492. # be caught by other patterns.
  493. # ############################################################# ##
  494. if current_macro is None: # No macro started yet
  495. match = self.am1_re.search(gline)
  496. # Start macro if match, else not an AM, carry on.
  497. if match:
  498. log.debug("Starting macro. Line %d: %s" % (line_num, gline))
  499. current_macro = match.group(1)
  500. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  501. if match.group(2): # Append
  502. self.aperture_macros[current_macro].append(match.group(2))
  503. if match.group(3): # Finish macro
  504. # self.aperture_macros[current_macro].parse_content()
  505. current_macro = None
  506. log.debug("Macro complete in 1 line.")
  507. continue
  508. else: # Continue macro
  509. log.debug("Continuing macro. Line %d." % line_num)
  510. match = self.am2_re.search(gline)
  511. if match: # Finish macro
  512. log.debug("End of macro. Line %d." % line_num)
  513. self.aperture_macros[current_macro].append(match.group(1))
  514. # self.aperture_macros[current_macro].parse_content()
  515. current_macro = None
  516. else: # Append
  517. self.aperture_macros[current_macro].append(gline)
  518. continue
  519. # ## Aperture definitions %ADD...
  520. match = self.ad_re.search(gline)
  521. if match:
  522. # log.info("Found aperture definition. Line %d: %s" % (line_num, gline))
  523. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  524. continue
  525. # ############################################################# ##
  526. # Operation code alone ###################### ##
  527. # Operation code alone, usually just D03 (Flash)
  528. # self.opcode_re = re.compile(r'^D0?([123])\*$')
  529. # ############################################################# ##
  530. match = self.opcode_re.search(gline)
  531. if match:
  532. current_operation_code = int(match.group(1))
  533. current_d = current_operation_code
  534. if current_operation_code == 3:
  535. # --- Buffered ---
  536. try:
  537. # log.debug("Bare op-code %d." % current_operation_code)
  538. geo_dict = dict()
  539. flash = self.create_flash_geometry(
  540. Point(current_x, current_y), self.apertures[current_aperture],
  541. self.steps_per_circle)
  542. geo_dict['follow'] = Point([current_x, current_y])
  543. if not flash.is_empty:
  544. if self.app.defaults['gerber_simplification']:
  545. poly_buffer.append(flash.simplify(s_tol))
  546. else:
  547. poly_buffer.append(flash)
  548. if self.is_lpc is True:
  549. geo_dict['clear'] = flash
  550. else:
  551. geo_dict['solid'] = flash
  552. if current_aperture not in self.apertures:
  553. self.apertures[current_aperture] = dict()
  554. if 'geometry' not in self.apertures[current_aperture]:
  555. self.apertures[current_aperture]['geometry'] = []
  556. self.apertures[current_aperture]['geometry'].append(deepcopy(geo_dict))
  557. except IndexError:
  558. log.warning("Line %d: %s -> Nothing there to flash!" % (line_num, gline))
  559. continue
  560. # ############################################################# ##
  561. # Tool/aperture change
  562. # Example: D12*
  563. # ############################################################# ##
  564. match = self.tool_re.search(gline)
  565. if match:
  566. current_aperture = match.group(1)
  567. # log.debug("Line %d: Aperture change to (%s)" % (line_num, current_aperture))
  568. # If the aperture value is zero then make it something quite small but with a non-zero value
  569. # so it can be processed by FlatCAM.
  570. # But first test to see if the aperture type is "aperture macro". In that case
  571. # we should not test for "size" key as it does not exist in this case.
  572. if self.apertures[current_aperture]["type"] is not "AM":
  573. if self.apertures[current_aperture]["size"] == 0:
  574. self.apertures[current_aperture]["size"] = 1e-12
  575. # log.debug(self.apertures[current_aperture])
  576. # Take care of the current path with the previous tool
  577. if len(path) > 1:
  578. if self.apertures[last_path_aperture]["type"] == 'R':
  579. # do nothing because 'R' type moving aperture is none at once
  580. pass
  581. else:
  582. geo_dict = dict()
  583. geo_f = LineString(path)
  584. if not geo_f.is_empty:
  585. follow_buffer.append(geo_f)
  586. geo_dict['follow'] = geo_f
  587. # --- Buffered ----
  588. width = self.apertures[last_path_aperture]["size"]
  589. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  590. if not geo_s.is_empty:
  591. if self.app.defaults['gerber_simplification']:
  592. poly_buffer.append(geo_s.simplify(s_tol))
  593. else:
  594. poly_buffer.append(geo_s)
  595. if self.is_lpc is True:
  596. geo_dict['clear'] = geo_s
  597. else:
  598. geo_dict['solid'] = geo_s
  599. if last_path_aperture not in self.apertures:
  600. self.apertures[last_path_aperture] = dict()
  601. if 'geometry' not in self.apertures[last_path_aperture]:
  602. self.apertures[last_path_aperture]['geometry'] = []
  603. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  604. path = [path[-1]]
  605. continue
  606. # ############################################################# ##
  607. # G36* - Begin region
  608. # ############################################################# ##
  609. if self.regionon_re.search(gline):
  610. if len(path) > 1:
  611. # Take care of what is left in the path
  612. geo_dict = dict()
  613. geo_f = LineString(path)
  614. if not geo_f.is_empty:
  615. follow_buffer.append(geo_f)
  616. geo_dict['follow'] = geo_f
  617. # --- Buffered ----
  618. width = self.apertures[last_path_aperture]["size"]
  619. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  620. if not geo_s.is_empty:
  621. if self.app.defaults['gerber_simplification']:
  622. poly_buffer.append(geo_s.simplify(s_tol))
  623. else:
  624. poly_buffer.append(geo_s)
  625. if self.is_lpc is True:
  626. geo_dict['clear'] = geo_s
  627. else:
  628. geo_dict['solid'] = geo_s
  629. if last_path_aperture not in self.apertures:
  630. self.apertures[last_path_aperture] = dict()
  631. if 'geometry' not in self.apertures[last_path_aperture]:
  632. self.apertures[last_path_aperture]['geometry'] = []
  633. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  634. path = [path[-1]]
  635. making_region = True
  636. continue
  637. # ############################################################# ##
  638. # G37* - End region
  639. # ############################################################# ##
  640. if self.regionoff_re.search(gline):
  641. making_region = False
  642. if '0' not in self.apertures:
  643. self.apertures['0'] = {}
  644. self.apertures['0']['type'] = 'REG'
  645. self.apertures['0']['size'] = 0.0
  646. self.apertures['0']['geometry'] = list()
  647. # if D02 happened before G37 we now have a path with 1 element only; we have to add the current
  648. # geo to the poly_buffer otherwise we loose it
  649. if current_operation_code == 2:
  650. if len(path) == 1:
  651. # this means that the geometry was prepared previously and we just need to add it
  652. geo_dict = dict()
  653. if geo_f:
  654. if not geo_f.is_empty:
  655. follow_buffer.append(geo_f)
  656. geo_dict['follow'] = geo_f
  657. if geo_s:
  658. if not geo_s.is_empty:
  659. if self.app.defaults['gerber_simplification']:
  660. poly_buffer.append(geo_s.simplify(s_tol))
  661. else:
  662. poly_buffer.append(geo_s)
  663. if self.is_lpc is True:
  664. geo_dict['clear'] = geo_s
  665. else:
  666. geo_dict['solid'] = geo_s
  667. if geo_s or geo_f:
  668. self.apertures['0']['geometry'].append(deepcopy(geo_dict))
  669. path = [[current_x, current_y]] # Start new path
  670. # Only one path defines region?
  671. # This can happen if D02 happened before G37 and
  672. # is not and error.
  673. if len(path) < 3:
  674. # print "ERROR: Path contains less than 3 points:"
  675. # path = [[current_x, current_y]]
  676. continue
  677. # For regions we may ignore an aperture that is None
  678. # --- Buffered ---
  679. geo_dict = dict()
  680. region_f = Polygon(path).exterior
  681. if not region_f.is_empty:
  682. follow_buffer.append(region_f)
  683. geo_dict['follow'] = region_f
  684. region_s = Polygon(path)
  685. if not region_s.is_valid:
  686. region_s = region_s.buffer(0, int(self.steps_per_circle / 4))
  687. if not region_s.is_empty:
  688. if self.app.defaults['gerber_simplification']:
  689. poly_buffer.append(region_s.simplify(s_tol))
  690. else:
  691. poly_buffer.append(region_s)
  692. if self.is_lpc is True:
  693. geo_dict['clear'] = region_s
  694. else:
  695. geo_dict['solid'] = region_s
  696. if not region_s.is_empty or not region_f.is_empty:
  697. self.apertures['0']['geometry'].append(deepcopy(geo_dict))
  698. path = [[current_x, current_y]] # Start new path
  699. continue
  700. # ## G01/2/3* - Interpolation mode change
  701. # Can occur along with coordinates and operation code but
  702. # sometimes by itself (handled here).
  703. # Example: G01*
  704. match = self.interp_re.search(gline)
  705. if match:
  706. current_interpolation_mode = int(match.group(1))
  707. continue
  708. # ## G01 - Linear interpolation plus flashes
  709. # Operation code (D0x) missing is deprecated... oh well I will support it.
  710. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  711. match = self.lin_re.search(gline)
  712. if match:
  713. # Dxx alone?
  714. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  715. # try:
  716. # current_operation_code = int(match.group(4))
  717. # except Exception:
  718. # pass # A line with just * will match too.
  719. # continue
  720. # NOTE: Letting it continue allows it to react to the
  721. # operation code.
  722. # Parse coordinates
  723. if match.group(2) is not None:
  724. linear_x = parse_gerber_number(match.group(2),
  725. self.int_digits, self.frac_digits, self.gerber_zeros)
  726. current_x = linear_x
  727. else:
  728. linear_x = current_x
  729. if match.group(3) is not None:
  730. linear_y = parse_gerber_number(match.group(3),
  731. self.int_digits, self.frac_digits, self.gerber_zeros)
  732. current_y = linear_y
  733. else:
  734. linear_y = current_y
  735. # Parse operation code
  736. if match.group(4) is not None:
  737. current_operation_code = int(match.group(4))
  738. # Pen down: add segment
  739. if current_operation_code == 1:
  740. # if linear_x or linear_y are None, ignore those
  741. if current_x is not None and current_y is not None:
  742. # only add the point if it's a new one otherwise skip it (harder to process)
  743. if path[-1] != [current_x, current_y]:
  744. path.append([current_x, current_y])
  745. if making_region is False:
  746. # if the aperture is rectangle then add a rectangular shape having as parameters the
  747. # coordinates of the start and end point and also the width and height
  748. # of the 'R' aperture
  749. try:
  750. if self.apertures[current_aperture]["type"] == 'R':
  751. width = self.apertures[current_aperture]['width']
  752. height = self.apertures[current_aperture]['height']
  753. minx = min(path[0][0], path[1][0]) - width / 2
  754. maxx = max(path[0][0], path[1][0]) + width / 2
  755. miny = min(path[0][1], path[1][1]) - height / 2
  756. maxy = max(path[0][1], path[1][1]) + height / 2
  757. log.debug("Coords: %s - %s - %s - %s" % (minx, miny, maxx, maxy))
  758. geo_dict = dict()
  759. geo_f = Point([current_x, current_y])
  760. follow_buffer.append(geo_f)
  761. geo_dict['follow'] = geo_f
  762. geo_s = shply_box(minx, miny, maxx, maxy)
  763. if self.app.defaults['gerber_simplification']:
  764. poly_buffer.append(geo_s.simplify(s_tol))
  765. else:
  766. poly_buffer.append(geo_s)
  767. if self.is_lpc is True:
  768. geo_dict['clear'] = geo_s
  769. else:
  770. geo_dict['solid'] = geo_s
  771. if current_aperture not in self.apertures:
  772. self.apertures[current_aperture] = dict()
  773. if 'geometry' not in self.apertures[current_aperture]:
  774. self.apertures[current_aperture]['geometry'] = []
  775. self.apertures[current_aperture]['geometry'].append(deepcopy(geo_dict))
  776. except Exception as e:
  777. pass
  778. last_path_aperture = current_aperture
  779. # we do this for the case that a region is done without having defined any aperture
  780. if last_path_aperture is None:
  781. if '0' not in self.apertures:
  782. self.apertures['0'] = {}
  783. self.apertures['0']['type'] = 'REG'
  784. self.apertures['0']['size'] = 0.0
  785. self.apertures['0']['geometry'] = []
  786. last_path_aperture = '0'
  787. else:
  788. self.app.inform.emit('[WARNING] %s: %s' %
  789. (_("Coordinates missing, line ignored"), str(gline)))
  790. self.app.inform.emit('[WARNING_NOTCL] %s' %
  791. _("GERBER file might be CORRUPT. Check the file !!!"))
  792. elif current_operation_code == 2:
  793. if len(path) > 1:
  794. geo_s = None
  795. geo_dict = dict()
  796. # --- BUFFERED ---
  797. # this treats the case when we are storing geometry as paths only
  798. if making_region:
  799. # we do this for the case that a region is done without having defined any aperture
  800. if last_path_aperture is None:
  801. if '0' not in self.apertures:
  802. self.apertures['0'] = {}
  803. self.apertures['0']['type'] = 'REG'
  804. self.apertures['0']['size'] = 0.0
  805. self.apertures['0']['geometry'] = []
  806. last_path_aperture = '0'
  807. geo_f = Polygon()
  808. else:
  809. geo_f = LineString(path)
  810. try:
  811. if self.apertures[last_path_aperture]["type"] != 'R':
  812. if not geo_f.is_empty:
  813. follow_buffer.append(geo_f)
  814. geo_dict['follow'] = geo_f
  815. except Exception as e:
  816. log.debug("camlib.Gerber.parse_lines() --> %s" % str(e))
  817. if not geo_f.is_empty:
  818. follow_buffer.append(geo_f)
  819. geo_dict['follow'] = geo_f
  820. # this treats the case when we are storing geometry as solids
  821. if making_region:
  822. # we do this for the case that a region is done without having defined any aperture
  823. if last_path_aperture is None:
  824. if '0' not in self.apertures:
  825. self.apertures['0'] = {}
  826. self.apertures['0']['type'] = 'REG'
  827. self.apertures['0']['size'] = 0.0
  828. self.apertures['0']['geometry'] = []
  829. last_path_aperture = '0'
  830. try:
  831. geo_s = Polygon(path)
  832. except ValueError:
  833. log.warning("Problem %s %s" % (gline, line_num))
  834. self.app.inform.emit('[ERROR] %s: %s' %
  835. (_("Region does not have enough points. "
  836. "File will be processed but there are parser errors. "
  837. "Line number"), str(line_num)))
  838. else:
  839. if last_path_aperture is None:
  840. log.warning("No aperture defined for curent path. (%d)" % line_num)
  841. width = self.apertures[last_path_aperture]["size"] # TODO: WARNING this should fail!
  842. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  843. try:
  844. if self.apertures[last_path_aperture]["type"] != 'R':
  845. if not geo_s.is_empty:
  846. if self.app.defaults['gerber_simplification']:
  847. poly_buffer.append(geo_s.simplify(s_tol))
  848. else:
  849. poly_buffer.append(geo_s)
  850. if self.is_lpc is True:
  851. geo_dict['clear'] = geo_s
  852. else:
  853. geo_dict['solid'] = geo_s
  854. except Exception as e:
  855. log.debug("camlib.Gerber.parse_lines() --> %s" % str(e))
  856. if self.app.defaults['gerber_simplification']:
  857. poly_buffer.append(geo_s.simplify(s_tol))
  858. else:
  859. poly_buffer.append(geo_s)
  860. if self.is_lpc is True:
  861. geo_dict['clear'] = geo_s
  862. else:
  863. geo_dict['solid'] = geo_s
  864. if last_path_aperture not in self.apertures:
  865. self.apertures[last_path_aperture] = dict()
  866. if 'geometry' not in self.apertures[last_path_aperture]:
  867. self.apertures[last_path_aperture]['geometry'] = []
  868. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  869. # if linear_x or linear_y are None, ignore those
  870. if linear_x is not None and linear_y is not None:
  871. path = [[linear_x, linear_y]] # Start new path
  872. else:
  873. self.app.inform.emit('[WARNING] %s: %s' %
  874. (_("Coordinates missing, line ignored"), str(gline)))
  875. self.app.inform.emit('[WARNING_NOTCL] %s' %
  876. _("GERBER file might be CORRUPT. Check the file !!!"))
  877. # Flash
  878. # Not allowed in region mode.
  879. elif current_operation_code == 3:
  880. # Create path draw so far.
  881. if len(path) > 1:
  882. # --- Buffered ----
  883. geo_dict = dict()
  884. # this treats the case when we are storing geometry as paths
  885. geo_f = LineString(path)
  886. if not geo_f.is_empty:
  887. try:
  888. if self.apertures[last_path_aperture]["type"] != 'R':
  889. follow_buffer.append(geo_f)
  890. geo_dict['follow'] = geo_f
  891. except Exception as e:
  892. log.debug("camlib.Gerber.parse_lines() --> G01 match D03 --> %s" % str(e))
  893. follow_buffer.append(geo_f)
  894. geo_dict['follow'] = geo_f
  895. # this treats the case when we are storing geometry as solids
  896. width = self.apertures[last_path_aperture]["size"]
  897. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  898. if not geo_s.is_empty:
  899. try:
  900. if self.apertures[last_path_aperture]["type"] != 'R':
  901. if self.app.defaults['gerber_simplification']:
  902. poly_buffer.append(geo_s.simplify(s_tol))
  903. else:
  904. poly_buffer.append(geo_s)
  905. if self.is_lpc is True:
  906. geo_dict['clear'] = geo_s
  907. else:
  908. geo_dict['solid'] = geo_s
  909. except Exception:
  910. if self.app.defaults['gerber_simplification']:
  911. poly_buffer.append(geo_s.simplify(s_tol))
  912. else:
  913. poly_buffer.append(geo_s)
  914. if self.is_lpc is True:
  915. geo_dict['clear'] = geo_s
  916. else:
  917. geo_dict['solid'] = geo_s
  918. if last_path_aperture not in self.apertures:
  919. self.apertures[last_path_aperture] = dict()
  920. if 'geometry' not in self.apertures[last_path_aperture]:
  921. self.apertures[last_path_aperture]['geometry'] = []
  922. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  923. # Reset path starting point
  924. path = [[linear_x, linear_y]]
  925. # --- BUFFERED ---
  926. # Draw the flash
  927. # this treats the case when we are storing geometry as paths
  928. geo_dict = dict()
  929. geo_flash = Point([linear_x, linear_y])
  930. follow_buffer.append(geo_flash)
  931. geo_dict['follow'] = geo_flash
  932. # this treats the case when we are storing geometry as solids
  933. flash = self.create_flash_geometry(
  934. Point([linear_x, linear_y]),
  935. self.apertures[current_aperture],
  936. self.steps_per_circle
  937. )
  938. if not flash.is_empty:
  939. if self.app.defaults['gerber_simplification']:
  940. poly_buffer.append(flash.simplify(s_tol))
  941. else:
  942. poly_buffer.append(flash)
  943. if self.is_lpc is True:
  944. geo_dict['clear'] = flash
  945. else:
  946. geo_dict['solid'] = flash
  947. if current_aperture not in self.apertures:
  948. self.apertures[current_aperture] = dict()
  949. if 'geometry' not in self.apertures[current_aperture]:
  950. self.apertures[current_aperture]['geometry'] = []
  951. self.apertures[current_aperture]['geometry'].append(deepcopy(geo_dict))
  952. # maybe those lines are not exactly needed but it is easier to read the program as those coordinates
  953. # are used in case that circular interpolation is encountered within the Gerber file
  954. current_x = linear_x
  955. current_y = linear_y
  956. # log.debug("Line_number=%3s X=%s Y=%s (%s)" % (line_num, linear_x, linear_y, gline))
  957. continue
  958. # ## G74/75* - Single or multiple quadrant arcs
  959. match = self.quad_re.search(gline)
  960. if match:
  961. if match.group(1) == '4':
  962. quadrant_mode = 'SINGLE'
  963. else:
  964. quadrant_mode = 'MULTI'
  965. continue
  966. # ## G02/3 - Circular interpolation
  967. # 2-clockwise, 3-counterclockwise
  968. # Ex. format: G03 X0 Y50 I-50 J0 where the X, Y coords are the coords of the End Point
  969. match = self.circ_re.search(gline)
  970. if match:
  971. arcdir = [None, None, "cw", "ccw"]
  972. mode, circular_x, circular_y, i, j, d = match.groups()
  973. try:
  974. circular_x = parse_gerber_number(circular_x,
  975. self.int_digits, self.frac_digits, self.gerber_zeros)
  976. except Exception as e:
  977. circular_x = current_x
  978. try:
  979. circular_y = parse_gerber_number(circular_y,
  980. self.int_digits, self.frac_digits, self.gerber_zeros)
  981. except Exception as e:
  982. circular_y = current_y
  983. # According to Gerber specification i and j are not modal, which means that when i or j are missing,
  984. # they are to be interpreted as being zero
  985. try:
  986. i = parse_gerber_number(i, self.int_digits, self.frac_digits, self.gerber_zeros)
  987. except Exception as e:
  988. i = 0
  989. try:
  990. j = parse_gerber_number(j, self.int_digits, self.frac_digits, self.gerber_zeros)
  991. except Exception as e:
  992. j = 0
  993. if quadrant_mode is None:
  994. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  995. log.error(gline)
  996. continue
  997. if mode is None and current_interpolation_mode not in [2, 3]:
  998. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  999. log.error(gline)
  1000. continue
  1001. elif mode is not None:
  1002. current_interpolation_mode = int(mode)
  1003. # Set operation code if provided
  1004. if d is not None:
  1005. current_operation_code = int(d)
  1006. # Nothing created! Pen Up.
  1007. if current_operation_code == 2:
  1008. log.warning("Arc with D2. (%d)" % line_num)
  1009. if len(path) > 1:
  1010. geo_dict = dict()
  1011. if last_path_aperture is None:
  1012. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1013. # --- BUFFERED ---
  1014. width = self.apertures[last_path_aperture]["size"]
  1015. # this treats the case when we are storing geometry as paths
  1016. geo_f = LineString(path)
  1017. if not geo_f.is_empty:
  1018. follow_buffer.append(geo_f)
  1019. geo_dict['follow'] = geo_f
  1020. # this treats the case when we are storing geometry as solids
  1021. buffered = LineString(path).buffer(width / 1.999, int(self.steps_per_circle))
  1022. if not buffered.is_empty:
  1023. if self.app.defaults['gerber_simplification']:
  1024. poly_buffer.append(buffered.simplify(s_tol))
  1025. else:
  1026. poly_buffer.append(buffered)
  1027. if self.is_lpc is True:
  1028. geo_dict['clear'] = buffered
  1029. else:
  1030. geo_dict['solid'] = buffered
  1031. if last_path_aperture not in self.apertures:
  1032. self.apertures[last_path_aperture] = dict()
  1033. if 'geometry' not in self.apertures[last_path_aperture]:
  1034. self.apertures[last_path_aperture]['geometry'] = []
  1035. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  1036. current_x = circular_x
  1037. current_y = circular_y
  1038. path = [[current_x, current_y]] # Start new path
  1039. continue
  1040. # Flash should not happen here
  1041. if current_operation_code == 3:
  1042. log.error("Trying to flash within arc. (%d)" % line_num)
  1043. continue
  1044. if quadrant_mode == 'MULTI':
  1045. center = [i + current_x, j + current_y]
  1046. radius = np.sqrt(i ** 2 + j ** 2)
  1047. start = np.arctan2(-j, -i) # Start angle
  1048. # Numerical errors might prevent start == stop therefore
  1049. # we check ahead of time. This should result in a
  1050. # 360 degree arc.
  1051. if current_x == circular_x and current_y == circular_y:
  1052. stop = start
  1053. else:
  1054. stop = np.arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  1055. this_arc = arc(center, radius, start, stop,
  1056. arcdir[current_interpolation_mode],
  1057. self.steps_per_circle)
  1058. # The last point in the computed arc can have
  1059. # numerical errors. The exact final point is the
  1060. # specified (x, y). Replace.
  1061. this_arc[-1] = (circular_x, circular_y)
  1062. # Last point in path is current point
  1063. # current_x = this_arc[-1][0]
  1064. # current_y = this_arc[-1][1]
  1065. current_x, current_y = circular_x, circular_y
  1066. # Append
  1067. path += this_arc
  1068. last_path_aperture = current_aperture
  1069. continue
  1070. if quadrant_mode == 'SINGLE':
  1071. center_candidates = [
  1072. [i + current_x, j + current_y],
  1073. [-i + current_x, j + current_y],
  1074. [i + current_x, -j + current_y],
  1075. [-i + current_x, -j + current_y]
  1076. ]
  1077. valid = False
  1078. log.debug("I: %f J: %f" % (i, j))
  1079. for center in center_candidates:
  1080. radius = np.sqrt(i ** 2 + j ** 2)
  1081. # Make sure radius to start is the same as radius to end.
  1082. radius2 = np.sqrt((center[0] - circular_x) ** 2 + (center[1] - circular_y) ** 2)
  1083. if radius2 < radius * 0.95 or radius2 > radius * 1.05:
  1084. continue # Not a valid center.
  1085. # Correct i and j and continue as with multi-quadrant.
  1086. i = center[0] - current_x
  1087. j = center[1] - current_y
  1088. start = np.arctan2(-j, -i) # Start angle
  1089. stop = np.arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  1090. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  1091. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  1092. (current_x, current_y, center[0], center[1], circular_x, circular_y))
  1093. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  1094. (start * 180 / np.pi, stop * 180 / np.pi, arcdir[current_interpolation_mode],
  1095. angle * 180 / np.pi, np.pi / 2 * 180 / np.pi, angle <= (np.pi + 1e-6) / 2))
  1096. if angle <= (np.pi + 1e-6) / 2:
  1097. log.debug("########## ACCEPTING ARC ############")
  1098. this_arc = arc(center, radius, start, stop,
  1099. arcdir[current_interpolation_mode],
  1100. self.steps_per_circle)
  1101. # Replace with exact values
  1102. this_arc[-1] = (circular_x, circular_y)
  1103. # current_x = this_arc[-1][0]
  1104. # current_y = this_arc[-1][1]
  1105. current_x, current_y = circular_x, circular_y
  1106. path += this_arc
  1107. last_path_aperture = current_aperture
  1108. valid = True
  1109. break
  1110. if valid:
  1111. continue
  1112. else:
  1113. log.warning("Invalid arc in line %d." % line_num)
  1114. # ## EOF
  1115. match = self.eof_re.search(gline)
  1116. if match:
  1117. continue
  1118. # ## Line did not match any pattern. Warn user.
  1119. log.warning("Line ignored (%d): %s" % (line_num, gline))
  1120. if len(path) > 1:
  1121. # In case that G01 (moving) aperture is rectangular, there is no need to still create
  1122. # another geo since we already created a shapely box using the start and end coordinates found in
  1123. # path variable. We do it only for other apertures than 'R' type
  1124. if self.apertures[last_path_aperture]["type"] == 'R':
  1125. pass
  1126. else:
  1127. # EOF, create shapely LineString if something still in path
  1128. # ## --- Buffered ---
  1129. geo_dict = dict()
  1130. # this treats the case when we are storing geometry as paths
  1131. geo_f = LineString(path)
  1132. if not geo_f.is_empty:
  1133. follow_buffer.append(geo_f)
  1134. geo_dict['follow'] = geo_f
  1135. # this treats the case when we are storing geometry as solids
  1136. width = self.apertures[last_path_aperture]["size"]
  1137. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  1138. if not geo_s.is_empty:
  1139. if self.app.defaults['gerber_simplification']:
  1140. poly_buffer.append(geo_s.simplify(s_tol))
  1141. else:
  1142. poly_buffer.append(geo_s)
  1143. if self.is_lpc is True:
  1144. geo_dict['clear'] = geo_s
  1145. else:
  1146. geo_dict['solid'] = geo_s
  1147. if last_path_aperture not in self.apertures:
  1148. self.apertures[last_path_aperture] = dict()
  1149. if 'geometry' not in self.apertures[last_path_aperture]:
  1150. self.apertures[last_path_aperture]['geometry'] = []
  1151. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  1152. # --- Apply buffer ---
  1153. # this treats the case when we are storing geometry as paths
  1154. self.follow_geometry = follow_buffer
  1155. # this treats the case when we are storing geometry as solids
  1156. if len(poly_buffer) == 0 and len(self.solid_geometry) == 0:
  1157. log.error("Object is not Gerber file or empty. Aborting Object creation.")
  1158. return 'fail'
  1159. log.warning("Joining %d polygons." % len(poly_buffer))
  1160. self.app.inform.emit('%s: %d.' % (_("Gerber processing. Joining polygons"), len(poly_buffer)))
  1161. if self.use_buffer_for_union:
  1162. log.debug("Union by buffer...")
  1163. new_poly = MultiPolygon(poly_buffer)
  1164. if self.app.defaults["gerber_buffering"] == 'full':
  1165. new_poly = new_poly.buffer(0.00000001)
  1166. new_poly = new_poly.buffer(-0.00000001)
  1167. log.warning("Union(buffer) done.")
  1168. else:
  1169. log.debug("Union by union()...")
  1170. new_poly = cascaded_union(poly_buffer)
  1171. new_poly = new_poly.buffer(0, int(self.steps_per_circle / 4))
  1172. log.warning("Union done.")
  1173. if current_polarity == 'D':
  1174. self.app.inform.emit('%s' % _("Gerber processing. Applying Gerber polarity."))
  1175. if new_poly.is_valid:
  1176. self.solid_geometry = self.solid_geometry.union(new_poly)
  1177. else:
  1178. # I do this so whenever the parsed geometry of the file is not valid (intersections) it is still
  1179. # loaded. Instead of applying a union I add to a list of polygons.
  1180. final_poly = []
  1181. try:
  1182. for poly in new_poly:
  1183. final_poly.append(poly)
  1184. except TypeError:
  1185. final_poly.append(new_poly)
  1186. try:
  1187. for poly in self.solid_geometry:
  1188. final_poly.append(poly)
  1189. except TypeError:
  1190. final_poly.append(self.solid_geometry)
  1191. self.solid_geometry = final_poly
  1192. # FIX for issue #347 - Sprint Layout generate strange Gerber files when the copper pour is enabled
  1193. # it use a filled bounding box polygon to which add clear polygons (negative) to isolate the copper
  1194. # features
  1195. if self.app.defaults['gerber_extra_buffering']:
  1196. candidate_geo = list()
  1197. try:
  1198. for p in self.solid_geometry:
  1199. candidate_geo.append(p.buffer(0.0000001))
  1200. except TypeError:
  1201. candidate_geo.append(self.solid_geometry.buffer(0.0000001))
  1202. self.solid_geometry = candidate_geo
  1203. # try:
  1204. # self.solid_geometry = self.solid_geometry.union(new_poly)
  1205. # except Exception as e:
  1206. # # in case in the new_poly are some self intersections try to avoid making union with them
  1207. # for poly in new_poly:
  1208. # try:
  1209. # self.solid_geometry = self.solid_geometry.union(poly)
  1210. # except Exception:
  1211. # pass
  1212. else:
  1213. self.solid_geometry = self.solid_geometry.difference(new_poly)
  1214. if self.app.defaults['gerber_clean_apertures']:
  1215. # clean the Gerber file of apertures with no geometry
  1216. for apid, apvalue in list(self.apertures.items()):
  1217. if 'geometry' not in apvalue:
  1218. self.apertures.pop(apid)
  1219. # init this for the following operations
  1220. self.conversion_done = False
  1221. except Exception as err:
  1222. ex_type, ex, tb = sys.exc_info()
  1223. traceback.print_tb(tb)
  1224. # print traceback.format_exc()
  1225. log.error("Gerber PARSING FAILED. Line %d: %s" % (line_num, gline))
  1226. loc = '%s #%d %s: %s\n' % (_("Gerber Line"), line_num, _("Gerber Line Content"), gline) + repr(err)
  1227. self.app.inform.emit('[ERROR] %s\n%s:' %
  1228. (_("Gerber Parser ERROR"), loc))
  1229. @staticmethod
  1230. def create_flash_geometry(location, aperture, steps_per_circle=None):
  1231. # log.debug('Flashing @%s, Aperture: %s' % (location, aperture))
  1232. if type(location) == list:
  1233. location = Point(location)
  1234. if aperture['type'] == 'C': # Circles
  1235. return location.buffer(aperture['size'] / 2, int(steps_per_circle / 4))
  1236. if aperture['type'] == 'R': # Rectangles
  1237. loc = location.coords[0]
  1238. width = aperture['width']
  1239. height = aperture['height']
  1240. minx = loc[0] - width / 2
  1241. maxx = loc[0] + width / 2
  1242. miny = loc[1] - height / 2
  1243. maxy = loc[1] + height / 2
  1244. return shply_box(minx, miny, maxx, maxy)
  1245. if aperture['type'] == 'O': # Obround
  1246. loc = location.coords[0]
  1247. width = aperture['width']
  1248. height = aperture['height']
  1249. if width > height:
  1250. p1 = Point(loc[0] + 0.5 * (width - height), loc[1])
  1251. p2 = Point(loc[0] - 0.5 * (width - height), loc[1])
  1252. c1 = p1.buffer(height * 0.5, int(steps_per_circle / 4))
  1253. c2 = p2.buffer(height * 0.5, int(steps_per_circle / 4))
  1254. else:
  1255. p1 = Point(loc[0], loc[1] + 0.5 * (height - width))
  1256. p2 = Point(loc[0], loc[1] - 0.5 * (height - width))
  1257. c1 = p1.buffer(width * 0.5, int(steps_per_circle / 4))
  1258. c2 = p2.buffer(width * 0.5, int(steps_per_circle / 4))
  1259. return cascaded_union([c1, c2]).convex_hull
  1260. if aperture['type'] == 'P': # Regular polygon
  1261. loc = location.coords[0]
  1262. diam = aperture['diam']
  1263. n_vertices = aperture['nVertices']
  1264. points = []
  1265. for i in range(0, n_vertices):
  1266. x = loc[0] + 0.5 * diam * (np.cos(2 * np.pi * i / n_vertices))
  1267. y = loc[1] + 0.5 * diam * (np.sin(2 * np.pi * i / n_vertices))
  1268. points.append((x, y))
  1269. ply = Polygon(points)
  1270. if 'rotation' in aperture:
  1271. ply = affinity.rotate(ply, aperture['rotation'])
  1272. return ply
  1273. if aperture['type'] == 'AM': # Aperture Macro
  1274. loc = location.coords[0]
  1275. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1276. if flash_geo.is_empty:
  1277. log.warning("Empty geometry for Aperture Macro: %s" % str(aperture['macro'].name))
  1278. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1279. log.warning("Unknown aperture type: %s" % aperture['type'])
  1280. return None
  1281. def create_geometry(self):
  1282. """
  1283. Geometry from a Gerber file is made up entirely of polygons.
  1284. Every stroke (linear or circular) has an aperture which gives
  1285. it thickness. Additionally, aperture strokes have non-zero area,
  1286. and regions naturally do as well.
  1287. :rtype : None
  1288. :return: None
  1289. """
  1290. pass
  1291. # self.buffer_paths()
  1292. #
  1293. # self.fix_regions()
  1294. #
  1295. # self.do_flashes()
  1296. #
  1297. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1298. # [poly['polygon'] for poly in self.regions] +
  1299. # self.flash_geometry)
  1300. def get_bounding_box(self, margin=0.0, rounded=False):
  1301. """
  1302. Creates and returns a rectangular polygon bounding at a distance of
  1303. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1304. can optionally have rounded corners of radius equal to margin.
  1305. :param margin: Distance to enlarge the rectangular bounding
  1306. box in both positive and negative, x and y axes.
  1307. :type margin: float
  1308. :param rounded: Wether or not to have rounded corners.
  1309. :type rounded: bool
  1310. :return: The bounding box.
  1311. :rtype: Shapely.Polygon
  1312. """
  1313. bbox = self.solid_geometry.envelope.buffer(margin)
  1314. if not rounded:
  1315. bbox = bbox.envelope
  1316. return bbox
  1317. def bounds(self):
  1318. """
  1319. Returns coordinates of rectangular bounds
  1320. of Gerber geometry: (xmin, ymin, xmax, ymax).
  1321. """
  1322. # fixed issue of getting bounds only for one level lists of objects
  1323. # now it can get bounds for nested lists of objects
  1324. log.debug("parseGerber.Gerber.bounds()")
  1325. if self.solid_geometry is None:
  1326. log.debug("solid_geometry is None")
  1327. return 0, 0, 0, 0
  1328. def bounds_rec(obj):
  1329. if type(obj) is list and type(obj) is not MultiPolygon:
  1330. minx = np.Inf
  1331. miny = np.Inf
  1332. maxx = -np.Inf
  1333. maxy = -np.Inf
  1334. for k in obj:
  1335. if type(k) is dict:
  1336. for key in k:
  1337. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  1338. minx = min(minx, minx_)
  1339. miny = min(miny, miny_)
  1340. maxx = max(maxx, maxx_)
  1341. maxy = max(maxy, maxy_)
  1342. else:
  1343. if not k.is_empty:
  1344. try:
  1345. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1346. except Exception as e:
  1347. log.debug("camlib.Gerber.bounds() --> %s" % str(e))
  1348. return
  1349. minx = min(minx, minx_)
  1350. miny = min(miny, miny_)
  1351. maxx = max(maxx, maxx_)
  1352. maxy = max(maxy, maxy_)
  1353. return minx, miny, maxx, maxy
  1354. else:
  1355. # it's a Shapely object, return it's bounds
  1356. return obj.bounds
  1357. bounds_coords = bounds_rec(self.solid_geometry)
  1358. return bounds_coords
  1359. def convert_units(self, obj_units):
  1360. """
  1361. Converts the units of the object to ``units`` by scaling all
  1362. the geometry appropriately. This call ``scale()``. Don't call
  1363. it again in descendants.
  1364. :param obj_units: "IN" or "MM"
  1365. :type obj_units: str
  1366. :return: Scaling factor resulting from unit change.
  1367. :rtype: float
  1368. """
  1369. if obj_units.upper() == self.units.upper():
  1370. log.debug("parseGerber.Gerber.convert_units() --> Factor: 1")
  1371. return 1.0
  1372. if obj_units.upper() == "MM":
  1373. factor = 25.4
  1374. log.debug("parseGerber.Gerber.convert_units() --> Factor: 25.4")
  1375. elif obj_units.upper() == "IN":
  1376. factor = 1 / 25.4
  1377. log.debug("parseGerber.Gerber.convert_units() --> Factor: %s" % str(1 / 25.4))
  1378. else:
  1379. log.error("Unsupported units: %s" % str(obj_units))
  1380. log.debug("parseGerber.Gerber.convert_units() --> Factor: 1")
  1381. return 1.0
  1382. self.units = obj_units
  1383. self.file_units_factor = factor
  1384. self.scale(factor, factor)
  1385. return factor
  1386. def import_svg(self, filename, object_type='gerber', flip=True, units='MM'):
  1387. """
  1388. Imports shapes from an SVG file into the object's geometry.
  1389. :param filename: Path to the SVG file.
  1390. :type filename: str
  1391. :param object_type: parameter passed further along
  1392. :param flip: Flip the vertically.
  1393. :type flip: bool
  1394. :param units: FlatCAM units
  1395. :return: None
  1396. """
  1397. log.debug("flatcamParsers.ParseGerber.Gerber.import_svg()")
  1398. # Parse into list of shapely objects
  1399. svg_tree = ET.parse(filename)
  1400. svg_root = svg_tree.getroot()
  1401. # Change origin to bottom left
  1402. # h = float(svg_root.get('height'))
  1403. # w = float(svg_root.get('width'))
  1404. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  1405. geos = getsvggeo(svg_root, 'gerber')
  1406. if flip:
  1407. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  1408. # Add to object
  1409. if self.solid_geometry is None:
  1410. self.solid_geometry = list()
  1411. # if type(self.solid_geometry) == list:
  1412. # if type(geos) == list:
  1413. # self.solid_geometry += geos
  1414. # else:
  1415. # self.solid_geometry.append(geos)
  1416. # else: # It's shapely geometry
  1417. # self.solid_geometry = [self.solid_geometry, geos]
  1418. if type(geos) == list:
  1419. # HACK for importing QRCODE exported by FlatCAM
  1420. if len(geos) == 1:
  1421. geo_qrcode = list()
  1422. geo_qrcode.append(Polygon(geos[0].exterior))
  1423. for i_el in geos[0].interiors:
  1424. geo_qrcode.append(Polygon(i_el).buffer(0))
  1425. for poly in geo_qrcode:
  1426. geos.append(poly)
  1427. if type(self.solid_geometry) == list:
  1428. self.solid_geometry += geos
  1429. else:
  1430. geos.append(self.solid_geometry)
  1431. self.solid_geometry = geos
  1432. else:
  1433. if type(self.solid_geometry) == list:
  1434. self.solid_geometry.append(geos)
  1435. else:
  1436. self.solid_geometry = [self.solid_geometry, geos]
  1437. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  1438. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  1439. try:
  1440. __ = iter(self.solid_geometry)
  1441. except TypeError:
  1442. self.solid_geometry = [self.solid_geometry]
  1443. if '0' not in self.apertures:
  1444. self.apertures['0'] = dict()
  1445. self.apertures['0']['type'] = 'REG'
  1446. self.apertures['0']['size'] = 0.0
  1447. self.apertures['0']['geometry'] = list()
  1448. for pol in self.solid_geometry:
  1449. new_el = dict()
  1450. new_el['solid'] = pol
  1451. new_el['follow'] = pol.exterior
  1452. self.apertures['0']['geometry'].append(deepcopy(new_el))
  1453. def scale(self, xfactor, yfactor=None, point=None):
  1454. """
  1455. Scales the objects' geometry on the XY plane by a given factor.
  1456. These are:
  1457. * ``buffered_paths``
  1458. * ``flash_geometry``
  1459. * ``solid_geometry``
  1460. * ``regions``
  1461. NOTE:
  1462. Does not modify the data used to create these elements. If these
  1463. are recreated, the scaling will be lost. This behavior was modified
  1464. because of the complexity reached in this class.
  1465. :param xfactor: Number by which to scale on X axis.
  1466. :type xfactor: float
  1467. :param yfactor: Number by which to scale on Y axis.
  1468. :type yfactor: float
  1469. :param point: reference point for scaling operation
  1470. :rtype : None
  1471. """
  1472. log.debug("parseGerber.Gerber.scale()")
  1473. try:
  1474. xfactor = float(xfactor)
  1475. except Exception:
  1476. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1477. _("Scale factor has to be a number: integer or float."))
  1478. return
  1479. if yfactor is None:
  1480. yfactor = xfactor
  1481. else:
  1482. try:
  1483. yfactor = float(yfactor)
  1484. except Exception:
  1485. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1486. _("Scale factor has to be a number: integer or float."))
  1487. return
  1488. if xfactor == 0 and yfactor == 0:
  1489. return
  1490. if point is None:
  1491. px = 0
  1492. py = 0
  1493. else:
  1494. px, py = point
  1495. # variables to display the percentage of work done
  1496. self.geo_len = 0
  1497. try:
  1498. self.geo_len = len(self.solid_geometry)
  1499. except TypeError:
  1500. self.geo_len = 1
  1501. self.old_disp_number = 0
  1502. self.el_count = 0
  1503. def scale_geom(obj):
  1504. if type(obj) is list:
  1505. new_obj = []
  1506. for g in obj:
  1507. new_obj.append(scale_geom(g))
  1508. return new_obj
  1509. else:
  1510. try:
  1511. self.el_count += 1
  1512. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 99]))
  1513. if self.old_disp_number < disp_number <= 100:
  1514. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1515. self.old_disp_number = disp_number
  1516. return affinity.scale(obj, xfactor, yfactor, origin=(px, py))
  1517. except AttributeError:
  1518. return obj
  1519. self.solid_geometry = scale_geom(self.solid_geometry)
  1520. self.follow_geometry = scale_geom(self.follow_geometry)
  1521. # we need to scale the geometry stored in the Gerber apertures, too
  1522. try:
  1523. for apid in self.apertures:
  1524. new_geometry = list()
  1525. if 'geometry' in self.apertures[apid]:
  1526. for geo_el in self.apertures[apid]['geometry']:
  1527. new_geo_el = dict()
  1528. if 'solid' in geo_el:
  1529. new_geo_el['solid'] = scale_geom(geo_el['solid'])
  1530. if 'follow' in geo_el:
  1531. new_geo_el['follow'] = scale_geom(geo_el['follow'])
  1532. if 'clear' in geo_el:
  1533. new_geo_el['clear'] = scale_geom(geo_el['clear'])
  1534. new_geometry.append(new_geo_el)
  1535. self.apertures[apid]['geometry'] = deepcopy(new_geometry)
  1536. try:
  1537. if str(self.apertures[apid]['type']) == 'R' or str(self.apertures[apid]['type']) == 'O':
  1538. self.apertures[apid]['width'] *= xfactor
  1539. self.apertures[apid]['height'] *= xfactor
  1540. elif str(self.apertures[apid]['type']) == 'P':
  1541. self.apertures[apid]['diam'] *= xfactor
  1542. self.apertures[apid]['nVertices'] *= xfactor
  1543. except KeyError:
  1544. pass
  1545. try:
  1546. if self.apertures[apid]['size'] is not None:
  1547. self.apertures[apid]['size'] = float(self.apertures[apid]['size'] * xfactor)
  1548. except KeyError:
  1549. pass
  1550. except Exception as e:
  1551. log.debug('camlib.Gerber.scale() Exception --> %s' % str(e))
  1552. return 'fail'
  1553. self.app.inform.emit('[success] %s' % _("Gerber Scale done."))
  1554. self.app.proc_container.new_text = ''
  1555. # ## solid_geometry ???
  1556. # It's a cascaded union of objects.
  1557. # self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  1558. # factor, origin=(0, 0))
  1559. # # Now buffered_paths, flash_geometry and solid_geometry
  1560. # self.create_geometry()
  1561. def offset(self, vect):
  1562. """
  1563. Offsets the objects' geometry on the XY plane by a given vector.
  1564. These are:
  1565. * ``buffered_paths``
  1566. * ``flash_geometry``
  1567. * ``solid_geometry``
  1568. * ``regions``
  1569. NOTE:
  1570. Does not modify the data used to create these elements. If these
  1571. are recreated, the scaling will be lost. This behavior was modified
  1572. because of the complexity reached in this class.
  1573. :param vect: (x, y) offset vector.
  1574. :type vect: tuple
  1575. :return: None
  1576. """
  1577. log.debug("parseGerber.Gerber.offset()")
  1578. try:
  1579. dx, dy = vect
  1580. except TypeError:
  1581. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1582. _("An (x,y) pair of values are needed. "
  1583. "Probable you entered only one value in the Offset field."))
  1584. return
  1585. if dx == 0 and dy == 0:
  1586. return
  1587. # variables to display the percentage of work done
  1588. self.geo_len = 0
  1589. try:
  1590. for __ in self.solid_geometry:
  1591. self.geo_len += 1
  1592. except TypeError:
  1593. self.geo_len = 1
  1594. self.old_disp_number = 0
  1595. self.el_count = 0
  1596. def offset_geom(obj):
  1597. if type(obj) is list:
  1598. new_obj = []
  1599. for g in obj:
  1600. new_obj.append(offset_geom(g))
  1601. return new_obj
  1602. else:
  1603. try:
  1604. self.el_count += 1
  1605. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 99]))
  1606. if self.old_disp_number < disp_number <= 100:
  1607. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1608. self.old_disp_number = disp_number
  1609. return affinity.translate(obj, xoff=dx, yoff=dy)
  1610. except AttributeError:
  1611. return obj
  1612. # ## Solid geometry
  1613. self.solid_geometry = offset_geom(self.solid_geometry)
  1614. self.follow_geometry = offset_geom(self.follow_geometry)
  1615. # we need to offset the geometry stored in the Gerber apertures, too
  1616. try:
  1617. for apid in self.apertures:
  1618. if 'geometry' in self.apertures[apid]:
  1619. for geo_el in self.apertures[apid]['geometry']:
  1620. if 'solid' in geo_el:
  1621. geo_el['solid'] = offset_geom(geo_el['solid'])
  1622. if 'follow' in geo_el:
  1623. geo_el['follow'] = offset_geom(geo_el['follow'])
  1624. if 'clear' in geo_el:
  1625. geo_el['clear'] = offset_geom(geo_el['clear'])
  1626. except Exception as e:
  1627. log.debug('camlib.Gerber.offset() Exception --> %s' % str(e))
  1628. return 'fail'
  1629. self.app.inform.emit('[success] %s' %
  1630. _("Gerber Offset done."))
  1631. self.app.proc_container.new_text = ''
  1632. def mirror(self, axis, point):
  1633. """
  1634. Mirrors the object around a specified axis passing through
  1635. the given point. What is affected:
  1636. * ``buffered_paths``
  1637. * ``flash_geometry``
  1638. * ``solid_geometry``
  1639. * ``regions``
  1640. NOTE:
  1641. Does not modify the data used to create these elements. If these
  1642. are recreated, the scaling will be lost. This behavior was modified
  1643. because of the complexity reached in this class.
  1644. :param axis: "X" or "Y" indicates around which axis to mirror.
  1645. :type axis: str
  1646. :param point: [x, y] point belonging to the mirror axis.
  1647. :type point: list
  1648. :return: None
  1649. """
  1650. log.debug("parseGerber.Gerber.mirror()")
  1651. px, py = point
  1652. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1653. # variables to display the percentage of work done
  1654. self.geo_len = 0
  1655. try:
  1656. for __ in self.solid_geometry:
  1657. self.geo_len += 1
  1658. except TypeError:
  1659. self.geo_len = 1
  1660. self.old_disp_number = 0
  1661. self.el_count = 0
  1662. def mirror_geom(obj):
  1663. if type(obj) is list:
  1664. new_obj = []
  1665. for g in obj:
  1666. new_obj.append(mirror_geom(g))
  1667. return new_obj
  1668. else:
  1669. try:
  1670. self.el_count += 1
  1671. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 99]))
  1672. if self.old_disp_number < disp_number <= 100:
  1673. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1674. self.old_disp_number = disp_number
  1675. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1676. except AttributeError:
  1677. return obj
  1678. self.solid_geometry = mirror_geom(self.solid_geometry)
  1679. self.follow_geometry = mirror_geom(self.follow_geometry)
  1680. # we need to mirror the geometry stored in the Gerber apertures, too
  1681. try:
  1682. for apid in self.apertures:
  1683. if 'geometry' in self.apertures[apid]:
  1684. for geo_el in self.apertures[apid]['geometry']:
  1685. if 'solid' in geo_el:
  1686. geo_el['solid'] = mirror_geom(geo_el['solid'])
  1687. if 'follow' in geo_el:
  1688. geo_el['follow'] = mirror_geom(geo_el['follow'])
  1689. if 'clear' in geo_el:
  1690. geo_el['clear'] = mirror_geom(geo_el['clear'])
  1691. except Exception as e:
  1692. log.debug('camlib.Gerber.mirror() Exception --> %s' % str(e))
  1693. return 'fail'
  1694. self.app.inform.emit('[success] %s' %
  1695. _("Gerber Mirror done."))
  1696. self.app.proc_container.new_text = ''
  1697. def skew(self, angle_x, angle_y, point):
  1698. """
  1699. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1700. Parameters
  1701. ----------
  1702. angle_x, angle_y : float, float
  1703. The shear angle(s) for the x and y axes respectively. These can be
  1704. specified in either degrees (default) or radians by setting
  1705. use_radians=True.
  1706. See shapely manual for more information:
  1707. http://toblerity.org/shapely/manual.html#affine-transformations
  1708. :param angle_x: the angle on X axis for skewing
  1709. :param angle_y: the angle on Y axis for skewing
  1710. :param point: reference point for skewing operation
  1711. :return None
  1712. """
  1713. log.debug("parseGerber.Gerber.skew()")
  1714. px, py = point
  1715. if angle_x == 0 and angle_y == 0:
  1716. return
  1717. # variables to display the percentage of work done
  1718. self.geo_len = 0
  1719. try:
  1720. self.geo_len = len(self.solid_geometry)
  1721. except TypeError:
  1722. self.geo_len = 1
  1723. self.old_disp_number = 0
  1724. self.el_count = 0
  1725. def skew_geom(obj):
  1726. if type(obj) is list:
  1727. new_obj = []
  1728. for g in obj:
  1729. new_obj.append(skew_geom(g))
  1730. return new_obj
  1731. else:
  1732. try:
  1733. self.el_count += 1
  1734. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1735. if self.old_disp_number < disp_number <= 100:
  1736. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1737. self.old_disp_number = disp_number
  1738. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1739. except AttributeError:
  1740. return obj
  1741. self.solid_geometry = skew_geom(self.solid_geometry)
  1742. self.follow_geometry = skew_geom(self.follow_geometry)
  1743. # we need to skew the geometry stored in the Gerber apertures, too
  1744. try:
  1745. for apid in self.apertures:
  1746. if 'geometry' in self.apertures[apid]:
  1747. for geo_el in self.apertures[apid]['geometry']:
  1748. if 'solid' in geo_el:
  1749. geo_el['solid'] = skew_geom(geo_el['solid'])
  1750. if 'follow' in geo_el:
  1751. geo_el['follow'] = skew_geom(geo_el['follow'])
  1752. if 'clear' in geo_el:
  1753. geo_el['clear'] = skew_geom(geo_el['clear'])
  1754. except Exception as e:
  1755. log.debug('camlib.Gerber.skew() Exception --> %s' % str(e))
  1756. return 'fail'
  1757. self.app.inform.emit('[success] %s' % _("Gerber Skew done."))
  1758. self.app.proc_container.new_text = ''
  1759. def rotate(self, angle, point):
  1760. """
  1761. Rotate an object by a given angle around given coords (point)
  1762. :param angle:
  1763. :param point:
  1764. :return:
  1765. """
  1766. log.debug("parseGerber.Gerber.rotate()")
  1767. px, py = point
  1768. if angle == 0:
  1769. return
  1770. # variables to display the percentage of work done
  1771. self.geo_len = 0
  1772. try:
  1773. for __ in self.solid_geometry:
  1774. self.geo_len += 1
  1775. except TypeError:
  1776. self.geo_len = 1
  1777. self.old_disp_number = 0
  1778. self.el_count = 0
  1779. def rotate_geom(obj):
  1780. if type(obj) is list:
  1781. new_obj = []
  1782. for g in obj:
  1783. new_obj.append(rotate_geom(g))
  1784. return new_obj
  1785. else:
  1786. try:
  1787. self.el_count += 1
  1788. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1789. if self.old_disp_number < disp_number <= 100:
  1790. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1791. self.old_disp_number = disp_number
  1792. return affinity.rotate(obj, angle, origin=(px, py))
  1793. except AttributeError:
  1794. return obj
  1795. self.solid_geometry = rotate_geom(self.solid_geometry)
  1796. self.follow_geometry = rotate_geom(self.follow_geometry)
  1797. # we need to rotate the geometry stored in the Gerber apertures, too
  1798. try:
  1799. for apid in self.apertures:
  1800. if 'geometry' in self.apertures[apid]:
  1801. for geo_el in self.apertures[apid]['geometry']:
  1802. if 'solid' in geo_el:
  1803. geo_el['solid'] = rotate_geom(geo_el['solid'])
  1804. if 'follow' in geo_el:
  1805. geo_el['follow'] = rotate_geom(geo_el['follow'])
  1806. if 'clear' in geo_el:
  1807. geo_el['clear'] = rotate_geom(geo_el['clear'])
  1808. except Exception as e:
  1809. log.debug('camlib.Gerber.rotate() Exception --> %s' % str(e))
  1810. return 'fail'
  1811. self.app.inform.emit('[success] %s' %
  1812. _("Gerber Rotate done."))
  1813. self.app.proc_container.new_text = ''
  1814. def parse_gerber_number(strnumber, int_digits, frac_digits, zeros):
  1815. """
  1816. Parse a single number of Gerber coordinates.
  1817. :param strnumber: String containing a number in decimal digits
  1818. from a coordinate data block, possibly with a leading sign.
  1819. :type strnumber: str
  1820. :param int_digits: Number of digits used for the integer
  1821. part of the number
  1822. :type frac_digits: int
  1823. :param frac_digits: Number of digits used for the fractional
  1824. part of the number
  1825. :type frac_digits: int
  1826. :param zeros: If 'L', leading zeros are removed and trailing zeros are kept. Same situation for 'D' when
  1827. no zero suppression is done. If 'T', is in reverse.
  1828. :type zeros: str
  1829. :return: The number in floating point.
  1830. :rtype: float
  1831. """
  1832. ret_val = None
  1833. if zeros == 'L' or zeros == 'D':
  1834. ret_val = int(strnumber) * (10 ** (-frac_digits))
  1835. if zeros == 'T':
  1836. int_val = int(strnumber)
  1837. ret_val = (int_val * (10 ** ((int_digits + frac_digits) - len(strnumber)))) * (10 ** (-frac_digits))
  1838. return ret_val