ParseGerber.py 113 KB

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