ParseGerber.py 102 KB

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