ParseGerber.py 112 KB

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