ParseGerber.py 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305
  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. # Polarity change ###### ##
  347. # Example: %LPD*% or %LPC*%
  348. # If polarity changes, creates geometry from current
  349. # buffer, then adds or subtracts accordingly.
  350. match = self.lpol_re.search(gline)
  351. if match:
  352. new_polarity = match.group(1)
  353. # log.info("Polarity CHANGE, LPC = %s, poly_buff = %s" % (self.is_lpc, poly_buffer))
  354. self.is_lpc = True if new_polarity == 'C' else False
  355. if len(path) > 1 and current_polarity != new_polarity:
  356. # finish the current path and add it to the storage
  357. # --- Buffered ----
  358. width = self.apertures[last_path_aperture]["size"]
  359. geo_dict = dict()
  360. geo_f = LineString(path)
  361. if not geo_f.is_empty:
  362. follow_buffer.append(geo_f)
  363. geo_dict['follow'] = geo_f
  364. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  365. if not geo_s.is_empty and geo_s.is_valid:
  366. if self.app.defaults['gerber_simplification']:
  367. poly_buffer.append(geo_s.simplify(s_tol))
  368. else:
  369. poly_buffer.append(geo_s)
  370. if self.is_lpc is True:
  371. geo_dict['clear'] = geo_s
  372. else:
  373. geo_dict['solid'] = geo_s
  374. if last_path_aperture not in self.apertures:
  375. self.apertures[last_path_aperture] = dict()
  376. if 'geometry' not in self.apertures[last_path_aperture]:
  377. self.apertures[last_path_aperture]['geometry'] = []
  378. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  379. path = [path[-1]]
  380. # --- Apply buffer ---
  381. # If added for testing of bug #83
  382. # TODO: Remove when bug fixed
  383. if len(poly_buffer) > 0:
  384. if current_polarity == 'D':
  385. # self.follow_geometry = self.follow_geometry.union(cascaded_union(follow_buffer))
  386. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  387. else:
  388. # self.follow_geometry = self.follow_geometry.difference(cascaded_union(follow_buffer))
  389. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  390. # follow_buffer = []
  391. poly_buffer = []
  392. current_polarity = new_polarity
  393. continue
  394. # ################################################################
  395. # ##################### Number format ###########################
  396. # ##################### Example: %FSLAX24Y24*% #################
  397. # ################################################################
  398. 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. else:
  687. region_geo = Polygon(path)
  688. region_f = region_geo.exterior
  689. if not region_f.is_empty:
  690. follow_buffer.append(region_f)
  691. geo_dict['follow'] = region_f
  692. region_s = region_geo
  693. if not region_s.is_valid:
  694. region_s = region_s.buffer(0, int(self.steps_per_circle))
  695. if not region_s.is_empty:
  696. if self.app.defaults['gerber_simplification']:
  697. poly_buffer.append(region_s.simplify(s_tol))
  698. else:
  699. poly_buffer.append(region_s)
  700. if self.is_lpc is True:
  701. geo_dict['clear'] = region_s
  702. else:
  703. geo_dict['solid'] = region_s
  704. if not region_s.is_empty or not region_f.is_empty:
  705. self.apertures['0']['geometry'].append(deepcopy(geo_dict))
  706. path = [[current_x, current_y]] # Start new path
  707. continue
  708. # ################################################################
  709. # ################ G01/2/3* - Interpolation mode change #########
  710. # #### Can occur along with coordinates and operation code but ##
  711. # #### sometimes by itself (handled here). #####################
  712. # #### Example: G01* #####################
  713. # ################################################################
  714. match = self.interp_re.search(gline)
  715. if match:
  716. current_interpolation_mode = int(match.group(1))
  717. continue
  718. # ################################################################
  719. # ######### G01 - Linear interpolation plus flashes #############
  720. # ######### Operation code (D0x) missing is deprecated #########
  721. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  722. # ################################################################
  723. match = self.lin_re.search(gline)
  724. if match:
  725. # Dxx alone?
  726. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  727. # try:
  728. # current_operation_code = int(match.group(4))
  729. # except Exception:
  730. # pass # A line with just * will match too.
  731. # continue
  732. # NOTE: Letting it continue allows it to react to the
  733. # operation code.
  734. # Parse coordinates
  735. if match.group(2) is not None:
  736. linear_x = parse_gerber_number(match.group(2),
  737. self.int_digits, self.frac_digits, self.gerber_zeros)
  738. current_x = linear_x
  739. else:
  740. linear_x = current_x
  741. if match.group(3) is not None:
  742. linear_y = parse_gerber_number(match.group(3),
  743. self.int_digits, self.frac_digits, self.gerber_zeros)
  744. current_y = linear_y
  745. else:
  746. linear_y = current_y
  747. # Parse operation code
  748. if match.group(4) is not None:
  749. current_operation_code = int(match.group(4))
  750. # Pen down: add segment
  751. if current_operation_code == 1:
  752. # if linear_x or linear_y are None, ignore those
  753. if current_x is not None and current_y is not None:
  754. # only add the point if it's a new one otherwise skip it (harder to process)
  755. if path[-1] != [current_x, current_y]:
  756. path.append([current_x, current_y])
  757. if making_region is False:
  758. # if the aperture is rectangle then add a rectangular shape having as parameters the
  759. # coordinates of the start and end point and also the width and height
  760. # of the 'R' aperture
  761. try:
  762. if self.apertures[current_aperture]["type"] == 'R':
  763. width = self.apertures[current_aperture]['width']
  764. height = self.apertures[current_aperture]['height']
  765. minx = min(path[0][0], path[1][0]) - width / 2
  766. maxx = max(path[0][0], path[1][0]) + width / 2
  767. miny = min(path[0][1], path[1][1]) - height / 2
  768. maxy = max(path[0][1], path[1][1]) + height / 2
  769. log.debug("Coords: %s - %s - %s - %s" % (minx, miny, maxx, maxy))
  770. geo_dict = dict()
  771. geo_f = Point([current_x, current_y])
  772. follow_buffer.append(geo_f)
  773. geo_dict['follow'] = geo_f
  774. geo_s = shply_box(minx, miny, maxx, maxy)
  775. if self.app.defaults['gerber_simplification']:
  776. poly_buffer.append(geo_s.simplify(s_tol))
  777. else:
  778. poly_buffer.append(geo_s)
  779. if self.is_lpc is True:
  780. geo_dict['clear'] = geo_s
  781. else:
  782. geo_dict['solid'] = geo_s
  783. if current_aperture not in self.apertures:
  784. self.apertures[current_aperture] = dict()
  785. if 'geometry' not in self.apertures[current_aperture]:
  786. self.apertures[current_aperture]['geometry'] = []
  787. self.apertures[current_aperture]['geometry'].append(deepcopy(geo_dict))
  788. except Exception as e:
  789. pass
  790. last_path_aperture = current_aperture
  791. # we do this for the case that a region is done without having defined any aperture
  792. if last_path_aperture is None:
  793. if '0' not in self.apertures:
  794. self.apertures['0'] = {}
  795. self.apertures['0']['type'] = 'REG'
  796. self.apertures['0']['size'] = 0.0
  797. self.apertures['0']['geometry'] = []
  798. last_path_aperture = '0'
  799. else:
  800. self.app.inform.emit('[WARNING] %s: %s' %
  801. (_("Coordinates missing, line ignored"), str(gline)))
  802. self.app.inform.emit('[WARNING_NOTCL] %s' %
  803. _("GERBER file might be CORRUPT. Check the file !!!"))
  804. elif current_operation_code == 2:
  805. if len(path) > 1:
  806. geo_s = None
  807. geo_dict = dict()
  808. # --- BUFFERED ---
  809. # this treats the case when we are storing geometry as paths only
  810. if making_region:
  811. # we do this for the case that a region is done without having defined any aperture
  812. if last_path_aperture is None:
  813. if '0' not in self.apertures:
  814. self.apertures['0'] = {}
  815. self.apertures['0']['type'] = 'REG'
  816. self.apertures['0']['size'] = 0.0
  817. self.apertures['0']['geometry'] = []
  818. last_path_aperture = '0'
  819. geo_f = Polygon()
  820. else:
  821. geo_f = LineString(path)
  822. try:
  823. if self.apertures[last_path_aperture]["type"] != 'R':
  824. if not geo_f.is_empty:
  825. follow_buffer.append(geo_f)
  826. geo_dict['follow'] = geo_f
  827. except Exception as e:
  828. log.debug("camlib.Gerber.parse_lines() --> %s" % str(e))
  829. if not geo_f.is_empty:
  830. follow_buffer.append(geo_f)
  831. geo_dict['follow'] = geo_f
  832. # this treats the case when we are storing geometry as solids
  833. if making_region:
  834. # we do this for the case that a region is done without having defined any aperture
  835. if last_path_aperture is None:
  836. if '0' not in self.apertures:
  837. self.apertures['0'] = {}
  838. self.apertures['0']['type'] = 'REG'
  839. self.apertures['0']['size'] = 0.0
  840. self.apertures['0']['geometry'] = []
  841. last_path_aperture = '0'
  842. try:
  843. geo_s = Polygon(path)
  844. except ValueError:
  845. log.warning("Problem %s %s" % (gline, line_num))
  846. self.app.inform.emit('[ERROR] %s: %s' %
  847. (_("Region does not have enough points. "
  848. "File will be processed but there are parser errors. "
  849. "Line number"), str(line_num)))
  850. else:
  851. if last_path_aperture is None:
  852. log.warning("No aperture defined for curent path. (%d)" % line_num)
  853. width = self.apertures[last_path_aperture]["size"] # TODO: WARNING this should fail!
  854. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  855. try:
  856. if self.apertures[last_path_aperture]["type"] != 'R':
  857. if not geo_s.is_empty:
  858. if self.app.defaults['gerber_simplification']:
  859. poly_buffer.append(geo_s.simplify(s_tol))
  860. else:
  861. poly_buffer.append(geo_s)
  862. if self.is_lpc is True:
  863. geo_dict['clear'] = geo_s
  864. else:
  865. geo_dict['solid'] = geo_s
  866. except Exception as e:
  867. log.debug("camlib.Gerber.parse_lines() --> %s" % str(e))
  868. if self.app.defaults['gerber_simplification']:
  869. poly_buffer.append(geo_s.simplify(s_tol))
  870. else:
  871. poly_buffer.append(geo_s)
  872. if self.is_lpc is True:
  873. geo_dict['clear'] = geo_s
  874. else:
  875. geo_dict['solid'] = geo_s
  876. if last_path_aperture not in self.apertures:
  877. self.apertures[last_path_aperture] = dict()
  878. if 'geometry' not in self.apertures[last_path_aperture]:
  879. self.apertures[last_path_aperture]['geometry'] = []
  880. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  881. # if linear_x or linear_y are None, ignore those
  882. if linear_x is not None and linear_y is not None:
  883. path = [[linear_x, linear_y]] # Start new path
  884. else:
  885. self.app.inform.emit('[WARNING] %s: %s' %
  886. (_("Coordinates missing, line ignored"), str(gline)))
  887. self.app.inform.emit('[WARNING_NOTCL] %s' %
  888. _("GERBER file might be CORRUPT. Check the file !!!"))
  889. # Flash
  890. # Not allowed in region mode.
  891. elif current_operation_code == 3:
  892. # Create path draw so far.
  893. if len(path) > 1:
  894. # --- Buffered ----
  895. geo_dict = dict()
  896. # this treats the case when we are storing geometry as paths
  897. geo_f = LineString(path)
  898. if not geo_f.is_empty:
  899. try:
  900. if self.apertures[last_path_aperture]["type"] != 'R':
  901. follow_buffer.append(geo_f)
  902. geo_dict['follow'] = geo_f
  903. except Exception as e:
  904. log.debug("camlib.Gerber.parse_lines() --> G01 match D03 --> %s" % str(e))
  905. follow_buffer.append(geo_f)
  906. geo_dict['follow'] = geo_f
  907. # this treats the case when we are storing geometry as solids
  908. width = self.apertures[last_path_aperture]["size"]
  909. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  910. if not geo_s.is_empty:
  911. try:
  912. if self.apertures[last_path_aperture]["type"] != 'R':
  913. if self.app.defaults['gerber_simplification']:
  914. poly_buffer.append(geo_s.simplify(s_tol))
  915. else:
  916. poly_buffer.append(geo_s)
  917. if self.is_lpc is True:
  918. geo_dict['clear'] = geo_s
  919. else:
  920. geo_dict['solid'] = geo_s
  921. except Exception:
  922. if self.app.defaults['gerber_simplification']:
  923. poly_buffer.append(geo_s.simplify(s_tol))
  924. else:
  925. poly_buffer.append(geo_s)
  926. if self.is_lpc is True:
  927. geo_dict['clear'] = geo_s
  928. else:
  929. geo_dict['solid'] = geo_s
  930. if last_path_aperture not in self.apertures:
  931. self.apertures[last_path_aperture] = dict()
  932. if 'geometry' not in self.apertures[last_path_aperture]:
  933. self.apertures[last_path_aperture]['geometry'] = []
  934. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  935. # Reset path starting point
  936. path = [[linear_x, linear_y]]
  937. # --- BUFFERED ---
  938. # Draw the flash
  939. # this treats the case when we are storing geometry as paths
  940. geo_dict = dict()
  941. geo_flash = Point([linear_x, linear_y])
  942. follow_buffer.append(geo_flash)
  943. geo_dict['follow'] = geo_flash
  944. # this treats the case when we are storing geometry as solids
  945. flash = self.create_flash_geometry(
  946. Point([linear_x, linear_y]),
  947. self.apertures[current_aperture],
  948. self.steps_per_circle
  949. )
  950. if not flash.is_empty:
  951. if self.app.defaults['gerber_simplification']:
  952. poly_buffer.append(flash.simplify(s_tol))
  953. else:
  954. poly_buffer.append(flash)
  955. if self.is_lpc is True:
  956. geo_dict['clear'] = flash
  957. else:
  958. geo_dict['solid'] = flash
  959. if current_aperture not in self.apertures:
  960. self.apertures[current_aperture] = dict()
  961. if 'geometry' not in self.apertures[current_aperture]:
  962. self.apertures[current_aperture]['geometry'] = []
  963. self.apertures[current_aperture]['geometry'].append(deepcopy(geo_dict))
  964. # maybe those lines are not exactly needed but it is easier to read the program as those coordinates
  965. # are used in case that circular interpolation is encountered within the Gerber file
  966. current_x = linear_x
  967. current_y = linear_y
  968. # log.debug("Line_number=%3s X=%s Y=%s (%s)" % (line_num, linear_x, linear_y, gline))
  969. continue
  970. # ################################################################
  971. # ######### G74/75* - Single or multiple quadrant arcs ##########
  972. # ################################################################
  973. match = self.quad_re.search(gline)
  974. if match:
  975. if match.group(1) == '4':
  976. quadrant_mode = 'SINGLE'
  977. else:
  978. quadrant_mode = 'MULTI'
  979. continue
  980. # ################################################################
  981. # ######### G02/3 - Circular interpolation #####################
  982. # ######### 2-clockwise, 3-counterclockwise #####################
  983. # ######### Ex. format: G03 X0 Y50 I-50 J0 where the #########
  984. # ######### X, Y coords are the coords of the End Point #########
  985. # ################################################################
  986. match = self.circ_re.search(gline)
  987. if match:
  988. arcdir = [None, None, "cw", "ccw"]
  989. mode, circular_x, circular_y, i, j, d = match.groups()
  990. try:
  991. circular_x = parse_gerber_number(circular_x,
  992. self.int_digits, self.frac_digits, self.gerber_zeros)
  993. except Exception as e:
  994. circular_x = current_x
  995. try:
  996. circular_y = parse_gerber_number(circular_y,
  997. self.int_digits, self.frac_digits, self.gerber_zeros)
  998. except Exception as e:
  999. circular_y = current_y
  1000. # According to Gerber specification i and j are not modal, which means that when i or j are missing,
  1001. # they are to be interpreted as being zero
  1002. try:
  1003. i = parse_gerber_number(i, self.int_digits, self.frac_digits, self.gerber_zeros)
  1004. except Exception as e:
  1005. i = 0
  1006. try:
  1007. j = parse_gerber_number(j, self.int_digits, self.frac_digits, self.gerber_zeros)
  1008. except Exception as e:
  1009. j = 0
  1010. if quadrant_mode is None:
  1011. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  1012. log.error(gline)
  1013. continue
  1014. if mode is None and current_interpolation_mode not in [2, 3]:
  1015. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  1016. log.error(gline)
  1017. continue
  1018. elif mode is not None:
  1019. current_interpolation_mode = int(mode)
  1020. # Set operation code if provided
  1021. if d is not None:
  1022. current_operation_code = int(d)
  1023. # Nothing created! Pen Up.
  1024. if current_operation_code == 2:
  1025. log.warning("Arc with D2. (%d)" % line_num)
  1026. if len(path) > 1:
  1027. geo_dict = dict()
  1028. if last_path_aperture is None:
  1029. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1030. # --- BUFFERED ---
  1031. width = self.apertures[last_path_aperture]["size"]
  1032. # this treats the case when we are storing geometry as paths
  1033. geo_f = LineString(path)
  1034. if not geo_f.is_empty:
  1035. follow_buffer.append(geo_f)
  1036. geo_dict['follow'] = geo_f
  1037. # this treats the case when we are storing geometry as solids
  1038. buffered = LineString(path).buffer(width / 1.999, int(self.steps_per_circle))
  1039. if not buffered.is_empty:
  1040. if self.app.defaults['gerber_simplification']:
  1041. poly_buffer.append(buffered.simplify(s_tol))
  1042. else:
  1043. poly_buffer.append(buffered)
  1044. if self.is_lpc is True:
  1045. geo_dict['clear'] = buffered
  1046. else:
  1047. geo_dict['solid'] = buffered
  1048. if last_path_aperture not in self.apertures:
  1049. self.apertures[last_path_aperture] = dict()
  1050. if 'geometry' not in self.apertures[last_path_aperture]:
  1051. self.apertures[last_path_aperture]['geometry'] = []
  1052. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  1053. current_x = circular_x
  1054. current_y = circular_y
  1055. path = [[current_x, current_y]] # Start new path
  1056. continue
  1057. # Flash should not happen here
  1058. if current_operation_code == 3:
  1059. log.error("Trying to flash within arc. (%d)" % line_num)
  1060. continue
  1061. if quadrant_mode == 'MULTI':
  1062. center = [i + current_x, j + current_y]
  1063. radius = np.sqrt(i ** 2 + j ** 2)
  1064. start = np.arctan2(-j, -i) # Start angle
  1065. # Numerical errors might prevent start == stop therefore
  1066. # we check ahead of time. This should result in a
  1067. # 360 degree arc.
  1068. if current_x == circular_x and current_y == circular_y:
  1069. stop = start
  1070. else:
  1071. stop = np.arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  1072. this_arc = arc(center, radius, start, stop,
  1073. arcdir[current_interpolation_mode],
  1074. self.steps_per_circle)
  1075. # The last point in the computed arc can have
  1076. # numerical errors. The exact final point is the
  1077. # specified (x, y). Replace.
  1078. this_arc[-1] = (circular_x, circular_y)
  1079. # Last point in path is current point
  1080. # current_x = this_arc[-1][0]
  1081. # current_y = this_arc[-1][1]
  1082. current_x, current_y = circular_x, circular_y
  1083. # Append
  1084. path += this_arc
  1085. last_path_aperture = current_aperture
  1086. continue
  1087. if quadrant_mode == 'SINGLE':
  1088. center_candidates = [
  1089. [i + current_x, j + current_y],
  1090. [-i + current_x, j + current_y],
  1091. [i + current_x, -j + current_y],
  1092. [-i + current_x, -j + current_y]
  1093. ]
  1094. valid = False
  1095. log.debug("I: %f J: %f" % (i, j))
  1096. for center in center_candidates:
  1097. radius = np.sqrt(i ** 2 + j ** 2)
  1098. # Make sure radius to start is the same as radius to end.
  1099. radius2 = np.sqrt((center[0] - circular_x) ** 2 + (center[1] - circular_y) ** 2)
  1100. if radius2 < radius * 0.95 or radius2 > radius * 1.05:
  1101. continue # Not a valid center.
  1102. # Correct i and j and continue as with multi-quadrant.
  1103. i = center[0] - current_x
  1104. j = center[1] - current_y
  1105. start = np.arctan2(-j, -i) # Start angle
  1106. stop = np.arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  1107. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  1108. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  1109. (current_x, current_y, center[0], center[1], circular_x, circular_y))
  1110. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  1111. (start * 180 / np.pi, stop * 180 / np.pi, arcdir[current_interpolation_mode],
  1112. angle * 180 / np.pi, np.pi / 2 * 180 / np.pi, angle <= (np.pi + 1e-6) / 2))
  1113. if angle <= (np.pi + 1e-6) / 2:
  1114. log.debug("########## ACCEPTING ARC ############")
  1115. this_arc = arc(center, radius, start, stop,
  1116. arcdir[current_interpolation_mode],
  1117. self.steps_per_circle)
  1118. # Replace with exact values
  1119. this_arc[-1] = (circular_x, circular_y)
  1120. # current_x = this_arc[-1][0]
  1121. # current_y = this_arc[-1][1]
  1122. current_x, current_y = circular_x, circular_y
  1123. path += this_arc
  1124. last_path_aperture = current_aperture
  1125. valid = True
  1126. break
  1127. if valid:
  1128. continue
  1129. else:
  1130. log.warning("Invalid arc in line %d." % line_num)
  1131. # ################################################################
  1132. # ######### EOF - END OF FILE ####################################
  1133. # ################################################################
  1134. match = self.eof_re.search(gline)
  1135. if match:
  1136. continue
  1137. # ################################################################
  1138. # ######### Line did not match any pattern. Warn user. ##########
  1139. # ################################################################
  1140. log.warning("Line ignored (%d): %s" % (line_num, gline))
  1141. if len(path) > 1:
  1142. # In case that G01 (moving) aperture is rectangular, there is no need to still create
  1143. # another geo since we already created a shapely box using the start and end coordinates found in
  1144. # path variable. We do it only for other apertures than 'R' type
  1145. if self.apertures[last_path_aperture]["type"] == 'R':
  1146. pass
  1147. else:
  1148. # EOF, create shapely LineString if something still in path
  1149. # ## --- Buffered ---
  1150. geo_dict = dict()
  1151. # this treats the case when we are storing geometry as paths
  1152. geo_f = LineString(path)
  1153. if not geo_f.is_empty:
  1154. follow_buffer.append(geo_f)
  1155. geo_dict['follow'] = geo_f
  1156. # this treats the case when we are storing geometry as solids
  1157. width = self.apertures[last_path_aperture]["size"]
  1158. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  1159. if not geo_s.is_empty:
  1160. if self.app.defaults['gerber_simplification']:
  1161. poly_buffer.append(geo_s.simplify(s_tol))
  1162. else:
  1163. poly_buffer.append(geo_s)
  1164. if self.is_lpc is True:
  1165. geo_dict['clear'] = geo_s
  1166. else:
  1167. geo_dict['solid'] = geo_s
  1168. if last_path_aperture not in self.apertures:
  1169. self.apertures[last_path_aperture] = dict()
  1170. if 'geometry' not in self.apertures[last_path_aperture]:
  1171. self.apertures[last_path_aperture]['geometry'] = []
  1172. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  1173. # --- Apply buffer ---
  1174. # this treats the case when we are storing geometry as paths
  1175. self.follow_geometry = follow_buffer
  1176. # this treats the case when we are storing geometry as solids
  1177. if len(poly_buffer) == 0 and len(self.solid_geometry) == 0:
  1178. log.error("Object is not Gerber file or empty. Aborting Object creation.")
  1179. return 'fail'
  1180. log.warning("Joining %d polygons." % len(poly_buffer))
  1181. self.app.inform.emit('%s: %d.' % (_("Gerber processing. Joining polygons"), len(poly_buffer)))
  1182. if self.use_buffer_for_union:
  1183. log.debug("Union by buffer...")
  1184. new_poly = MultiPolygon(poly_buffer)
  1185. if self.app.defaults["gerber_buffering"] == 'full':
  1186. new_poly = new_poly.buffer(0.00000001)
  1187. new_poly = new_poly.buffer(-0.00000001)
  1188. log.warning("Union(buffer) done.")
  1189. else:
  1190. log.debug("Union by union()...")
  1191. new_poly = cascaded_union(poly_buffer)
  1192. new_poly = new_poly.buffer(0, int(self.steps_per_circle / 4))
  1193. log.warning("Union done.")
  1194. if current_polarity == 'D':
  1195. self.app.inform.emit('%s' % _("Gerber processing. Applying Gerber polarity."))
  1196. if new_poly.is_valid:
  1197. self.solid_geometry = self.solid_geometry.union(new_poly)
  1198. else:
  1199. # I do this so whenever the parsed geometry of the file is not valid (intersections) it is still
  1200. # loaded. Instead of applying a union I add to a list of polygons.
  1201. final_poly = []
  1202. try:
  1203. for poly in new_poly:
  1204. final_poly.append(poly)
  1205. except TypeError:
  1206. final_poly.append(new_poly)
  1207. try:
  1208. for poly in self.solid_geometry:
  1209. final_poly.append(poly)
  1210. except TypeError:
  1211. final_poly.append(self.solid_geometry)
  1212. self.solid_geometry = final_poly
  1213. # FIX for issue #347 - Sprint Layout generate strange Gerber files when the copper pour is enabled
  1214. # it use a filled bounding box polygon to which add clear polygons (negative) to isolate the copper
  1215. # features
  1216. if self.app.defaults['gerber_extra_buffering']:
  1217. candidate_geo = list()
  1218. try:
  1219. for p in self.solid_geometry:
  1220. candidate_geo.append(p.buffer(0.0000001))
  1221. except TypeError:
  1222. candidate_geo.append(self.solid_geometry.buffer(0.0000001))
  1223. self.solid_geometry = candidate_geo
  1224. # try:
  1225. # self.solid_geometry = self.solid_geometry.union(new_poly)
  1226. # except Exception as e:
  1227. # # in case in the new_poly are some self intersections try to avoid making union with them
  1228. # for poly in new_poly:
  1229. # try:
  1230. # self.solid_geometry = self.solid_geometry.union(poly)
  1231. # except Exception:
  1232. # pass
  1233. else:
  1234. self.solid_geometry = self.solid_geometry.difference(new_poly)
  1235. if self.app.defaults['gerber_clean_apertures']:
  1236. # clean the Gerber file of apertures with no geometry
  1237. for apid, apvalue in list(self.apertures.items()):
  1238. if 'geometry' not in apvalue:
  1239. self.apertures.pop(apid)
  1240. # init this for the following operations
  1241. self.conversion_done = False
  1242. except Exception as err:
  1243. ex_type, ex, tb = sys.exc_info()
  1244. traceback.print_tb(tb)
  1245. # print traceback.format_exc()
  1246. log.error("Gerber PARSING FAILED. Line %d: %s" % (line_num, gline))
  1247. loc = '%s #%d %s: %s\n' % (_("Gerber Line"), line_num, _("Gerber Line Content"), gline) + repr(err)
  1248. self.app.inform.emit('[ERROR] %s\n%s:' %
  1249. (_("Gerber Parser ERROR"), loc))
  1250. @staticmethod
  1251. def create_flash_geometry(location, aperture, steps_per_circle=None):
  1252. # log.debug('Flashing @%s, Aperture: %s' % (location, aperture))
  1253. if type(location) == list:
  1254. location = Point(location)
  1255. if aperture['type'] == 'C': # Circles
  1256. return location.buffer(aperture['size'] / 2, int(steps_per_circle / 4))
  1257. if aperture['type'] == 'R': # Rectangles
  1258. loc = location.coords[0]
  1259. width = aperture['width']
  1260. height = aperture['height']
  1261. minx = loc[0] - width / 2
  1262. maxx = loc[0] + width / 2
  1263. miny = loc[1] - height / 2
  1264. maxy = loc[1] + height / 2
  1265. return shply_box(minx, miny, maxx, maxy)
  1266. if aperture['type'] == 'O': # Obround
  1267. loc = location.coords[0]
  1268. width = aperture['width']
  1269. height = aperture['height']
  1270. if width > height:
  1271. p1 = Point(loc[0] + 0.5 * (width - height), loc[1])
  1272. p2 = Point(loc[0] - 0.5 * (width - height), loc[1])
  1273. c1 = p1.buffer(height * 0.5, int(steps_per_circle / 4))
  1274. c2 = p2.buffer(height * 0.5, int(steps_per_circle / 4))
  1275. else:
  1276. p1 = Point(loc[0], loc[1] + 0.5 * (height - width))
  1277. p2 = Point(loc[0], loc[1] - 0.5 * (height - width))
  1278. c1 = p1.buffer(width * 0.5, int(steps_per_circle / 4))
  1279. c2 = p2.buffer(width * 0.5, int(steps_per_circle / 4))
  1280. return cascaded_union([c1, c2]).convex_hull
  1281. if aperture['type'] == 'P': # Regular polygon
  1282. loc = location.coords[0]
  1283. diam = aperture['diam']
  1284. n_vertices = aperture['nVertices']
  1285. points = []
  1286. for i in range(0, n_vertices):
  1287. x = loc[0] + 0.5 * diam * (np.cos(2 * np.pi * i / n_vertices))
  1288. y = loc[1] + 0.5 * diam * (np.sin(2 * np.pi * i / n_vertices))
  1289. points.append((x, y))
  1290. ply = Polygon(points)
  1291. if 'rotation' in aperture:
  1292. ply = affinity.rotate(ply, aperture['rotation'])
  1293. return ply
  1294. if aperture['type'] == 'AM': # Aperture Macro
  1295. loc = location.coords[0]
  1296. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1297. if flash_geo.is_empty:
  1298. log.warning("Empty geometry for Aperture Macro: %s" % str(aperture['macro'].name))
  1299. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1300. log.warning("Unknown aperture type: %s" % aperture['type'])
  1301. return None
  1302. def create_geometry(self):
  1303. """
  1304. Geometry from a Gerber file is made up entirely of polygons.
  1305. Every stroke (linear or circular) has an aperture which gives
  1306. it thickness. Additionally, aperture strokes have non-zero area,
  1307. and regions naturally do as well.
  1308. :rtype : None
  1309. :return: None
  1310. """
  1311. pass
  1312. # self.buffer_paths()
  1313. #
  1314. # self.fix_regions()
  1315. #
  1316. # self.do_flashes()
  1317. #
  1318. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1319. # [poly['polygon'] for poly in self.regions] +
  1320. # self.flash_geometry)
  1321. def get_bounding_box(self, margin=0.0, rounded=False):
  1322. """
  1323. Creates and returns a rectangular polygon bounding at a distance of
  1324. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1325. can optionally have rounded corners of radius equal to margin.
  1326. :param margin: Distance to enlarge the rectangular bounding
  1327. box in both positive and negative, x and y axes.
  1328. :type margin: float
  1329. :param rounded: Wether or not to have rounded corners.
  1330. :type rounded: bool
  1331. :return: The bounding box.
  1332. :rtype: Shapely.Polygon
  1333. """
  1334. bbox = self.solid_geometry.envelope.buffer(margin)
  1335. if not rounded:
  1336. bbox = bbox.envelope
  1337. return bbox
  1338. def bounds(self):
  1339. """
  1340. Returns coordinates of rectangular bounds
  1341. of Gerber geometry: (xmin, ymin, xmax, ymax).
  1342. """
  1343. # fixed issue of getting bounds only for one level lists of objects
  1344. # now it can get bounds for nested lists of objects
  1345. log.debug("parseGerber.Gerber.bounds()")
  1346. if self.solid_geometry is None:
  1347. log.debug("solid_geometry is None")
  1348. return 0, 0, 0, 0
  1349. def bounds_rec(obj):
  1350. if type(obj) is list and type(obj) is not MultiPolygon:
  1351. minx = np.Inf
  1352. miny = np.Inf
  1353. maxx = -np.Inf
  1354. maxy = -np.Inf
  1355. for k in obj:
  1356. if type(k) is dict:
  1357. for key in k:
  1358. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  1359. minx = min(minx, minx_)
  1360. miny = min(miny, miny_)
  1361. maxx = max(maxx, maxx_)
  1362. maxy = max(maxy, maxy_)
  1363. else:
  1364. if not k.is_empty:
  1365. try:
  1366. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1367. except Exception as e:
  1368. log.debug("camlib.Gerber.bounds() --> %s" % str(e))
  1369. return
  1370. minx = min(minx, minx_)
  1371. miny = min(miny, miny_)
  1372. maxx = max(maxx, maxx_)
  1373. maxy = max(maxy, maxy_)
  1374. return minx, miny, maxx, maxy
  1375. else:
  1376. # it's a Shapely object, return it's bounds
  1377. return obj.bounds
  1378. bounds_coords = bounds_rec(self.solid_geometry)
  1379. return bounds_coords
  1380. def convert_units(self, obj_units):
  1381. """
  1382. Converts the units of the object to ``units`` by scaling all
  1383. the geometry appropriately. This call ``scale()``. Don't call
  1384. it again in descendants.
  1385. :param obj_units: "IN" or "MM"
  1386. :type obj_units: str
  1387. :return: Scaling factor resulting from unit change.
  1388. :rtype: float
  1389. """
  1390. if obj_units.upper() == self.units.upper():
  1391. log.debug("parseGerber.Gerber.convert_units() --> Factor: 1")
  1392. return 1.0
  1393. if obj_units.upper() == "MM":
  1394. factor = 25.4
  1395. log.debug("parseGerber.Gerber.convert_units() --> Factor: 25.4")
  1396. elif obj_units.upper() == "IN":
  1397. factor = 1 / 25.4
  1398. log.debug("parseGerber.Gerber.convert_units() --> Factor: %s" % str(1 / 25.4))
  1399. else:
  1400. log.error("Unsupported units: %s" % str(obj_units))
  1401. log.debug("parseGerber.Gerber.convert_units() --> Factor: 1")
  1402. return 1.0
  1403. self.units = obj_units
  1404. self.file_units_factor = factor
  1405. self.scale(factor, factor)
  1406. return factor
  1407. def import_svg(self, filename, object_type='gerber', flip=True, units='MM'):
  1408. """
  1409. Imports shapes from an SVG file into the object's geometry.
  1410. :param filename: Path to the SVG file.
  1411. :type filename: str
  1412. :param object_type: parameter passed further along
  1413. :param flip: Flip the vertically.
  1414. :type flip: bool
  1415. :param units: FlatCAM units
  1416. :return: None
  1417. """
  1418. log.debug("flatcamParsers.ParseGerber.Gerber.import_svg()")
  1419. # Parse into list of shapely objects
  1420. svg_tree = ET.parse(filename)
  1421. svg_root = svg_tree.getroot()
  1422. # Change origin to bottom left
  1423. # h = float(svg_root.get('height'))
  1424. # w = float(svg_root.get('width'))
  1425. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  1426. geos = getsvggeo(svg_root, 'gerber')
  1427. if flip:
  1428. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  1429. # Add to object
  1430. if self.solid_geometry is None:
  1431. self.solid_geometry = list()
  1432. # if type(self.solid_geometry) == list:
  1433. # if type(geos) == list:
  1434. # self.solid_geometry += geos
  1435. # else:
  1436. # self.solid_geometry.append(geos)
  1437. # else: # It's shapely geometry
  1438. # self.solid_geometry = [self.solid_geometry, geos]
  1439. if type(geos) == list:
  1440. # HACK for importing QRCODE exported by FlatCAM
  1441. if len(geos) == 1:
  1442. geo_qrcode = list()
  1443. geo_qrcode.append(Polygon(geos[0].exterior))
  1444. for i_el in geos[0].interiors:
  1445. geo_qrcode.append(Polygon(i_el).buffer(0))
  1446. for poly in geo_qrcode:
  1447. geos.append(poly)
  1448. if type(self.solid_geometry) == list:
  1449. self.solid_geometry += geos
  1450. else:
  1451. geos.append(self.solid_geometry)
  1452. self.solid_geometry = geos
  1453. else:
  1454. if type(self.solid_geometry) == list:
  1455. self.solid_geometry.append(geos)
  1456. else:
  1457. self.solid_geometry = [self.solid_geometry, geos]
  1458. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  1459. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  1460. try:
  1461. __ = iter(self.solid_geometry)
  1462. except TypeError:
  1463. self.solid_geometry = [self.solid_geometry]
  1464. if '0' not in self.apertures:
  1465. self.apertures['0'] = dict()
  1466. self.apertures['0']['type'] = 'REG'
  1467. self.apertures['0']['size'] = 0.0
  1468. self.apertures['0']['geometry'] = list()
  1469. for pol in self.solid_geometry:
  1470. new_el = dict()
  1471. new_el['solid'] = pol
  1472. new_el['follow'] = pol.exterior
  1473. self.apertures['0']['geometry'].append(deepcopy(new_el))
  1474. def scale(self, xfactor, yfactor=None, point=None):
  1475. """
  1476. Scales the objects' geometry on the XY plane by a given factor.
  1477. These are:
  1478. * ``buffered_paths``
  1479. * ``flash_geometry``
  1480. * ``solid_geometry``
  1481. * ``regions``
  1482. NOTE:
  1483. Does not modify the data used to create these elements. If these
  1484. are recreated, the scaling will be lost. This behavior was modified
  1485. because of the complexity reached in this class.
  1486. :param xfactor: Number by which to scale on X axis.
  1487. :type xfactor: float
  1488. :param yfactor: Number by which to scale on Y axis.
  1489. :type yfactor: float
  1490. :param point: reference point for scaling operation
  1491. :rtype : None
  1492. """
  1493. log.debug("parseGerber.Gerber.scale()")
  1494. try:
  1495. xfactor = float(xfactor)
  1496. except Exception:
  1497. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1498. _("Scale factor has to be a number: integer or float."))
  1499. return
  1500. if yfactor is None:
  1501. yfactor = xfactor
  1502. else:
  1503. try:
  1504. yfactor = float(yfactor)
  1505. except Exception:
  1506. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1507. _("Scale factor has to be a number: integer or float."))
  1508. return
  1509. if xfactor == 0 and yfactor == 0:
  1510. return
  1511. if point is None:
  1512. px = 0
  1513. py = 0
  1514. else:
  1515. px, py = point
  1516. # variables to display the percentage of work done
  1517. self.geo_len = 0
  1518. try:
  1519. self.geo_len = len(self.solid_geometry)
  1520. except TypeError:
  1521. self.geo_len = 1
  1522. self.old_disp_number = 0
  1523. self.el_count = 0
  1524. def scale_geom(obj):
  1525. if type(obj) is list:
  1526. new_obj = []
  1527. for g in obj:
  1528. new_obj.append(scale_geom(g))
  1529. return new_obj
  1530. else:
  1531. try:
  1532. self.el_count += 1
  1533. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 99]))
  1534. if self.old_disp_number < disp_number <= 100:
  1535. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1536. self.old_disp_number = disp_number
  1537. return affinity.scale(obj, xfactor, yfactor, origin=(px, py))
  1538. except AttributeError:
  1539. return obj
  1540. self.solid_geometry = scale_geom(self.solid_geometry)
  1541. self.follow_geometry = scale_geom(self.follow_geometry)
  1542. # we need to scale the geometry stored in the Gerber apertures, too
  1543. try:
  1544. for apid in self.apertures:
  1545. new_geometry = list()
  1546. if 'geometry' in self.apertures[apid]:
  1547. for geo_el in self.apertures[apid]['geometry']:
  1548. new_geo_el = dict()
  1549. if 'solid' in geo_el:
  1550. new_geo_el['solid'] = scale_geom(geo_el['solid'])
  1551. if 'follow' in geo_el:
  1552. new_geo_el['follow'] = scale_geom(geo_el['follow'])
  1553. if 'clear' in geo_el:
  1554. new_geo_el['clear'] = scale_geom(geo_el['clear'])
  1555. new_geometry.append(new_geo_el)
  1556. self.apertures[apid]['geometry'] = deepcopy(new_geometry)
  1557. try:
  1558. if str(self.apertures[apid]['type']) == 'R' or str(self.apertures[apid]['type']) == 'O':
  1559. self.apertures[apid]['width'] *= xfactor
  1560. self.apertures[apid]['height'] *= xfactor
  1561. elif str(self.apertures[apid]['type']) == 'P':
  1562. self.apertures[apid]['diam'] *= xfactor
  1563. self.apertures[apid]['nVertices'] *= xfactor
  1564. except KeyError:
  1565. pass
  1566. try:
  1567. if self.apertures[apid]['size'] is not None:
  1568. self.apertures[apid]['size'] = float(self.apertures[apid]['size'] * xfactor)
  1569. except KeyError:
  1570. pass
  1571. except Exception as e:
  1572. log.debug('camlib.Gerber.scale() Exception --> %s' % str(e))
  1573. return 'fail'
  1574. self.app.inform.emit('[success] %s' % _("Gerber Scale done."))
  1575. self.app.proc_container.new_text = ''
  1576. # ## solid_geometry ???
  1577. # It's a cascaded union of objects.
  1578. # self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  1579. # factor, origin=(0, 0))
  1580. # # Now buffered_paths, flash_geometry and solid_geometry
  1581. # self.create_geometry()
  1582. def offset(self, vect):
  1583. """
  1584. Offsets the objects' geometry on the XY plane by a given vector.
  1585. These are:
  1586. * ``buffered_paths``
  1587. * ``flash_geometry``
  1588. * ``solid_geometry``
  1589. * ``regions``
  1590. NOTE:
  1591. Does not modify the data used to create these elements. If these
  1592. are recreated, the scaling will be lost. This behavior was modified
  1593. because of the complexity reached in this class.
  1594. :param vect: (x, y) offset vector.
  1595. :type vect: tuple
  1596. :return: None
  1597. """
  1598. log.debug("parseGerber.Gerber.offset()")
  1599. try:
  1600. dx, dy = vect
  1601. except TypeError:
  1602. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1603. _("An (x,y) pair of values are needed. "
  1604. "Probable you entered only one value in the Offset field."))
  1605. return
  1606. if dx == 0 and dy == 0:
  1607. return
  1608. # variables to display the percentage of work done
  1609. self.geo_len = 0
  1610. try:
  1611. for __ in self.solid_geometry:
  1612. self.geo_len += 1
  1613. except TypeError:
  1614. self.geo_len = 1
  1615. self.old_disp_number = 0
  1616. self.el_count = 0
  1617. def offset_geom(obj):
  1618. if type(obj) is list:
  1619. new_obj = []
  1620. for g in obj:
  1621. new_obj.append(offset_geom(g))
  1622. return new_obj
  1623. else:
  1624. try:
  1625. self.el_count += 1
  1626. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 99]))
  1627. if self.old_disp_number < disp_number <= 100:
  1628. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1629. self.old_disp_number = disp_number
  1630. return affinity.translate(obj, xoff=dx, yoff=dy)
  1631. except AttributeError:
  1632. return obj
  1633. # ## Solid geometry
  1634. self.solid_geometry = offset_geom(self.solid_geometry)
  1635. self.follow_geometry = offset_geom(self.follow_geometry)
  1636. # we need to offset the geometry stored in the Gerber apertures, too
  1637. try:
  1638. for apid in self.apertures:
  1639. if 'geometry' in self.apertures[apid]:
  1640. for geo_el in self.apertures[apid]['geometry']:
  1641. if 'solid' in geo_el:
  1642. geo_el['solid'] = offset_geom(geo_el['solid'])
  1643. if 'follow' in geo_el:
  1644. geo_el['follow'] = offset_geom(geo_el['follow'])
  1645. if 'clear' in geo_el:
  1646. geo_el['clear'] = offset_geom(geo_el['clear'])
  1647. except Exception as e:
  1648. log.debug('camlib.Gerber.offset() Exception --> %s' % str(e))
  1649. return 'fail'
  1650. self.app.inform.emit('[success] %s' %
  1651. _("Gerber Offset done."))
  1652. self.app.proc_container.new_text = ''
  1653. def mirror(self, axis, point):
  1654. """
  1655. Mirrors the object around a specified axis passing through
  1656. the given point. What is affected:
  1657. * ``buffered_paths``
  1658. * ``flash_geometry``
  1659. * ``solid_geometry``
  1660. * ``regions``
  1661. NOTE:
  1662. Does not modify the data used to create these elements. If these
  1663. are recreated, the scaling will be lost. This behavior was modified
  1664. because of the complexity reached in this class.
  1665. :param axis: "X" or "Y" indicates around which axis to mirror.
  1666. :type axis: str
  1667. :param point: [x, y] point belonging to the mirror axis.
  1668. :type point: list
  1669. :return: None
  1670. """
  1671. log.debug("parseGerber.Gerber.mirror()")
  1672. px, py = point
  1673. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1674. # variables to display the percentage of work done
  1675. self.geo_len = 0
  1676. try:
  1677. for __ in self.solid_geometry:
  1678. self.geo_len += 1
  1679. except TypeError:
  1680. self.geo_len = 1
  1681. self.old_disp_number = 0
  1682. self.el_count = 0
  1683. def mirror_geom(obj):
  1684. if type(obj) is list:
  1685. new_obj = []
  1686. for g in obj:
  1687. new_obj.append(mirror_geom(g))
  1688. return new_obj
  1689. else:
  1690. try:
  1691. self.el_count += 1
  1692. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 99]))
  1693. if self.old_disp_number < disp_number <= 100:
  1694. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1695. self.old_disp_number = disp_number
  1696. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1697. except AttributeError:
  1698. return obj
  1699. self.solid_geometry = mirror_geom(self.solid_geometry)
  1700. self.follow_geometry = mirror_geom(self.follow_geometry)
  1701. # we need to mirror the geometry stored in the Gerber apertures, too
  1702. try:
  1703. for apid in self.apertures:
  1704. if 'geometry' in self.apertures[apid]:
  1705. for geo_el in self.apertures[apid]['geometry']:
  1706. if 'solid' in geo_el:
  1707. geo_el['solid'] = mirror_geom(geo_el['solid'])
  1708. if 'follow' in geo_el:
  1709. geo_el['follow'] = mirror_geom(geo_el['follow'])
  1710. if 'clear' in geo_el:
  1711. geo_el['clear'] = mirror_geom(geo_el['clear'])
  1712. except Exception as e:
  1713. log.debug('camlib.Gerber.mirror() Exception --> %s' % str(e))
  1714. return 'fail'
  1715. self.app.inform.emit('[success] %s' %
  1716. _("Gerber Mirror done."))
  1717. self.app.proc_container.new_text = ''
  1718. def skew(self, angle_x, angle_y, point):
  1719. """
  1720. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1721. Parameters
  1722. ----------
  1723. angle_x, angle_y : float, float
  1724. The shear angle(s) for the x and y axes respectively. These can be
  1725. specified in either degrees (default) or radians by setting
  1726. use_radians=True.
  1727. See shapely manual for more information:
  1728. http://toblerity.org/shapely/manual.html#affine-transformations
  1729. :param angle_x: the angle on X axis for skewing
  1730. :param angle_y: the angle on Y axis for skewing
  1731. :param point: reference point for skewing operation
  1732. :return None
  1733. """
  1734. log.debug("parseGerber.Gerber.skew()")
  1735. px, py = point
  1736. if angle_x == 0 and angle_y == 0:
  1737. return
  1738. # variables to display the percentage of work done
  1739. self.geo_len = 0
  1740. try:
  1741. self.geo_len = len(self.solid_geometry)
  1742. except TypeError:
  1743. self.geo_len = 1
  1744. self.old_disp_number = 0
  1745. self.el_count = 0
  1746. def skew_geom(obj):
  1747. if type(obj) is list:
  1748. new_obj = []
  1749. for g in obj:
  1750. new_obj.append(skew_geom(g))
  1751. return new_obj
  1752. else:
  1753. try:
  1754. self.el_count += 1
  1755. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1756. if self.old_disp_number < disp_number <= 100:
  1757. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1758. self.old_disp_number = disp_number
  1759. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1760. except AttributeError:
  1761. return obj
  1762. self.solid_geometry = skew_geom(self.solid_geometry)
  1763. self.follow_geometry = skew_geom(self.follow_geometry)
  1764. # we need to skew the geometry stored in the Gerber apertures, too
  1765. try:
  1766. for apid in self.apertures:
  1767. if 'geometry' in self.apertures[apid]:
  1768. for geo_el in self.apertures[apid]['geometry']:
  1769. if 'solid' in geo_el:
  1770. geo_el['solid'] = skew_geom(geo_el['solid'])
  1771. if 'follow' in geo_el:
  1772. geo_el['follow'] = skew_geom(geo_el['follow'])
  1773. if 'clear' in geo_el:
  1774. geo_el['clear'] = skew_geom(geo_el['clear'])
  1775. except Exception as e:
  1776. log.debug('camlib.Gerber.skew() Exception --> %s' % str(e))
  1777. return 'fail'
  1778. self.app.inform.emit('[success] %s' % _("Gerber Skew done."))
  1779. self.app.proc_container.new_text = ''
  1780. def rotate(self, angle, point):
  1781. """
  1782. Rotate an object by a given angle around given coords (point)
  1783. :param angle:
  1784. :param point:
  1785. :return:
  1786. """
  1787. log.debug("parseGerber.Gerber.rotate()")
  1788. px, py = point
  1789. if angle == 0:
  1790. return
  1791. # variables to display the percentage of work done
  1792. self.geo_len = 0
  1793. try:
  1794. for __ in self.solid_geometry:
  1795. self.geo_len += 1
  1796. except TypeError:
  1797. self.geo_len = 1
  1798. self.old_disp_number = 0
  1799. self.el_count = 0
  1800. def rotate_geom(obj):
  1801. if type(obj) is list:
  1802. new_obj = []
  1803. for g in obj:
  1804. new_obj.append(rotate_geom(g))
  1805. return new_obj
  1806. else:
  1807. try:
  1808. self.el_count += 1
  1809. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1810. if self.old_disp_number < disp_number <= 100:
  1811. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1812. self.old_disp_number = disp_number
  1813. return affinity.rotate(obj, angle, origin=(px, py))
  1814. except AttributeError:
  1815. return obj
  1816. self.solid_geometry = rotate_geom(self.solid_geometry)
  1817. self.follow_geometry = rotate_geom(self.follow_geometry)
  1818. # we need to rotate the geometry stored in the Gerber apertures, too
  1819. try:
  1820. for apid in self.apertures:
  1821. if 'geometry' in self.apertures[apid]:
  1822. for geo_el in self.apertures[apid]['geometry']:
  1823. if 'solid' in geo_el:
  1824. geo_el['solid'] = rotate_geom(geo_el['solid'])
  1825. if 'follow' in geo_el:
  1826. geo_el['follow'] = rotate_geom(geo_el['follow'])
  1827. if 'clear' in geo_el:
  1828. geo_el['clear'] = rotate_geom(geo_el['clear'])
  1829. except Exception as e:
  1830. log.debug('camlib.Gerber.rotate() Exception --> %s' % str(e))
  1831. return 'fail'
  1832. self.app.inform.emit('[success] %s' %
  1833. _("Gerber Rotate done."))
  1834. self.app.proc_container.new_text = ''
  1835. def buffer(self, distance, join):
  1836. """
  1837. :param distance:
  1838. :return:
  1839. """
  1840. log.debug("parseGerber.Gerber.buffer()")
  1841. if distance == 0:
  1842. return
  1843. # variables to display the percentage of work done
  1844. self.geo_len = 0
  1845. try:
  1846. for __ in self.solid_geometry:
  1847. self.geo_len += 1
  1848. except TypeError:
  1849. self.geo_len = 1
  1850. self.old_disp_number = 0
  1851. self.el_count = 0
  1852. def buffer_geom(obj):
  1853. if type(obj) is list:
  1854. new_obj = []
  1855. for g in obj:
  1856. new_obj.append(buffer_geom(g))
  1857. return new_obj
  1858. else:
  1859. try:
  1860. self.el_count += 1
  1861. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1862. if self.old_disp_number < disp_number <= 100:
  1863. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1864. self.old_disp_number = disp_number
  1865. return obj.buffer(distance, resolution=self.steps_per_circle, join_style=join)
  1866. except AttributeError:
  1867. return obj
  1868. self.solid_geometry = buffer_geom(self.solid_geometry)
  1869. # we need to buffer the geometry stored in the Gerber apertures, too
  1870. try:
  1871. for apid in self.apertures:
  1872. new_geometry = list()
  1873. if 'geometry' in self.apertures[apid]:
  1874. for geo_el in self.apertures[apid]['geometry']:
  1875. new_geo_el = dict()
  1876. if 'solid' in geo_el:
  1877. new_geo_el['solid'] = buffer_geom(geo_el['solid'])
  1878. if 'follow' in geo_el:
  1879. new_geo_el['follow'] = buffer_geom(geo_el['follow'])
  1880. if 'clear' in geo_el:
  1881. new_geo_el['clear'] = buffer_geom(geo_el['clear'])
  1882. new_geometry.append(new_geo_el)
  1883. self.apertures[apid]['geometry'] = deepcopy(new_geometry)
  1884. try:
  1885. if str(self.apertures[apid]['type']) == 'R' or str(self.apertures[apid]['type']) == 'O':
  1886. self.apertures[apid]['width'] += (distance * 2)
  1887. self.apertures[apid]['height'] += (distance * 2)
  1888. elif str(self.apertures[apid]['type']) == 'P':
  1889. self.apertures[apid]['diam'] += (distance * 2)
  1890. self.apertures[apid]['nVertices'] += (distance * 2)
  1891. except KeyError:
  1892. pass
  1893. try:
  1894. if self.apertures[apid]['size'] is not None:
  1895. self.apertures[apid]['size'] = float(self.apertures[apid]['size'] + (distance * 2))
  1896. except KeyError:
  1897. pass
  1898. except Exception as e:
  1899. log.debug('camlib.Gerber.buffer() Exception --> %s' % str(e))
  1900. return 'fail'
  1901. self.app.inform.emit('[success] %s' % _("Gerber Buffer done."))
  1902. self.app.proc_container.new_text = ''
  1903. def parse_gerber_number(strnumber, int_digits, frac_digits, zeros):
  1904. """
  1905. Parse a single number of Gerber coordinates.
  1906. :param strnumber: String containing a number in decimal digits
  1907. from a coordinate data block, possibly with a leading sign.
  1908. :type strnumber: str
  1909. :param int_digits: Number of digits used for the integer
  1910. part of the number
  1911. :type frac_digits: int
  1912. :param frac_digits: Number of digits used for the fractional
  1913. part of the number
  1914. :type frac_digits: int
  1915. :param zeros: If 'L', leading zeros are removed and trailing zeros are kept. Same situation for 'D' when
  1916. no zero suppression is done. If 'T', is in reverse.
  1917. :type zeros: str
  1918. :return: The number in floating point.
  1919. :rtype: float
  1920. """
  1921. ret_val = None
  1922. if zeros == 'L' or zeros == 'D':
  1923. ret_val = int(strnumber) * (10 ** (-frac_digits))
  1924. if zeros == 'T':
  1925. int_val = int(strnumber)
  1926. ret_val = (int_val * (10 ** ((int_digits + frac_digits) - len(strnumber)))) * (10 ** (-frac_digits))
  1927. return ret_val