ParseGerber.py 88 KB

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