ParseGerber.py 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005
  1. from camlib import Geometry, ApertureMacro, parse_gerber_number, arc, arctan2, arc_angle
  2. import FlatCAMApp
  3. import FlatCAMTranslation as fcTranslate
  4. from shapely.geometry import Polygon, Point, LineString, MultiPolygon
  5. from shapely.ops import cascaded_union
  6. import shapely.affinity as affinity
  7. from shapely.geometry import box as shply_box
  8. import re
  9. import traceback
  10. from copy import deepcopy
  11. import gettext
  12. import builtins
  13. import numpy as np
  14. from numpy import Inf
  15. from math import sqrt, pi, sin, cos
  16. import sys
  17. import logging
  18. if '_' not in builtins.__dict__:
  19. _ = gettext.gettext
  20. log = logging.getLogger('base2')
  21. log.setLevel(logging.DEBUG)
  22. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  23. handler = logging.StreamHandler()
  24. handler.setFormatter(formatter)
  25. log.addHandler(handler)
  26. class Gerber(Geometry):
  27. """
  28. Here it is done all the Gerber parsing.
  29. **ATTRIBUTES**
  30. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  31. The values are dictionaries key/value pairs which describe the aperture. The
  32. type key is always present and the rest depend on the key:
  33. +-----------+-----------------------------------+
  34. | Key | Value |
  35. +===========+===================================+
  36. | type | (str) "C", "R", "O", "P", or "AP" |
  37. +-----------+-----------------------------------+
  38. | others | Depend on ``type`` |
  39. +-----------+-----------------------------------+
  40. | solid_geometry | (list) |
  41. +-----------+-----------------------------------+
  42. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  43. that can be instantiated with different parameters in an aperture
  44. definition. See ``apertures`` above. The key is the name of the macro,
  45. and the macro itself, the value, is a ``Aperture_Macro`` object.
  46. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  47. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  48. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  49. *buffering* (or thickening) the ``paths`` with the aperture. These are
  50. generated from ``paths`` in ``buffer_paths()``.
  51. **USAGE**::
  52. g = Gerber()
  53. g.parse_file(filename)
  54. g.create_geometry()
  55. do_something(s.solid_geometry)
  56. """
  57. # defaults = {
  58. # "steps_per_circle": 128,
  59. # "use_buffer_for_union": True
  60. # }
  61. def __init__(self, steps_per_circle=None):
  62. """
  63. The constructor takes no parameters. Use ``gerber.parse_files()``
  64. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  65. :return: Gerber object
  66. :rtype: Gerber
  67. """
  68. # How to approximate a circle with lines.
  69. self.steps_per_circle = int(self.app.defaults["gerber_circle_steps"])
  70. # Initialize parent
  71. Geometry.__init__(self, geo_steps_per_circle=int(self.app.defaults["gerber_circle_steps"]))
  72. # Number format
  73. self.int_digits = 3
  74. """Number of integer digits in Gerber numbers. Used during parsing."""
  75. self.frac_digits = 4
  76. """Number of fraction digits in Gerber numbers. Used during parsing."""
  77. self.gerber_zeros = self.app.defaults['gerber_def_zeros']
  78. """Zeros in Gerber numbers. If 'L' then remove leading zeros, if 'T' remove trailing zeros. Used during parsing.
  79. """
  80. # ## Gerber elements # ##
  81. '''
  82. apertures = {
  83. 'id':{
  84. 'type':string,
  85. 'size':float,
  86. 'width':float,
  87. 'height':float,
  88. 'geometry': [],
  89. }
  90. }
  91. apertures['geometry'] list elements are dicts
  92. dict = {
  93. 'solid': [],
  94. 'follow': [],
  95. 'clear': []
  96. }
  97. '''
  98. # store the file units here:
  99. self.gerber_units = self.app.defaults['gerber_def_units']
  100. # aperture storage
  101. self.apertures = {}
  102. # Aperture Macros
  103. self.aperture_macros = {}
  104. # will store the Gerber geometry's as solids
  105. self.solid_geometry = Polygon()
  106. # will store the Gerber geometry's as paths
  107. self.follow_geometry = []
  108. # made True when the LPC command is encountered in Gerber parsing
  109. # it allows adding data into the clear_geometry key of the self.apertures[aperture] dict
  110. self.is_lpc = False
  111. self.source_file = ''
  112. # Attributes to be included in serialization
  113. # Always append to it because it carries contents
  114. # from Geometry.
  115. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures',
  116. 'aperture_macros', 'solid_geometry', 'source_file']
  117. # ### Parser patterns ## ##
  118. # FS - Format Specification
  119. # The format of X and Y must be the same!
  120. # L-omit leading zeros, T-omit trailing zeros, D-no zero supression
  121. # A-absolute notation, I-incremental notation
  122. self.fmt_re = re.compile(r'%?FS([LTD])?([AI])X(\d)(\d)Y\d\d\*%?$')
  123. self.fmt_re_alt = re.compile(r'%FS([LTD])?([AI])X(\d)(\d)Y\d\d\*MO(IN|MM)\*%$')
  124. self.fmt_re_orcad = re.compile(r'(G\d+)*\**%FS([LTD])?([AI]).*X(\d)(\d)Y\d\d\*%$')
  125. # Mode (IN/MM)
  126. self.mode_re = re.compile(r'^%?MO(IN|MM)\*%?$')
  127. # Comment G04|G4
  128. self.comm_re = re.compile(r'^G0?4(.*)$')
  129. # AD - Aperture definition
  130. # Aperture Macro names: Name = [a-zA-Z_.$]{[a-zA-Z_.0-9]+}
  131. # NOTE: Adding "-" to support output from Upverter.
  132. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z_$\.][a-zA-Z0-9_$\.\-]*)(?:,(.*))?\*%$')
  133. # AM - Aperture Macro
  134. # Beginning of macro (Ends with *%):
  135. # self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  136. # Tool change
  137. # May begin with G54 but that is deprecated
  138. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  139. # G01... - Linear interpolation plus flashes with coordinates
  140. # Operation code (D0x) missing is deprecated... oh well I will support it.
  141. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  142. # Operation code alone, usually just D03 (Flash)
  143. self.opcode_re = re.compile(r'^D0?([123])\*$')
  144. # G02/3... - Circular interpolation with coordinates
  145. # 2-clockwise, 3-counterclockwise
  146. # Operation code (D0x) missing is deprecated... oh well I will support it.
  147. # Optional start with G02 or G03, optional end with D01 or D02 with
  148. # optional coordinates but at least one in any order.
  149. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))' +
  150. '?(?=.*I([\+-]?\d+))?(?=.*J([\+-]?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  151. # G01/2/3 Occurring without coordinates
  152. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  153. # Single G74 or multi G75 quadrant for circular interpolation
  154. self.quad_re = re.compile(r'^G7([45]).*\*$')
  155. # Region mode on
  156. # In region mode, D01 starts a region
  157. # and D02 ends it. A new region can be started again
  158. # with D01. All contours must be closed before
  159. # D02 or G37.
  160. self.regionon_re = re.compile(r'^G36\*$')
  161. # Region mode off
  162. # Will end a region and come off region mode.
  163. # All contours must be closed before D02 or G37.
  164. self.regionoff_re = re.compile(r'^G37\*$')
  165. # End of file
  166. self.eof_re = re.compile(r'^M02\*')
  167. # IP - Image polarity
  168. self.pol_re = re.compile(r'^%?IP(POS|NEG)\*%?$')
  169. # LP - Level polarity
  170. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  171. # Units (OBSOLETE)
  172. self.units_re = re.compile(r'^G7([01])\*$')
  173. # Absolute/Relative G90/1 (OBSOLETE)
  174. self.absrel_re = re.compile(r'^G9([01])\*$')
  175. # Aperture macros
  176. self.am1_re = re.compile(r'^%AM([^\*]+)\*([^%]+)?(%)?$')
  177. self.am2_re = re.compile(r'(.*)%$')
  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:
  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": 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": 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:
  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.gerber_units = match.group(1)
  417. log.debug("Gerber units found = %s" % self.gerber_units)
  418. # Changed for issue #80
  419. self.convert_units(match.group(1))
  420. continue
  421. # ############################################################# ##
  422. # Combined Number format and Mode --- Allegro does this ####### ##
  423. # ############################################################# ##
  424. match = self.fmt_re_alt.search(gline)
  425. if match:
  426. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(2)]
  427. if match.group(1) is not None:
  428. self.gerber_zeros = match.group(1)
  429. self.int_digits = int(match.group(3))
  430. self.frac_digits = int(match.group(4))
  431. log.debug("Gerber format found. (%s) " % str(gline))
  432. log.debug(
  433. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros, "
  434. "D-no zero suppression)" % self.gerber_zeros)
  435. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  436. self.gerber_units = match.group(5)
  437. log.debug("Gerber units found = %s" % self.gerber_units)
  438. # Changed for issue #80
  439. self.convert_units(match.group(5))
  440. continue
  441. # ############################################################# ##
  442. # Search for OrCAD way for having Number format
  443. # ############################################################# ##
  444. match = self.fmt_re_orcad.search(gline)
  445. if match:
  446. if match.group(1) is not None:
  447. if match.group(1) == 'G74':
  448. quadrant_mode = 'SINGLE'
  449. elif match.group(1) == 'G75':
  450. quadrant_mode = 'MULTI'
  451. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(3)]
  452. if match.group(2) is not None:
  453. self.gerber_zeros = match.group(2)
  454. self.int_digits = int(match.group(4))
  455. self.frac_digits = int(match.group(5))
  456. log.debug("Gerber format found. (%s) " % str(gline))
  457. log.debug(
  458. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros, "
  459. "D-no zerosuppressionn)" % self.gerber_zeros)
  460. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  461. self.gerber_units = match.group(1)
  462. log.debug("Gerber units found = %s" % self.gerber_units)
  463. # Changed for issue #80
  464. self.convert_units(match.group(5))
  465. continue
  466. # ############################################################# ##
  467. # Units (G70/1) OBSOLETE
  468. # ############################################################# ##
  469. match = self.units_re.search(gline)
  470. if match:
  471. obs_gerber_units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  472. log.warning("Gerber obsolete units found = %s" % obs_gerber_units)
  473. # Changed for issue #80
  474. self.convert_units({'0': 'IN', '1': 'MM'}[match.group(1)])
  475. continue
  476. # ############################################################# ##
  477. # Absolute/relative coordinates G90/1 OBSOLETE ######## ##
  478. # ##################################################### ##
  479. match = self.absrel_re.search(gline)
  480. if match:
  481. absolute = {'0': "Absolute", '1': "Relative"}[match.group(1)]
  482. log.warning("Gerber obsolete coordinates type found = %s (Absolute or Relative) " % absolute)
  483. continue
  484. # ############################################################# ##
  485. # Aperture Macros ##################################### ##
  486. # Having this at the beginning will slow things down
  487. # but macros can have complicated statements than could
  488. # be caught by other patterns.
  489. # ############################################################# ##
  490. if current_macro is None: # No macro started yet
  491. match = self.am1_re.search(gline)
  492. # Start macro if match, else not an AM, carry on.
  493. if match:
  494. log.debug("Starting macro. Line %d: %s" % (line_num, gline))
  495. current_macro = match.group(1)
  496. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  497. if match.group(2): # Append
  498. self.aperture_macros[current_macro].append(match.group(2))
  499. if match.group(3): # Finish macro
  500. # self.aperture_macros[current_macro].parse_content()
  501. current_macro = None
  502. log.debug("Macro complete in 1 line.")
  503. continue
  504. else: # Continue macro
  505. log.debug("Continuing macro. Line %d." % line_num)
  506. match = self.am2_re.search(gline)
  507. if match: # Finish macro
  508. log.debug("End of macro. Line %d." % line_num)
  509. self.aperture_macros[current_macro].append(match.group(1))
  510. # self.aperture_macros[current_macro].parse_content()
  511. current_macro = None
  512. else: # Append
  513. self.aperture_macros[current_macro].append(gline)
  514. continue
  515. # ## Aperture definitions %ADD...
  516. match = self.ad_re.search(gline)
  517. if match:
  518. # log.info("Found aperture definition. Line %d: %s" % (line_num, gline))
  519. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  520. continue
  521. # ############################################################# ##
  522. # Operation code alone ###################### ##
  523. # Operation code alone, usually just D03 (Flash)
  524. # self.opcode_re = re.compile(r'^D0?([123])\*$')
  525. # ############################################################# ##
  526. match = self.opcode_re.search(gline)
  527. if match:
  528. current_operation_code = int(match.group(1))
  529. current_d = current_operation_code
  530. if current_operation_code == 3:
  531. # --- Buffered ---
  532. try:
  533. log.debug("Bare op-code %d." % current_operation_code)
  534. geo_dict = dict()
  535. flash = self.create_flash_geometry(
  536. Point(current_x, current_y), self.apertures[current_aperture],
  537. self.steps_per_circle)
  538. geo_dict['follow'] = Point([current_x, current_y])
  539. if not flash.is_empty:
  540. if self.app.defaults['gerber_simplification']:
  541. poly_buffer.append(flash.simplify(s_tol))
  542. else:
  543. poly_buffer.append(flash)
  544. if self.is_lpc is True:
  545. geo_dict['clear'] = flash
  546. else:
  547. geo_dict['solid'] = flash
  548. if current_aperture not in self.apertures:
  549. self.apertures[current_aperture] = dict()
  550. if 'geometry' not in self.apertures[current_aperture]:
  551. self.apertures[current_aperture]['geometry'] = []
  552. self.apertures[current_aperture]['geometry'].append(deepcopy(geo_dict))
  553. except IndexError:
  554. log.warning("Line %d: %s -> Nothing there to flash!" % (line_num, gline))
  555. continue
  556. # ############################################################# ##
  557. # Tool/aperture change
  558. # Example: D12*
  559. # ############################################################# ##
  560. match = self.tool_re.search(gline)
  561. if match:
  562. current_aperture = match.group(1)
  563. # log.debug("Line %d: Aperture change to (%s)" % (line_num, current_aperture))
  564. # If the aperture value is zero then make it something quite small but with a non-zero value
  565. # so it can be processed by FlatCAM.
  566. # But first test to see if the aperture type is "aperture macro". In that case
  567. # we should not test for "size" key as it does not exist in this case.
  568. if self.apertures[current_aperture]["type"] is not "AM":
  569. if self.apertures[current_aperture]["size"] == 0:
  570. self.apertures[current_aperture]["size"] = 1e-12
  571. # log.debug(self.apertures[current_aperture])
  572. # Take care of the current path with the previous tool
  573. if len(path) > 1:
  574. if self.apertures[last_path_aperture]["type"] == 'R':
  575. # do nothing because 'R' type moving aperture is none at once
  576. pass
  577. else:
  578. geo_dict = dict()
  579. geo_f = LineString(path)
  580. if not geo_f.is_empty:
  581. follow_buffer.append(geo_f)
  582. geo_dict['follow'] = geo_f
  583. # --- Buffered ----
  584. width = self.apertures[last_path_aperture]["size"]
  585. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  586. if not geo_s.is_empty:
  587. if self.app.defaults['gerber_simplification']:
  588. poly_buffer.append(geo_s.simplify(s_tol))
  589. else:
  590. poly_buffer.append(geo_s)
  591. if self.is_lpc is True:
  592. geo_dict['clear'] = geo_s
  593. else:
  594. geo_dict['solid'] = geo_s
  595. if last_path_aperture not in self.apertures:
  596. self.apertures[last_path_aperture] = dict()
  597. if 'geometry' not in self.apertures[last_path_aperture]:
  598. self.apertures[last_path_aperture]['geometry'] = []
  599. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  600. path = [path[-1]]
  601. continue
  602. # ############################################################# ##
  603. # G36* - Begin region
  604. # ############################################################# ##
  605. if self.regionon_re.search(gline):
  606. if len(path) > 1:
  607. # Take care of what is left in the path
  608. geo_dict = dict()
  609. geo_f = LineString(path)
  610. if not geo_f.is_empty:
  611. follow_buffer.append(geo_f)
  612. geo_dict['follow'] = geo_f
  613. # --- Buffered ----
  614. width = self.apertures[last_path_aperture]["size"]
  615. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  616. if not geo_s.is_empty:
  617. if self.app.defaults['gerber_simplification']:
  618. poly_buffer.append(geo_s.simplify(s_tol))
  619. else:
  620. poly_buffer.append(geo_s)
  621. if self.is_lpc is True:
  622. geo_dict['clear'] = geo_s
  623. else:
  624. geo_dict['solid'] = geo_s
  625. if last_path_aperture not in self.apertures:
  626. self.apertures[last_path_aperture] = dict()
  627. if 'geometry' not in self.apertures[last_path_aperture]:
  628. self.apertures[last_path_aperture]['geometry'] = []
  629. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  630. path = [path[-1]]
  631. making_region = True
  632. continue
  633. # ############################################################# ##
  634. # G37* - End region
  635. # ############################################################# ##
  636. if self.regionoff_re.search(gline):
  637. making_region = False
  638. if '0' not in self.apertures:
  639. self.apertures['0'] = {}
  640. self.apertures['0']['type'] = 'REG'
  641. self.apertures['0']['size'] = 0.0
  642. self.apertures['0']['geometry'] = []
  643. # if D02 happened before G37 we now have a path with 1 element only; we have to add the current
  644. # geo to the poly_buffer otherwise we loose it
  645. if current_operation_code == 2:
  646. if len(path) == 1:
  647. # this means that the geometry was prepared previously and we just need to add it
  648. geo_dict = dict()
  649. if geo_f:
  650. if not geo_f.is_empty:
  651. follow_buffer.append(geo_f)
  652. geo_dict['follow'] = geo_f
  653. if geo_s:
  654. if not geo_s.is_empty:
  655. if self.app.defaults['gerber_simplification']:
  656. poly_buffer.append(geo_s.simplify(s_tol))
  657. else:
  658. poly_buffer.append(geo_s)
  659. if self.is_lpc is True:
  660. geo_dict['clear'] = geo_s
  661. else:
  662. geo_dict['solid'] = geo_s
  663. if geo_s or geo_f:
  664. self.apertures['0']['geometry'].append(deepcopy(geo_dict))
  665. path = [[current_x, current_y]] # Start new path
  666. # Only one path defines region?
  667. # This can happen if D02 happened before G37 and
  668. # is not and error.
  669. if len(path) < 3:
  670. # print "ERROR: Path contains less than 3 points:"
  671. # path = [[current_x, current_y]]
  672. continue
  673. # For regions we may ignore an aperture that is None
  674. # --- Buffered ---
  675. geo_dict = dict()
  676. region_f = Polygon(path).exterior
  677. if not region_f.is_empty:
  678. follow_buffer.append(region_f)
  679. geo_dict['follow'] = region_f
  680. region_s = Polygon(path)
  681. if not region_s.is_valid:
  682. region_s = region_s.buffer(0, int(self.steps_per_circle / 4))
  683. if not region_s.is_empty:
  684. if self.app.defaults['gerber_simplification']:
  685. poly_buffer.append(region_s.simplify(s_tol))
  686. else:
  687. poly_buffer.append(region_s)
  688. if self.is_lpc is True:
  689. geo_dict['clear'] = region_s
  690. else:
  691. geo_dict['solid'] = region_s
  692. if not region_s.is_empty or not region_f.is_empty:
  693. self.apertures['0']['geometry'].append(deepcopy(geo_dict))
  694. path = [[current_x, current_y]] # Start new path
  695. continue
  696. # ## G01/2/3* - Interpolation mode change
  697. # Can occur along with coordinates and operation code but
  698. # sometimes by itself (handled here).
  699. # Example: G01*
  700. match = self.interp_re.search(gline)
  701. if match:
  702. current_interpolation_mode = int(match.group(1))
  703. continue
  704. # ## G01 - Linear interpolation plus flashes
  705. # Operation code (D0x) missing is deprecated... oh well I will support it.
  706. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  707. match = self.lin_re.search(gline)
  708. if match:
  709. # Dxx alone?
  710. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  711. # try:
  712. # current_operation_code = int(match.group(4))
  713. # except:
  714. # pass # A line with just * will match too.
  715. # continue
  716. # NOTE: Letting it continue allows it to react to the
  717. # operation code.
  718. # Parse coordinates
  719. if match.group(2) is not None:
  720. linear_x = parse_gerber_number(match.group(2),
  721. self.int_digits, self.frac_digits, self.gerber_zeros)
  722. current_x = linear_x
  723. else:
  724. linear_x = current_x
  725. if match.group(3) is not None:
  726. linear_y = parse_gerber_number(match.group(3),
  727. self.int_digits, self.frac_digits, self.gerber_zeros)
  728. current_y = linear_y
  729. else:
  730. linear_y = current_y
  731. # Parse operation code
  732. if match.group(4) is not None:
  733. current_operation_code = int(match.group(4))
  734. # Pen down: add segment
  735. if current_operation_code == 1:
  736. # if linear_x or linear_y are None, ignore those
  737. if current_x is not None and current_y is not None:
  738. # only add the point if it's a new one otherwise skip it (harder to process)
  739. if path[-1] != [current_x, current_y]:
  740. path.append([current_x, current_y])
  741. if making_region is False:
  742. # if the aperture is rectangle then add a rectangular shape having as parameters the
  743. # coordinates of the start and end point and also the width and height
  744. # of the 'R' aperture
  745. try:
  746. if self.apertures[current_aperture]["type"] == 'R':
  747. width = self.apertures[current_aperture]['width']
  748. height = self.apertures[current_aperture]['height']
  749. minx = min(path[0][0], path[1][0]) - width / 2
  750. maxx = max(path[0][0], path[1][0]) + width / 2
  751. miny = min(path[0][1], path[1][1]) - height / 2
  752. maxy = max(path[0][1], path[1][1]) + height / 2
  753. log.debug("Coords: %s - %s - %s - %s" % (minx, miny, maxx, maxy))
  754. geo_dict = dict()
  755. geo_f = Point([current_x, current_y])
  756. follow_buffer.append(geo_f)
  757. geo_dict['follow'] = geo_f
  758. geo_s = shply_box(minx, miny, maxx, maxy)
  759. if self.app.defaults['gerber_simplification']:
  760. poly_buffer.append(geo_s.simplify(s_tol))
  761. else:
  762. poly_buffer.append(geo_s)
  763. if self.is_lpc is True:
  764. geo_dict['clear'] = geo_s
  765. else:
  766. geo_dict['solid'] = geo_s
  767. if current_aperture not in self.apertures:
  768. self.apertures[current_aperture] = dict()
  769. if 'geometry' not in self.apertures[current_aperture]:
  770. self.apertures[current_aperture]['geometry'] = []
  771. self.apertures[current_aperture]['geometry'].append(deepcopy(geo_dict))
  772. except Exception as e:
  773. pass
  774. last_path_aperture = current_aperture
  775. # we do this for the case that a region is done without having defined any aperture
  776. if last_path_aperture is None:
  777. if '0' not in self.apertures:
  778. self.apertures['0'] = {}
  779. self.apertures['0']['type'] = 'REG'
  780. self.apertures['0']['size'] = 0.0
  781. self.apertures['0']['geometry'] = []
  782. last_path_aperture = '0'
  783. else:
  784. self.app.inform.emit('[WARNING] %s: %s' %
  785. (_("Coordinates missing, line ignored"), str(gline)))
  786. self.app.inform.emit('[WARNING_NOTCL] %s' %
  787. _("GERBER file might be CORRUPT. Check the file !!!"))
  788. elif current_operation_code == 2:
  789. if len(path) > 1:
  790. geo_s = None
  791. geo_dict = dict()
  792. # --- BUFFERED ---
  793. # this treats the case when we are storing geometry as paths only
  794. if making_region:
  795. # we do this for the case that a region is done without having defined any aperture
  796. if last_path_aperture is None:
  797. if '0' not in self.apertures:
  798. self.apertures['0'] = {}
  799. self.apertures['0']['type'] = 'REG'
  800. self.apertures['0']['size'] = 0.0
  801. self.apertures['0']['geometry'] = []
  802. last_path_aperture = '0'
  803. geo_f = Polygon()
  804. else:
  805. geo_f = LineString(path)
  806. try:
  807. if self.apertures[last_path_aperture]["type"] != 'R':
  808. if not geo_f.is_empty:
  809. follow_buffer.append(geo_f)
  810. geo_dict['follow'] = geo_f
  811. except Exception as e:
  812. log.debug("camlib.Gerber.parse_lines() --> %s" % str(e))
  813. if not geo_f.is_empty:
  814. follow_buffer.append(geo_f)
  815. geo_dict['follow'] = geo_f
  816. # this treats the case when we are storing geometry as solids
  817. if making_region:
  818. # we do this for the case that a region is done without having defined any aperture
  819. if last_path_aperture is None:
  820. if '0' not in self.apertures:
  821. self.apertures['0'] = {}
  822. self.apertures['0']['type'] = 'REG'
  823. self.apertures['0']['size'] = 0.0
  824. self.apertures['0']['geometry'] = []
  825. last_path_aperture = '0'
  826. try:
  827. geo_s = Polygon(path)
  828. except ValueError:
  829. log.warning("Problem %s %s" % (gline, line_num))
  830. self.app.inform.emit('[ERROR] %s: %s' %
  831. (_("Region does not have enough points. "
  832. "File will be processed but there are parser errors. "
  833. "Line number"), str(line_num)))
  834. else:
  835. if last_path_aperture is None:
  836. log.warning("No aperture defined for curent path. (%d)" % line_num)
  837. width = self.apertures[last_path_aperture]["size"] # TODO: WARNING this should fail!
  838. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  839. try:
  840. if self.apertures[last_path_aperture]["type"] != 'R':
  841. if not geo_s.is_empty:
  842. if self.app.defaults['gerber_simplification']:
  843. poly_buffer.append(geo_s.simplify(s_tol))
  844. else:
  845. poly_buffer.append(geo_s)
  846. if self.is_lpc is True:
  847. geo_dict['clear'] = geo_s
  848. else:
  849. geo_dict['solid'] = geo_s
  850. except Exception as e:
  851. log.debug("camlib.Gerber.parse_lines() --> %s" % str(e))
  852. if self.app.defaults['gerber_simplification']:
  853. poly_buffer.append(geo_s.simplify(s_tol))
  854. else:
  855. poly_buffer.append(geo_s)
  856. if self.is_lpc is True:
  857. geo_dict['clear'] = geo_s
  858. else:
  859. geo_dict['solid'] = geo_s
  860. if last_path_aperture not in self.apertures:
  861. self.apertures[last_path_aperture] = dict()
  862. if 'geometry' not in self.apertures[last_path_aperture]:
  863. self.apertures[last_path_aperture]['geometry'] = []
  864. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  865. # if linear_x or linear_y are None, ignore those
  866. if linear_x is not None and linear_y is not None:
  867. path = [[linear_x, linear_y]] # Start new path
  868. else:
  869. self.app.inform.emit('[WARNING] %s: %s' %
  870. (_("Coordinates missing, line ignored"), str(gline)))
  871. self.app.inform.emit('[WARNING_NOTCL] %s' %
  872. _("GERBER file might be CORRUPT. Check the file !!!"))
  873. # Flash
  874. # Not allowed in region mode.
  875. elif current_operation_code == 3:
  876. # Create path draw so far.
  877. if len(path) > 1:
  878. # --- Buffered ----
  879. geo_dict = dict()
  880. # this treats the case when we are storing geometry as paths
  881. geo_f = LineString(path)
  882. if not geo_f.is_empty:
  883. try:
  884. if self.apertures[last_path_aperture]["type"] != 'R':
  885. follow_buffer.append(geo_f)
  886. geo_dict['follow'] = geo_f
  887. except Exception as e:
  888. log.debug("camlib.Gerber.parse_lines() --> G01 match D03 --> %s" % str(e))
  889. follow_buffer.append(geo_f)
  890. geo_dict['follow'] = geo_f
  891. # this treats the case when we are storing geometry as solids
  892. width = self.apertures[last_path_aperture]["size"]
  893. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  894. if not geo_s.is_empty:
  895. try:
  896. if self.apertures[last_path_aperture]["type"] != 'R':
  897. if self.app.defaults['gerber_simplification']:
  898. poly_buffer.append(geo_s.simplify(s_tol))
  899. else:
  900. poly_buffer.append(geo_s)
  901. if self.is_lpc is True:
  902. geo_dict['clear'] = geo_s
  903. else:
  904. geo_dict['solid'] = geo_s
  905. except:
  906. if self.app.defaults['gerber_simplification']:
  907. poly_buffer.append(geo_s.simplify(s_tol))
  908. else:
  909. poly_buffer.append(geo_s)
  910. if self.is_lpc is True:
  911. geo_dict['clear'] = geo_s
  912. else:
  913. geo_dict['solid'] = geo_s
  914. if last_path_aperture not in self.apertures:
  915. self.apertures[last_path_aperture] = dict()
  916. if 'geometry' not in self.apertures[last_path_aperture]:
  917. self.apertures[last_path_aperture]['geometry'] = []
  918. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  919. # Reset path starting point
  920. path = [[linear_x, linear_y]]
  921. # --- BUFFERED ---
  922. # Draw the flash
  923. # this treats the case when we are storing geometry as paths
  924. geo_dict = dict()
  925. geo_flash = Point([linear_x, linear_y])
  926. follow_buffer.append(geo_flash)
  927. geo_dict['follow'] = geo_flash
  928. # this treats the case when we are storing geometry as solids
  929. flash = self.create_flash_geometry(
  930. Point([linear_x, linear_y]),
  931. self.apertures[current_aperture],
  932. self.steps_per_circle
  933. )
  934. if not flash.is_empty:
  935. if self.app.defaults['gerber_simplification']:
  936. poly_buffer.append(flash.simplify(s_tol))
  937. else:
  938. poly_buffer.append(flash)
  939. if self.is_lpc is True:
  940. geo_dict['clear'] = flash
  941. else:
  942. geo_dict['solid'] = flash
  943. if current_aperture not in self.apertures:
  944. self.apertures[current_aperture] = dict()
  945. if 'geometry' not in self.apertures[current_aperture]:
  946. self.apertures[current_aperture]['geometry'] = []
  947. self.apertures[current_aperture]['geometry'].append(deepcopy(geo_dict))
  948. # maybe those lines are not exactly needed but it is easier to read the program as those coordinates
  949. # are used in case that circular interpolation is encountered within the Gerber file
  950. current_x = linear_x
  951. current_y = linear_y
  952. # log.debug("Line_number=%3s X=%s Y=%s (%s)" % (line_num, linear_x, linear_y, gline))
  953. continue
  954. # ## G74/75* - Single or multiple quadrant arcs
  955. match = self.quad_re.search(gline)
  956. if match:
  957. if match.group(1) == '4':
  958. quadrant_mode = 'SINGLE'
  959. else:
  960. quadrant_mode = 'MULTI'
  961. continue
  962. # ## G02/3 - Circular interpolation
  963. # 2-clockwise, 3-counterclockwise
  964. # Ex. format: G03 X0 Y50 I-50 J0 where the X, Y coords are the coords of the End Point
  965. match = self.circ_re.search(gline)
  966. if match:
  967. arcdir = [None, None, "cw", "ccw"]
  968. mode, circular_x, circular_y, i, j, d = match.groups()
  969. try:
  970. circular_x = parse_gerber_number(circular_x,
  971. self.int_digits, self.frac_digits, self.gerber_zeros)
  972. except Exception as e:
  973. circular_x = current_x
  974. try:
  975. circular_y = parse_gerber_number(circular_y,
  976. self.int_digits, self.frac_digits, self.gerber_zeros)
  977. except Exception as e:
  978. circular_y = current_y
  979. # According to Gerber specification i and j are not modal, which means that when i or j are missing,
  980. # they are to be interpreted as being zero
  981. try:
  982. i = parse_gerber_number(i, self.int_digits, self.frac_digits, self.gerber_zeros)
  983. except Exception as e:
  984. i = 0
  985. try:
  986. j = parse_gerber_number(j, self.int_digits, self.frac_digits, self.gerber_zeros)
  987. except Exception as e:
  988. j = 0
  989. if quadrant_mode is None:
  990. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  991. log.error(gline)
  992. continue
  993. if mode is None and current_interpolation_mode not in [2, 3]:
  994. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  995. log.error(gline)
  996. continue
  997. elif mode is not None:
  998. current_interpolation_mode = int(mode)
  999. # Set operation code if provided
  1000. if d is not None:
  1001. current_operation_code = int(d)
  1002. # Nothing created! Pen Up.
  1003. if current_operation_code == 2:
  1004. log.warning("Arc with D2. (%d)" % line_num)
  1005. if len(path) > 1:
  1006. geo_dict = dict()
  1007. if last_path_aperture is None:
  1008. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1009. # --- BUFFERED ---
  1010. width = self.apertures[last_path_aperture]["size"]
  1011. # this treats the case when we are storing geometry as paths
  1012. geo_f = LineString(path)
  1013. if not geo_f.is_empty:
  1014. follow_buffer.append(geo_f)
  1015. geo_dict['follow'] = geo_f
  1016. # this treats the case when we are storing geometry as solids
  1017. buffered = LineString(path).buffer(width / 1.999, int(self.steps_per_circle))
  1018. if not buffered.is_empty:
  1019. if self.app.defaults['gerber_simplification']:
  1020. poly_buffer.append(buffered.simplify(s_tol))
  1021. else:
  1022. poly_buffer.append(buffered)
  1023. if self.is_lpc is True:
  1024. geo_dict['clear'] = buffered
  1025. else:
  1026. geo_dict['solid'] = buffered
  1027. if last_path_aperture not in self.apertures:
  1028. self.apertures[last_path_aperture] = dict()
  1029. if 'geometry' not in self.apertures[last_path_aperture]:
  1030. self.apertures[last_path_aperture]['geometry'] = []
  1031. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  1032. current_x = circular_x
  1033. current_y = circular_y
  1034. path = [[current_x, current_y]] # Start new path
  1035. continue
  1036. # Flash should not happen here
  1037. if current_operation_code == 3:
  1038. log.error("Trying to flash within arc. (%d)" % line_num)
  1039. continue
  1040. if quadrant_mode == 'MULTI':
  1041. center = [i + current_x, j + current_y]
  1042. radius = sqrt(i ** 2 + j ** 2)
  1043. start = arctan2(-j, -i) # Start angle
  1044. # Numerical errors might prevent start == stop therefore
  1045. # we check ahead of time. This should result in a
  1046. # 360 degree arc.
  1047. if current_x == circular_x and current_y == circular_y:
  1048. stop = start
  1049. else:
  1050. stop = arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  1051. this_arc = arc(center, radius, start, stop,
  1052. arcdir[current_interpolation_mode],
  1053. self.steps_per_circle)
  1054. # The last point in the computed arc can have
  1055. # numerical errors. The exact final point is the
  1056. # specified (x, y). Replace.
  1057. this_arc[-1] = (circular_x, circular_y)
  1058. # Last point in path is current point
  1059. # current_x = this_arc[-1][0]
  1060. # current_y = this_arc[-1][1]
  1061. current_x, current_y = circular_x, circular_y
  1062. # Append
  1063. path += this_arc
  1064. last_path_aperture = current_aperture
  1065. continue
  1066. if quadrant_mode == 'SINGLE':
  1067. center_candidates = [
  1068. [i + current_x, j + current_y],
  1069. [-i + current_x, j + current_y],
  1070. [i + current_x, -j + current_y],
  1071. [-i + current_x, -j + current_y]
  1072. ]
  1073. valid = False
  1074. log.debug("I: %f J: %f" % (i, j))
  1075. for center in center_candidates:
  1076. radius = sqrt(i ** 2 + j ** 2)
  1077. # Make sure radius to start is the same as radius to end.
  1078. radius2 = sqrt((center[0] - circular_x) ** 2 + (center[1] - circular_y) ** 2)
  1079. if radius2 < radius * 0.95 or radius2 > radius * 1.05:
  1080. continue # Not a valid center.
  1081. # Correct i and j and continue as with multi-quadrant.
  1082. i = center[0] - current_x
  1083. j = center[1] - current_y
  1084. start = arctan2(-j, -i) # Start angle
  1085. stop = arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  1086. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  1087. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  1088. (current_x, current_y, center[0], center[1], circular_x, circular_y))
  1089. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  1090. (start * 180 / pi, stop * 180 / pi, arcdir[current_interpolation_mode],
  1091. angle * 180 / pi, pi / 2 * 180 / pi, angle <= (pi + 1e-6) / 2))
  1092. if angle <= (pi + 1e-6) / 2:
  1093. log.debug("########## ACCEPTING ARC ############")
  1094. this_arc = arc(center, radius, start, stop,
  1095. arcdir[current_interpolation_mode],
  1096. self.steps_per_circle)
  1097. # Replace with exact values
  1098. this_arc[-1] = (circular_x, circular_y)
  1099. # current_x = this_arc[-1][0]
  1100. # current_y = this_arc[-1][1]
  1101. current_x, current_y = circular_x, circular_y
  1102. path += this_arc
  1103. last_path_aperture = current_aperture
  1104. valid = True
  1105. break
  1106. if valid:
  1107. continue
  1108. else:
  1109. log.warning("Invalid arc in line %d." % line_num)
  1110. # ## EOF
  1111. match = self.eof_re.search(gline)
  1112. if match:
  1113. continue
  1114. # ## Line did not match any pattern. Warn user.
  1115. log.warning("Line ignored (%d): %s" % (line_num, gline))
  1116. if len(path) > 1:
  1117. # In case that G01 (moving) aperture is rectangular, there is no need to still create
  1118. # another geo since we already created a shapely box using the start and end coordinates found in
  1119. # path variable. We do it only for other apertures than 'R' type
  1120. if self.apertures[last_path_aperture]["type"] == 'R':
  1121. pass
  1122. else:
  1123. # EOF, create shapely LineString if something still in path
  1124. # ## --- Buffered ---
  1125. geo_dict = dict()
  1126. # this treats the case when we are storing geometry as paths
  1127. geo_f = LineString(path)
  1128. if not geo_f.is_empty:
  1129. follow_buffer.append(geo_f)
  1130. geo_dict['follow'] = geo_f
  1131. # this treats the case when we are storing geometry as solids
  1132. width = self.apertures[last_path_aperture]["size"]
  1133. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  1134. if not geo_s.is_empty:
  1135. if self.app.defaults['gerber_simplification']:
  1136. poly_buffer.append(geo_s.simplify(s_tol))
  1137. else:
  1138. poly_buffer.append(geo_s)
  1139. if self.is_lpc is True:
  1140. geo_dict['clear'] = geo_s
  1141. else:
  1142. geo_dict['solid'] = geo_s
  1143. if last_path_aperture not in self.apertures:
  1144. self.apertures[last_path_aperture] = dict()
  1145. if 'geometry' not in self.apertures[last_path_aperture]:
  1146. self.apertures[last_path_aperture]['geometry'] = []
  1147. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  1148. # TODO: make sure to keep track of units changes because right now it seems to happen in a weird way
  1149. # find out the conversion factor used to convert inside the self.apertures keys: size, width, height
  1150. file_units = self.gerber_units if self.gerber_units else 'IN'
  1151. app_units = self.app.defaults['units']
  1152. conversion_factor = 25.4 if file_units == 'IN' else (1 / 25.4) if file_units != app_units else 1
  1153. # --- Apply buffer ---
  1154. # this treats the case when we are storing geometry as paths
  1155. self.follow_geometry = follow_buffer
  1156. # this treats the case when we are storing geometry as solids
  1157. if len(poly_buffer) == 0:
  1158. log.error("Object is not Gerber file or empty. Aborting Object creation.")
  1159. return 'fail'
  1160. log.warning("Joining %d polygons." % len(poly_buffer))
  1161. self.app.inform.emit('%s: %d.' % (_("Gerber processing. Joining polygons"), len(poly_buffer)))
  1162. if self.use_buffer_for_union:
  1163. log.debug("Union by buffer...")
  1164. new_poly = MultiPolygon(poly_buffer)
  1165. if self.app.defaults["gerber_buffering"] == 'full':
  1166. new_poly = new_poly.buffer(0.00000001)
  1167. new_poly = new_poly.buffer(-0.00000001)
  1168. log.warning("Union(buffer) done.")
  1169. else:
  1170. log.debug("Union by union()...")
  1171. new_poly = cascaded_union(poly_buffer)
  1172. new_poly = new_poly.buffer(0, int(self.steps_per_circle / 4))
  1173. log.warning("Union done.")
  1174. if current_polarity == 'D':
  1175. self.app.inform.emit('%s' % _("Gerber processing. Applying Gerber polarity."))
  1176. if new_poly.is_valid:
  1177. self.solid_geometry = self.solid_geometry.union(new_poly)
  1178. else:
  1179. # I do this so whenever the parsed geometry of the file is not valid (intersections) it is still
  1180. # loaded. Instead of applying a union I add to a list of polygons.
  1181. final_poly = []
  1182. try:
  1183. for poly in new_poly:
  1184. final_poly.append(poly)
  1185. except TypeError:
  1186. final_poly.append(new_poly)
  1187. try:
  1188. for poly in self.solid_geometry:
  1189. final_poly.append(poly)
  1190. except TypeError:
  1191. final_poly.append(self.solid_geometry)
  1192. self.solid_geometry = final_poly
  1193. # try:
  1194. # self.solid_geometry = self.solid_geometry.union(new_poly)
  1195. # except Exception as e:
  1196. # # in case in the new_poly are some self intersections try to avoid making union with them
  1197. # for poly in new_poly:
  1198. # try:
  1199. # self.solid_geometry = self.solid_geometry.union(poly)
  1200. # except:
  1201. # pass
  1202. else:
  1203. self.solid_geometry = self.solid_geometry.difference(new_poly)
  1204. except Exception as err:
  1205. ex_type, ex, tb = sys.exc_info()
  1206. traceback.print_tb(tb)
  1207. # print traceback.format_exc()
  1208. log.error("Gerber PARSING FAILED. Line %d: %s" % (line_num, gline))
  1209. loc = '%s #%d %s: %s\n' % (_("Gerber Line"), line_num, _("Gerber Line Content"), gline) + repr(err)
  1210. self.app.inform.emit('[ERROR] %s\n%s:' %
  1211. (_("Gerber Parser ERROR"), loc))
  1212. @staticmethod
  1213. def create_flash_geometry(location, aperture, steps_per_circle=None):
  1214. # log.debug('Flashing @%s, Aperture: %s' % (location, aperture))
  1215. if type(location) == list:
  1216. location = Point(location)
  1217. if aperture['type'] == 'C': # Circles
  1218. return location.buffer(aperture['size'] / 2, int(steps_per_circle / 4))
  1219. if aperture['type'] == 'R': # Rectangles
  1220. loc = location.coords[0]
  1221. width = aperture['width']
  1222. height = aperture['height']
  1223. minx = loc[0] - width / 2
  1224. maxx = loc[0] + width / 2
  1225. miny = loc[1] - height / 2
  1226. maxy = loc[1] + height / 2
  1227. return shply_box(minx, miny, maxx, maxy)
  1228. if aperture['type'] == 'O': # Obround
  1229. loc = location.coords[0]
  1230. width = aperture['width']
  1231. height = aperture['height']
  1232. if width > height:
  1233. p1 = Point(loc[0] + 0.5 * (width - height), loc[1])
  1234. p2 = Point(loc[0] - 0.5 * (width - height), loc[1])
  1235. c1 = p1.buffer(height * 0.5, int(steps_per_circle / 4))
  1236. c2 = p2.buffer(height * 0.5, int(steps_per_circle / 4))
  1237. else:
  1238. p1 = Point(loc[0], loc[1] + 0.5 * (height - width))
  1239. p2 = Point(loc[0], loc[1] - 0.5 * (height - width))
  1240. c1 = p1.buffer(width * 0.5, int(steps_per_circle / 4))
  1241. c2 = p2.buffer(width * 0.5, int(steps_per_circle / 4))
  1242. return cascaded_union([c1, c2]).convex_hull
  1243. if aperture['type'] == 'P': # Regular polygon
  1244. loc = location.coords[0]
  1245. diam = aperture['diam']
  1246. n_vertices = aperture['nVertices']
  1247. points = []
  1248. for i in range(0, n_vertices):
  1249. x = loc[0] + 0.5 * diam * (cos(2 * pi * i / n_vertices))
  1250. y = loc[1] + 0.5 * diam * (sin(2 * pi * i / n_vertices))
  1251. points.append((x, y))
  1252. ply = Polygon(points)
  1253. if 'rotation' in aperture:
  1254. ply = affinity.rotate(ply, aperture['rotation'])
  1255. return ply
  1256. if aperture['type'] == 'AM': # Aperture Macro
  1257. loc = location.coords[0]
  1258. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1259. if flash_geo.is_empty:
  1260. log.warning("Empty geometry for Aperture Macro: %s" % str(aperture['macro'].name))
  1261. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1262. log.warning("Unknown aperture type: %s" % aperture['type'])
  1263. return None
  1264. def create_geometry(self):
  1265. """
  1266. Geometry from a Gerber file is made up entirely of polygons.
  1267. Every stroke (linear or circular) has an aperture which gives
  1268. it thickness. Additionally, aperture strokes have non-zero area,
  1269. and regions naturally do as well.
  1270. :rtype : None
  1271. :return: None
  1272. """
  1273. pass
  1274. # self.buffer_paths()
  1275. #
  1276. # self.fix_regions()
  1277. #
  1278. # self.do_flashes()
  1279. #
  1280. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1281. # [poly['polygon'] for poly in self.regions] +
  1282. # self.flash_geometry)
  1283. def get_bounding_box(self, margin=0.0, rounded=False):
  1284. """
  1285. Creates and returns a rectangular polygon bounding at a distance of
  1286. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1287. can optionally have rounded corners of radius equal to margin.
  1288. :param margin: Distance to enlarge the rectangular bounding
  1289. box in both positive and negative, x and y axes.
  1290. :type margin: float
  1291. :param rounded: Wether or not to have rounded corners.
  1292. :type rounded: bool
  1293. :return: The bounding box.
  1294. :rtype: Shapely.Polygon
  1295. """
  1296. bbox = self.solid_geometry.envelope.buffer(margin)
  1297. if not rounded:
  1298. bbox = bbox.envelope
  1299. return bbox
  1300. def bounds(self):
  1301. """
  1302. Returns coordinates of rectangular bounds
  1303. of Gerber geometry: (xmin, ymin, xmax, ymax).
  1304. """
  1305. # fixed issue of getting bounds only for one level lists of objects
  1306. # now it can get bounds for nested lists of objects
  1307. log.debug("camlib.Gerber.bounds()")
  1308. if self.solid_geometry is None:
  1309. log.debug("solid_geometry is None")
  1310. return 0, 0, 0, 0
  1311. def bounds_rec(obj):
  1312. if type(obj) is list and type(obj) is not MultiPolygon:
  1313. minx = Inf
  1314. miny = Inf
  1315. maxx = -Inf
  1316. maxy = -Inf
  1317. for k in obj:
  1318. if type(k) is dict:
  1319. for key in k:
  1320. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  1321. minx = min(minx, minx_)
  1322. miny = min(miny, miny_)
  1323. maxx = max(maxx, maxx_)
  1324. maxy = max(maxy, maxy_)
  1325. else:
  1326. if not k.is_empty:
  1327. try:
  1328. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1329. except Exception as e:
  1330. log.debug("camlib.Gerber.bounds() --> %s" % str(e))
  1331. return
  1332. minx = min(minx, minx_)
  1333. miny = min(miny, miny_)
  1334. maxx = max(maxx, maxx_)
  1335. maxy = max(maxy, maxy_)
  1336. return minx, miny, maxx, maxy
  1337. else:
  1338. # it's a Shapely object, return it's bounds
  1339. return obj.bounds
  1340. bounds_coords = bounds_rec(self.solid_geometry)
  1341. return bounds_coords
  1342. def scale(self, xfactor, yfactor=None, point=None):
  1343. """
  1344. Scales the objects' geometry on the XY plane by a given factor.
  1345. These are:
  1346. * ``buffered_paths``
  1347. * ``flash_geometry``
  1348. * ``solid_geometry``
  1349. * ``regions``
  1350. NOTE:
  1351. Does not modify the data used to create these elements. If these
  1352. are recreated, the scaling will be lost. This behavior was modified
  1353. because of the complexity reached in this class.
  1354. :param xfactor: Number by which to scale on X axis.
  1355. :type xfactor: float
  1356. :param yfactor: Number by which to scale on Y axis.
  1357. :type yfactor: float
  1358. :param point: reference point for scaling operation
  1359. :rtype : None
  1360. """
  1361. log.debug("camlib.Gerber.scale()")
  1362. try:
  1363. xfactor = float(xfactor)
  1364. except:
  1365. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1366. _("Scale factor has to be a number: integer or float."))
  1367. return
  1368. if yfactor is None:
  1369. yfactor = xfactor
  1370. else:
  1371. try:
  1372. yfactor = float(yfactor)
  1373. except:
  1374. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1375. _("Scale factor has to be a number: integer or float."))
  1376. return
  1377. if point is None:
  1378. px = 0
  1379. py = 0
  1380. else:
  1381. px, py = point
  1382. # variables to display the percentage of work done
  1383. self.geo_len = 0
  1384. try:
  1385. for __ in self.solid_geometry:
  1386. self.geo_len += 1
  1387. except TypeError:
  1388. self.geo_len = 1
  1389. self.old_disp_number = 0
  1390. self.el_count = 0
  1391. def scale_geom(obj):
  1392. if type(obj) is list:
  1393. new_obj = []
  1394. for g in obj:
  1395. new_obj.append(scale_geom(g))
  1396. return new_obj
  1397. else:
  1398. try:
  1399. self.el_count += 1
  1400. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 99]))
  1401. if self.old_disp_number < disp_number <= 100:
  1402. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1403. self.old_disp_number = disp_number
  1404. return affinity.scale(obj, xfactor, yfactor, origin=(px, py))
  1405. except AttributeError:
  1406. return obj
  1407. self.solid_geometry = scale_geom(self.solid_geometry)
  1408. self.follow_geometry = scale_geom(self.follow_geometry)
  1409. # we need to scale the geometry stored in the Gerber apertures, too
  1410. try:
  1411. for apid in self.apertures:
  1412. if 'geometry' in self.apertures[apid]:
  1413. for geo_el in self.apertures[apid]['geometry']:
  1414. if 'solid' in geo_el:
  1415. geo_el['solid'] = scale_geom(geo_el['solid'])
  1416. if 'follow' in geo_el:
  1417. geo_el['follow'] = scale_geom(geo_el['follow'])
  1418. if 'clear' in geo_el:
  1419. geo_el['clear'] = scale_geom(geo_el['clear'])
  1420. except Exception as e:
  1421. log.debug('camlib.Gerber.scale() Exception --> %s' % str(e))
  1422. return 'fail'
  1423. self.app.inform.emit('[success] %s' %
  1424. _("Gerber Scale done."))
  1425. self.app.proc_container.new_text = ''
  1426. # ## solid_geometry ???
  1427. # It's a cascaded union of objects.
  1428. # self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  1429. # factor, origin=(0, 0))
  1430. # # Now buffered_paths, flash_geometry and solid_geometry
  1431. # self.create_geometry()
  1432. def offset(self, vect):
  1433. """
  1434. Offsets the objects' geometry on the XY plane by a given vector.
  1435. These are:
  1436. * ``buffered_paths``
  1437. * ``flash_geometry``
  1438. * ``solid_geometry``
  1439. * ``regions``
  1440. NOTE:
  1441. Does not modify the data used to create these elements. If these
  1442. are recreated, the scaling will be lost. This behavior was modified
  1443. because of the complexity reached in this class.
  1444. :param vect: (x, y) offset vector.
  1445. :type vect: tuple
  1446. :return: None
  1447. """
  1448. log.debug("camlib.Gerber.offset()")
  1449. try:
  1450. dx, dy = vect
  1451. except TypeError:
  1452. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1453. _("An (x,y) pair of values are needed. "
  1454. "Probable you entered only one value in the Offset field."))
  1455. return
  1456. # variables to display the percentage of work done
  1457. self.geo_len = 0
  1458. try:
  1459. for __ in self.solid_geometry:
  1460. self.geo_len += 1
  1461. except TypeError:
  1462. self.geo_len = 1
  1463. self.old_disp_number = 0
  1464. self.el_count = 0
  1465. def offset_geom(obj):
  1466. if type(obj) is list:
  1467. new_obj = []
  1468. for g in obj:
  1469. new_obj.append(offset_geom(g))
  1470. return new_obj
  1471. else:
  1472. try:
  1473. self.el_count += 1
  1474. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 99]))
  1475. if self.old_disp_number < disp_number <= 100:
  1476. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1477. self.old_disp_number = disp_number
  1478. return affinity.translate(obj, xoff=dx, yoff=dy)
  1479. except AttributeError:
  1480. return obj
  1481. # ## Solid geometry
  1482. self.solid_geometry = offset_geom(self.solid_geometry)
  1483. self.follow_geometry = offset_geom(self.follow_geometry)
  1484. # we need to offset the geometry stored in the Gerber apertures, too
  1485. try:
  1486. for apid in self.apertures:
  1487. if 'geometry' in self.apertures[apid]:
  1488. for geo_el in self.apertures[apid]['geometry']:
  1489. if 'solid' in geo_el:
  1490. geo_el['solid'] = offset_geom(geo_el['solid'])
  1491. if 'follow' in geo_el:
  1492. geo_el['follow'] = offset_geom(geo_el['follow'])
  1493. if 'clear' in geo_el:
  1494. geo_el['clear'] = offset_geom(geo_el['clear'])
  1495. except Exception as e:
  1496. log.debug('camlib.Gerber.offset() Exception --> %s' % str(e))
  1497. return 'fail'
  1498. self.app.inform.emit('[success] %s' %
  1499. _("Gerber Offset done."))
  1500. self.app.proc_container.new_text = ''
  1501. def mirror(self, axis, point):
  1502. """
  1503. Mirrors the object around a specified axis passing through
  1504. the given point. What is affected:
  1505. * ``buffered_paths``
  1506. * ``flash_geometry``
  1507. * ``solid_geometry``
  1508. * ``regions``
  1509. NOTE:
  1510. Does not modify the data used to create these elements. If these
  1511. are recreated, the scaling will be lost. This behavior was modified
  1512. because of the complexity reached in this class.
  1513. :param axis: "X" or "Y" indicates around which axis to mirror.
  1514. :type axis: str
  1515. :param point: [x, y] point belonging to the mirror axis.
  1516. :type point: list
  1517. :return: None
  1518. """
  1519. log.debug("camlib.Gerber.mirror()")
  1520. px, py = point
  1521. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1522. # variables to display the percentage of work done
  1523. self.geo_len = 0
  1524. try:
  1525. for __ in self.solid_geometry:
  1526. self.geo_len += 1
  1527. except TypeError:
  1528. self.geo_len = 1
  1529. self.old_disp_number = 0
  1530. self.el_count = 0
  1531. def mirror_geom(obj):
  1532. if type(obj) is list:
  1533. new_obj = []
  1534. for g in obj:
  1535. new_obj.append(mirror_geom(g))
  1536. return new_obj
  1537. else:
  1538. try:
  1539. self.el_count += 1
  1540. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 99]))
  1541. if self.old_disp_number < disp_number <= 100:
  1542. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1543. self.old_disp_number = disp_number
  1544. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1545. except AttributeError:
  1546. return obj
  1547. self.solid_geometry = mirror_geom(self.solid_geometry)
  1548. self.follow_geometry = mirror_geom(self.follow_geometry)
  1549. # we need to mirror the geometry stored in the Gerber apertures, too
  1550. try:
  1551. for apid in self.apertures:
  1552. if 'geometry' in self.apertures[apid]:
  1553. for geo_el in self.apertures[apid]['geometry']:
  1554. if 'solid' in geo_el:
  1555. geo_el['solid'] = mirror_geom(geo_el['solid'])
  1556. if 'follow' in geo_el:
  1557. geo_el['follow'] = mirror_geom(geo_el['follow'])
  1558. if 'clear' in geo_el:
  1559. geo_el['clear'] = mirror_geom(geo_el['clear'])
  1560. except Exception as e:
  1561. log.debug('camlib.Gerber.mirror() Exception --> %s' % str(e))
  1562. return 'fail'
  1563. self.app.inform.emit('[success] %s' %
  1564. _("Gerber Mirror done."))
  1565. self.app.proc_container.new_text = ''
  1566. def skew(self, angle_x, angle_y, point):
  1567. """
  1568. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1569. Parameters
  1570. ----------
  1571. angle_x, angle_y : float, float
  1572. The shear angle(s) for the x and y axes respectively. These can be
  1573. specified in either degrees (default) or radians by setting
  1574. use_radians=True.
  1575. See shapely manual for more information:
  1576. http://toblerity.org/shapely/manual.html#affine-transformations
  1577. :param angle_x: the angle on X axis for skewing
  1578. :param angle_y: the angle on Y axis for skewing
  1579. :param point: reference point for skewing operation
  1580. :return None
  1581. """
  1582. log.debug("camlib.Gerber.skew()")
  1583. px, py = point
  1584. # variables to display the percentage of work done
  1585. self.geo_len = 0
  1586. try:
  1587. for __ in self.solid_geometry:
  1588. self.geo_len += 1
  1589. except TypeError:
  1590. self.geo_len = 1
  1591. self.old_disp_number = 0
  1592. self.el_count = 0
  1593. def skew_geom(obj):
  1594. if type(obj) is list:
  1595. new_obj = []
  1596. for g in obj:
  1597. new_obj.append(skew_geom(g))
  1598. return new_obj
  1599. else:
  1600. try:
  1601. self.el_count += 1
  1602. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1603. if self.old_disp_number < disp_number <= 100:
  1604. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1605. self.old_disp_number = disp_number
  1606. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1607. except AttributeError:
  1608. return obj
  1609. self.solid_geometry = skew_geom(self.solid_geometry)
  1610. self.follow_geometry = skew_geom(self.follow_geometry)
  1611. # we need to skew the geometry stored in the Gerber apertures, too
  1612. try:
  1613. for apid in self.apertures:
  1614. if 'geometry' in self.apertures[apid]:
  1615. for geo_el in self.apertures[apid]['geometry']:
  1616. if 'solid' in geo_el:
  1617. geo_el['solid'] = skew_geom(geo_el['solid'])
  1618. if 'follow' in geo_el:
  1619. geo_el['follow'] = skew_geom(geo_el['follow'])
  1620. if 'clear' in geo_el:
  1621. geo_el['clear'] = skew_geom(geo_el['clear'])
  1622. except Exception as e:
  1623. log.debug('camlib.Gerber.skew() Exception --> %s' % str(e))
  1624. return 'fail'
  1625. self.app.inform.emit('[success] %s' % _("Gerber Skew done."))
  1626. self.app.proc_container.new_text = ''
  1627. def rotate(self, angle, point):
  1628. """
  1629. Rotate an object by a given angle around given coords (point)
  1630. :param angle:
  1631. :param point:
  1632. :return:
  1633. """
  1634. log.debug("camlib.Gerber.rotate()")
  1635. px, py = point
  1636. # variables to display the percentage of work done
  1637. self.geo_len = 0
  1638. try:
  1639. for __ in self.solid_geometry:
  1640. self.geo_len += 1
  1641. except TypeError:
  1642. self.geo_len = 1
  1643. self.old_disp_number = 0
  1644. self.el_count = 0
  1645. def rotate_geom(obj):
  1646. if type(obj) is list:
  1647. new_obj = []
  1648. for g in obj:
  1649. new_obj.append(rotate_geom(g))
  1650. return new_obj
  1651. else:
  1652. try:
  1653. self.el_count += 1
  1654. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1655. if self.old_disp_number < disp_number <= 100:
  1656. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1657. self.old_disp_number = disp_number
  1658. return affinity.rotate(obj, angle, origin=(px, py))
  1659. except AttributeError:
  1660. return obj
  1661. self.solid_geometry = rotate_geom(self.solid_geometry)
  1662. self.follow_geometry = rotate_geom(self.follow_geometry)
  1663. # we need to rotate the geometry stored in the Gerber apertures, too
  1664. try:
  1665. for apid in self.apertures:
  1666. if 'geometry' in self.apertures[apid]:
  1667. for geo_el in self.apertures[apid]['geometry']:
  1668. if 'solid' in geo_el:
  1669. geo_el['solid'] = rotate_geom(geo_el['solid'])
  1670. if 'follow' in geo_el:
  1671. geo_el['follow'] = rotate_geom(geo_el['follow'])
  1672. if 'clear' in geo_el:
  1673. geo_el['clear'] = rotate_geom(geo_el['clear'])
  1674. except Exception as e:
  1675. log.debug('camlib.Gerber.rotate() Exception --> %s' % str(e))
  1676. return 'fail'
  1677. self.app.inform.emit('[success] %s' %
  1678. _("Gerber Rotate done."))
  1679. self.app.proc_container.new_text = ''