ParseExcellon.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. from camlib import Geometry
  9. import FlatCAMApp
  10. import shapely.affinity as affinity
  11. from shapely.geometry import Point, LineString
  12. import numpy as np
  13. import re
  14. import logging
  15. import traceback
  16. from copy import deepcopy
  17. import FlatCAMTranslation as fcTranslate
  18. import gettext
  19. import builtins
  20. if '_' not in builtins.__dict__:
  21. _ = gettext.gettext
  22. log = logging.getLogger('base')
  23. class Excellon(Geometry):
  24. """
  25. Here it is done all the Excellon parsing.
  26. *ATTRIBUTES*
  27. * ``tools`` (dict): The key is the tool name and the value is
  28. a dictionary specifying the tool:
  29. ================ ====================================
  30. Key Value
  31. ================ ====================================
  32. C Diameter of the tool
  33. solid_geometry Geometry list for each tool
  34. Others Not supported (Ignored).
  35. ================ ====================================
  36. * ``drills`` (list): Each is a dictionary:
  37. ================ ====================================
  38. Key Value
  39. ================ ====================================
  40. point (Shapely.Point) Where to drill
  41. tool (str) A key in ``tools``
  42. ================ ====================================
  43. * ``slots`` (list): Each is a dictionary
  44. ================ ====================================
  45. Key Value
  46. ================ ====================================
  47. start (Shapely.Point) Start point of the slot
  48. stop (Shapely.Point) Stop point of the slot
  49. tool (str) A key in ``tools``
  50. ================ ====================================
  51. """
  52. defaults = {
  53. "zeros": "L",
  54. "excellon_format_upper_mm": '3',
  55. "excellon_format_lower_mm": '3',
  56. "excellon_format_upper_in": '2',
  57. "excellon_format_lower_in": '4',
  58. "excellon_units": 'INCH',
  59. "geo_steps_per_circle": '64'
  60. }
  61. def __init__(self, zeros=None, excellon_format_upper_mm=None, excellon_format_lower_mm=None,
  62. excellon_format_upper_in=None, excellon_format_lower_in=None, excellon_units=None,
  63. geo_steps_per_circle=None):
  64. """
  65. The constructor takes no parameters.
  66. :return: Excellon object.
  67. :rtype: Excellon
  68. """
  69. self.decimals = self.app.decimals
  70. if geo_steps_per_circle is None:
  71. geo_steps_per_circle = int(Excellon.defaults['geo_steps_per_circle'])
  72. self.geo_steps_per_circle = int(geo_steps_per_circle)
  73. Geometry.__init__(self, geo_steps_per_circle=int(geo_steps_per_circle))
  74. # dictionary to store tools, see above for description
  75. self.tools = {}
  76. # list to store the drills, see above for description
  77. self.drills = []
  78. # self.slots (list) to store the slots; each is a dictionary
  79. self.slots = []
  80. self.source_file = ''
  81. # it serve to flag if a start routing or a stop routing was encountered
  82. # if a stop is encounter and this flag is still 0 (so there is no stop for a previous start) issue error
  83. self.routing_flag = 1
  84. self.match_routing_start = None
  85. self.match_routing_stop = None
  86. self.num_tools = [] # List for keeping the tools sorted
  87. self.index_per_tool = {} # Dictionary to store the indexed points for each tool
  88. # ## IN|MM -> Units are inherited from Geometry
  89. self.units = self.app.defaults['units']
  90. # Trailing "T" or leading "L" (default)
  91. # self.zeros = "T"
  92. self.zeros = zeros or self.defaults["zeros"]
  93. self.zeros_found = self.zeros
  94. self.units_found = self.units
  95. # this will serve as a default if the Excellon file has no info regarding of tool diameters (this info may be
  96. # in another file like for PCB WIzard ECAD software
  97. self.toolless_diam = 1.0
  98. # signal that the Excellon file has no tool diameter informations and the tools have bogus (random) diameter
  99. self.diameterless = False
  100. # Excellon format
  101. self.excellon_format_upper_in = excellon_format_upper_in or self.defaults["excellon_format_upper_in"]
  102. self.excellon_format_lower_in = excellon_format_lower_in or self.defaults["excellon_format_lower_in"]
  103. self.excellon_format_upper_mm = excellon_format_upper_mm or self.defaults["excellon_format_upper_mm"]
  104. self.excellon_format_lower_mm = excellon_format_lower_mm or self.defaults["excellon_format_lower_mm"]
  105. self.excellon_units = excellon_units or self.defaults["excellon_units"]
  106. # detected Excellon format is stored here:
  107. self.excellon_format = None
  108. # Attributes to be included in serialization
  109. # Always append to it because it carries contents
  110. # from Geometry.
  111. self.ser_attrs += ['tools', 'drills', 'zeros', 'excellon_format_upper_mm', 'excellon_format_lower_mm',
  112. 'excellon_format_upper_in', 'excellon_format_lower_in', 'excellon_units', 'slots',
  113. 'source_file']
  114. # ### Patterns ####
  115. # Regex basics:
  116. # ^ - beginning
  117. # $ - end
  118. # *: 0 or more, +: 1 or more, ?: 0 or 1
  119. # M48 - Beginning of Part Program Header
  120. self.hbegin_re = re.compile(r'^M48$')
  121. # ;HEADER - Beginning of Allegro Program Header
  122. self.allegro_hbegin_re = re.compile(r'\;\s*(HEADER)')
  123. # M95 or % - End of Part Program Header
  124. # NOTE: % has different meaning in the body
  125. self.hend_re = re.compile(r'^(?:M95|%)$')
  126. # FMAT Excellon format
  127. # Ignored in the parser
  128. # self.fmat_re = re.compile(r'^FMAT,([12])$')
  129. # Uunits and possible Excellon zeros and possible Excellon format
  130. # INCH uses 6 digits
  131. # METRIC uses 5/6
  132. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?,?(\d*\.\d+)?.*$')
  133. # Tool definition/parameters (?= is look-ahead
  134. # NOTE: This might be an overkill!
  135. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  136. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  137. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  138. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  139. self.toolset_re = re.compile(r'^T(\d+)(?=.*C,?(\d*\.?\d*))?' +
  140. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  141. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  142. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  143. self.detect_gcode_re = re.compile(r'^G2([01])$')
  144. # Tool select
  145. # Can have additional data after tool number but
  146. # is ignored if present in the header.
  147. # Warning: This will match toolset_re too.
  148. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  149. self.toolsel_re = re.compile(r'^T(\d+)')
  150. # Headerless toolset
  151. # self.toolset_hl_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))')
  152. self.toolset_hl_re = re.compile(r'^T(\d+)(?:.?C(\d+\.?\d*))?')
  153. # Comment
  154. self.comm_re = re.compile(r'^;(.*)$')
  155. # Absolute/Incremental G90/G91
  156. self.absinc_re = re.compile(r'^G9([01])$')
  157. # Modes of operation
  158. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  159. self.modes_re = re.compile(r'^G0([012345])')
  160. # Measuring mode
  161. # 1-metric, 2-inch
  162. self.meas_re = re.compile(r'^M7([12])$')
  163. # Coordinates
  164. # self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  165. # self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  166. coordsperiod_re_string = r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]'
  167. self.coordsperiod_re = re.compile(coordsperiod_re_string)
  168. coordsnoperiod_re_string = r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]'
  169. self.coordsnoperiod_re = re.compile(coordsnoperiod_re_string)
  170. # Slots parsing
  171. slots_re_string = r'^([^G]+)G85(.*)$'
  172. self.slots_re = re.compile(slots_re_string)
  173. # R - Repeat hole (# times, X offset, Y offset)
  174. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  175. # Various stop/pause commands
  176. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  177. # Allegro Excellon format support
  178. self.tool_units_re = re.compile(r'(\;\s*Holesize \d+.\s*\=\s*(\d+.\d+).*(MILS|MM))')
  179. # Altium Excellon format support
  180. # it's a comment like this: ";FILE_FORMAT=2:5"
  181. self.altium_format = re.compile(r'^;\s*(?:FILE_FORMAT)?(?:Format)?[=|:]\s*(\d+)[:|.](\d+).*$')
  182. # Parse coordinates
  183. self.leadingzeros_re = re.compile(r'^[-\+]?(0*)(\d*)')
  184. # Repeating command
  185. self.repeat_re = re.compile(r'R(\d+)')
  186. def parse_file(self, filename=None, file_obj=None):
  187. """
  188. Reads the specified file as array of lines as
  189. passes it to ``parse_lines()``.
  190. :param filename: The file to be read and parsed.
  191. :type filename: str
  192. :return: None
  193. """
  194. if file_obj:
  195. estr = file_obj
  196. else:
  197. if filename is None:
  198. return "fail"
  199. efile = open(filename, 'r')
  200. estr = efile.readlines()
  201. efile.close()
  202. try:
  203. self.parse_lines(estr)
  204. except Exception:
  205. return "fail"
  206. def parse_lines(self, elines):
  207. """
  208. Main Excellon parser.
  209. :param elines: List of strings, each being a line of Excellon code.
  210. :type elines: list
  211. :return: None
  212. """
  213. # State variables
  214. current_tool = ""
  215. in_header = False
  216. headerless = False
  217. current_x = None
  218. current_y = None
  219. slot_current_x = None
  220. slot_current_y = None
  221. name_tool = 0
  222. allegro_warning = False
  223. line_units_found = False
  224. repeating_x = 0
  225. repeating_y = 0
  226. repeat = 0
  227. line_units = ''
  228. # ## Parsing starts here ## ##
  229. line_num = 0 # Line number
  230. eline = ""
  231. try:
  232. for eline in elines:
  233. if self.app.abort_flag:
  234. # graceful abort requested by the user
  235. raise FlatCAMApp.GracefulException
  236. line_num += 1
  237. # log.debug("%3d %s" % (line_num, str(eline)))
  238. self.source_file += eline
  239. # Cleanup lines
  240. eline = eline.strip(' \r\n')
  241. # Excellon files and Gcode share some extensions therefore if we detect G20 or G21 it's GCODe
  242. # and we need to exit from here
  243. if self.detect_gcode_re.search(eline):
  244. log.warning("This is GCODE mark: %s" % eline)
  245. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_('This is GCODE mark'), eline))
  246. return
  247. # Header Begin (M48) #
  248. if self.hbegin_re.search(eline):
  249. in_header = True
  250. headerless = False
  251. log.warning("Found start of the header: %s" % eline)
  252. continue
  253. # Allegro Header Begin (;HEADER) #
  254. if self.allegro_hbegin_re.search(eline):
  255. in_header = True
  256. allegro_warning = True
  257. log.warning("Found ALLEGRO start of the header: %s" % eline)
  258. continue
  259. # Search for Header End #
  260. # Since there might be comments in the header that include header end char (% or M95)
  261. # we ignore the lines starting with ';' that contains such header end chars because it is not a
  262. # real header end.
  263. if self.comm_re.search(eline):
  264. match = self.tool_units_re.search(eline)
  265. if match:
  266. if line_units_found is False:
  267. line_units_found = True
  268. line_units = match.group(3)
  269. self.convert_units({"MILS": "IN", "MM": "MM"}[line_units])
  270. log.warning("Type of Allegro UNITS found inline in comments: %s" % line_units)
  271. if match.group(2):
  272. name_tool += 1
  273. if line_units == 'MILS':
  274. spec = {"C": (float(match.group(2)) / 1000)}
  275. self.tools[str(name_tool)] = spec
  276. log.debug("Tool definition: %s %s" % (name_tool, spec))
  277. else:
  278. spec = {"C": float(match.group(2))}
  279. self.tools[str(name_tool)] = spec
  280. log.debug("Tool definition: %s %s" % (name_tool, spec))
  281. spec['solid_geometry'] = []
  282. continue
  283. # search for Altium Excellon Format / Sprint Layout who is included as a comment
  284. match = self.altium_format.search(eline)
  285. if match:
  286. self.excellon_format_upper_mm = match.group(1)
  287. self.excellon_format_lower_mm = match.group(2)
  288. self.excellon_format_upper_in = match.group(1)
  289. self.excellon_format_lower_in = match.group(2)
  290. log.warning("Altium Excellon format preset found in comments: %s:%s" %
  291. (match.group(1), match.group(2)))
  292. continue
  293. else:
  294. log.warning("Line ignored, it's a comment: %s" % eline)
  295. else:
  296. if self.hend_re.search(eline):
  297. if in_header is False or bool(self.tools) is False:
  298. log.warning("Found end of the header but there is no header: %s" % eline)
  299. log.warning("The only useful data in header are tools, units and format.")
  300. log.warning("Therefore we will create units and format based on defaults.")
  301. headerless = True
  302. try:
  303. self.convert_units({"INCH": "IN", "METRIC": "MM"}[self.excellon_units])
  304. except Exception as e:
  305. log.warning("Units could not be converted: %s" % str(e))
  306. in_header = False
  307. # for Allegro type of Excellons we reset name_tool variable so we can reuse it for toolchange
  308. if allegro_warning is True:
  309. name_tool = 0
  310. log.warning("Found end of the header: %s" % eline)
  311. continue
  312. # ## Alternative units format M71/M72
  313. # Supposed to be just in the body (yes, the body)
  314. # but some put it in the header (PADS for example).
  315. # Will detect anywhere. Occurrence will change the
  316. # object's units.
  317. match = self.meas_re.match(eline)
  318. if match:
  319. self.units = {"1": "MM", "2": "IN"}[match.group(1)]
  320. # Modified for issue #80
  321. log.debug("ALternative M71/M72 units found, before conversion: %s" % self.units)
  322. self.convert_units(self.units)
  323. log.debug("ALternative M71/M72 units found, after conversion: %s" % self.units)
  324. if self.units == 'MM':
  325. log.warning("Excellon format preset is: %s:%s" %
  326. (str(self.excellon_format_upper_mm), str(self.excellon_format_lower_mm)))
  327. else:
  328. log.warning("Excellon format preset is: %s:%s" %
  329. (str(self.excellon_format_upper_in), str(self.excellon_format_lower_in)))
  330. continue
  331. # ### Body ####
  332. if not in_header:
  333. # ## Tool change ###
  334. match = self.toolsel_re.search(eline)
  335. if match:
  336. current_tool = str(int(match.group(1)))
  337. log.debug("Tool change: %s" % current_tool)
  338. if bool(headerless):
  339. match = self.toolset_hl_re.search(eline)
  340. if match:
  341. name = str(int(match.group(1)))
  342. try:
  343. diam = float(match.group(2))
  344. except Exception:
  345. # it's possible that tool definition has only tool number and no diameter info
  346. # (those could be in another file like PCB Wizard do)
  347. # then match.group(2) = None and float(None) will create the exception
  348. # the bellow construction is so each tool will have a slightly different diameter
  349. # starting with a default value, to allow Excellon editing after that
  350. self.diameterless = True
  351. self.app.inform.emit('[WARNING] %s%s %s' %
  352. (_("No tool diameter info's. See shell.\n"
  353. "A tool change event: T"),
  354. str(current_tool),
  355. _("was found but the Excellon file "
  356. "have no informations regarding the tool "
  357. "diameters therefore the application will try to load it "
  358. "by using some 'fake' diameters.\n"
  359. "The user needs to edit the resulting Excellon object and "
  360. "change the diameters to reflect the real diameters.")
  361. )
  362. )
  363. if self.excellon_units == 'MM':
  364. diam = self.toolless_diam + (int(current_tool) - 1) / 100
  365. else:
  366. diam = (self.toolless_diam + (int(current_tool) - 1) / 100) / 25.4
  367. spec = {"C": diam, 'solid_geometry': []}
  368. self.tools[name] = spec
  369. log.debug("Tool definition out of header: %s %s" % (name, spec))
  370. continue
  371. # ## Allegro Type Tool change ###
  372. if allegro_warning is True:
  373. match = self.absinc_re.search(eline)
  374. match1 = self.stop_re.search(eline)
  375. if match or match1:
  376. name_tool += 1
  377. current_tool = str(name_tool)
  378. log.debug("Tool change for Allegro type of Excellon: %s" % current_tool)
  379. continue
  380. # ## Slots parsing for drilled slots (contain G85)
  381. # a Excellon drilled slot line may look like this:
  382. # X01125Y0022244G85Y0027756
  383. match = self.slots_re.search(eline)
  384. if match:
  385. # signal that there are milling slots operations
  386. self.defaults['excellon_drills'] = False
  387. # the slot start coordinates group is to the left of G85 command (group(1) )
  388. # the slot stop coordinates group is to the right of G85 command (group(2) )
  389. start_coords_match = match.group(1)
  390. stop_coords_match = match.group(2)
  391. # Slot coordinates without period # ##
  392. # get the coordinates for slot start and for slot stop into variables
  393. start_coords_noperiod = self.coordsnoperiod_re.search(start_coords_match)
  394. stop_coords_noperiod = self.coordsnoperiod_re.search(stop_coords_match)
  395. if start_coords_noperiod:
  396. try:
  397. slot_start_x = self.parse_number(start_coords_noperiod.group(1))
  398. slot_current_x = slot_start_x
  399. except TypeError:
  400. slot_start_x = slot_current_x
  401. except Exception:
  402. return
  403. try:
  404. slot_start_y = self.parse_number(start_coords_noperiod.group(2))
  405. slot_current_y = slot_start_y
  406. except TypeError:
  407. slot_start_y = slot_current_y
  408. except Exception:
  409. return
  410. try:
  411. slot_stop_x = self.parse_number(stop_coords_noperiod.group(1))
  412. slot_current_x = slot_stop_x
  413. except TypeError:
  414. slot_stop_x = slot_current_x
  415. except Exception:
  416. return
  417. try:
  418. slot_stop_y = self.parse_number(stop_coords_noperiod.group(2))
  419. slot_current_y = slot_stop_y
  420. except TypeError:
  421. slot_stop_y = slot_current_y
  422. except Exception:
  423. return
  424. if (slot_start_x is None or slot_start_y is None or
  425. slot_stop_x is None or slot_stop_y is None):
  426. log.error("Slots are missing some or all coordinates.")
  427. continue
  428. # we have a slot
  429. log.debug('Parsed a slot with coordinates: ' + str([slot_start_x,
  430. slot_start_y, slot_stop_x,
  431. slot_stop_y]))
  432. # store current tool diameter as slot diameter
  433. slot_dia = 0.05
  434. try:
  435. slot_dia = float(self.tools[current_tool]['C'])
  436. except Exception as e:
  437. pass
  438. log.debug(
  439. 'Milling/Drilling slot with tool %s, diam=%f' % (
  440. current_tool,
  441. slot_dia
  442. )
  443. )
  444. self.slots.append(
  445. {
  446. 'start': Point(slot_start_x, slot_start_y),
  447. 'stop': Point(slot_stop_x, slot_stop_y),
  448. 'tool': current_tool
  449. }
  450. )
  451. continue
  452. # Slot coordinates with period: Use literally. ###
  453. # get the coordinates for slot start and for slot stop into variables
  454. start_coords_period = self.coordsperiod_re.search(start_coords_match)
  455. stop_coords_period = self.coordsperiod_re.search(stop_coords_match)
  456. if start_coords_period:
  457. try:
  458. slot_start_x = float(start_coords_period.group(1))
  459. slot_current_x = slot_start_x
  460. except TypeError:
  461. slot_start_x = slot_current_x
  462. except Exception:
  463. return
  464. try:
  465. slot_start_y = float(start_coords_period.group(2))
  466. slot_current_y = slot_start_y
  467. except TypeError:
  468. slot_start_y = slot_current_y
  469. except Exception:
  470. return
  471. try:
  472. slot_stop_x = float(stop_coords_period.group(1))
  473. slot_current_x = slot_stop_x
  474. except TypeError:
  475. slot_stop_x = slot_current_x
  476. except Exception:
  477. return
  478. try:
  479. slot_stop_y = float(stop_coords_period.group(2))
  480. slot_current_y = slot_stop_y
  481. except TypeError:
  482. slot_stop_y = slot_current_y
  483. except Exception:
  484. return
  485. if (slot_start_x is None or slot_start_y is None or
  486. slot_stop_x is None or slot_stop_y is None):
  487. log.error("Slots are missing some or all coordinates.")
  488. continue
  489. # we have a slot
  490. log.debug('Parsed a slot with coordinates: ' + str([slot_start_x,
  491. slot_start_y, slot_stop_x,
  492. slot_stop_y]))
  493. # store current tool diameter as slot diameter
  494. slot_dia = 0.05
  495. try:
  496. slot_dia = float(self.tools[current_tool]['C'])
  497. except Exception as e:
  498. pass
  499. log.debug(
  500. 'Milling/Drilling slot with tool %s, diam=%f' % (
  501. current_tool,
  502. slot_dia
  503. )
  504. )
  505. self.slots.append(
  506. {
  507. 'start': Point(slot_start_x, slot_start_y),
  508. 'stop': Point(slot_stop_x, slot_stop_y),
  509. 'tool': current_tool
  510. }
  511. )
  512. continue
  513. # ## Coordinates without period # ##
  514. match = self.coordsnoperiod_re.search(eline)
  515. if match:
  516. matchr = self.repeat_re.search(eline)
  517. if matchr:
  518. repeat = int(matchr.group(1))
  519. try:
  520. x = self.parse_number(match.group(1))
  521. repeating_x = current_x
  522. current_x = x
  523. except TypeError:
  524. x = current_x
  525. repeating_x = 0
  526. except Exception:
  527. return
  528. try:
  529. y = self.parse_number(match.group(2))
  530. repeating_y = current_y
  531. current_y = y
  532. except TypeError:
  533. y = current_y
  534. repeating_y = 0
  535. except Exception:
  536. return
  537. if x is None or y is None:
  538. log.error("Missing coordinates")
  539. continue
  540. # ## Excellon Routing parse
  541. if len(re.findall("G00", eline)) > 0:
  542. self.match_routing_start = 'G00'
  543. # signal that there are milling slots operations
  544. self.defaults['excellon_drills'] = False
  545. self.routing_flag = 0
  546. slot_start_x = x
  547. slot_start_y = y
  548. continue
  549. if self.routing_flag == 0:
  550. if len(re.findall("G01", eline)) > 0:
  551. self.match_routing_stop = 'G01'
  552. # signal that there are milling slots operations
  553. self.defaults['excellon_drills'] = False
  554. self.routing_flag = 1
  555. slot_stop_x = x
  556. slot_stop_y = y
  557. self.slots.append(
  558. {
  559. 'start': Point(slot_start_x, slot_start_y),
  560. 'stop': Point(slot_stop_x, slot_stop_y),
  561. 'tool': current_tool
  562. }
  563. )
  564. continue
  565. if self.match_routing_start is None and self.match_routing_stop is None:
  566. if repeat == 0:
  567. # signal that there are drill operations
  568. self.defaults['excellon_drills'] = True
  569. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  570. else:
  571. coordx = x
  572. coordy = y
  573. while repeat > 0:
  574. if repeating_x:
  575. coordx = (repeat * x) + repeating_x
  576. if repeating_y:
  577. coordy = (repeat * y) + repeating_y
  578. self.drills.append({'point': Point((coordx, coordy)), 'tool': current_tool})
  579. repeat -= 1
  580. repeating_x = repeating_y = 0
  581. # log.debug("{:15} {:8} {:8}".format(eline, x, y))
  582. continue
  583. # ## Coordinates with period: Use literally. # ##
  584. match = self.coordsperiod_re.search(eline)
  585. if match:
  586. matchr = self.repeat_re.search(eline)
  587. if matchr:
  588. repeat = int(matchr.group(1))
  589. if match:
  590. # signal that there are drill operations
  591. self.defaults['excellon_drills'] = True
  592. try:
  593. x = float(match.group(1))
  594. repeating_x = current_x
  595. current_x = x
  596. except TypeError:
  597. x = current_x
  598. repeating_x = 0
  599. try:
  600. y = float(match.group(2))
  601. repeating_y = current_y
  602. current_y = y
  603. except TypeError:
  604. y = current_y
  605. repeating_y = 0
  606. if x is None or y is None:
  607. log.error("Missing coordinates")
  608. continue
  609. # ## Excellon Routing parse
  610. if len(re.findall("G00", eline)) > 0:
  611. self.match_routing_start = 'G00'
  612. # signal that there are milling slots operations
  613. self.defaults['excellon_drills'] = False
  614. self.routing_flag = 0
  615. slot_start_x = x
  616. slot_start_y = y
  617. continue
  618. if self.routing_flag == 0:
  619. if len(re.findall("G01", eline)) > 0:
  620. self.match_routing_stop = 'G01'
  621. # signal that there are milling slots operations
  622. self.defaults['excellon_drills'] = False
  623. self.routing_flag = 1
  624. slot_stop_x = x
  625. slot_stop_y = y
  626. self.slots.append(
  627. {
  628. 'start': Point(slot_start_x, slot_start_y),
  629. 'stop': Point(slot_stop_x, slot_stop_y),
  630. 'tool': current_tool
  631. }
  632. )
  633. continue
  634. if self.match_routing_start is None and self.match_routing_stop is None:
  635. # signal that there are drill operations
  636. if repeat == 0:
  637. # signal that there are drill operations
  638. self.defaults['excellon_drills'] = True
  639. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  640. else:
  641. coordx = x
  642. coordy = y
  643. while repeat > 0:
  644. if repeating_x:
  645. coordx = (repeat * x) + repeating_x
  646. if repeating_y:
  647. coordy = (repeat * y) + repeating_y
  648. self.drills.append({'point': Point((coordx, coordy)), 'tool': current_tool})
  649. repeat -= 1
  650. repeating_x = repeating_y = 0
  651. # log.debug("{:15} {:8} {:8}".format(eline, x, y))
  652. continue
  653. # ### Header ####
  654. if in_header:
  655. # ## Tool definitions # ##
  656. match = self.toolset_re.search(eline)
  657. if match:
  658. name = str(int(match.group(1)))
  659. spec = {"C": float(match.group(2)), 'solid_geometry': []}
  660. self.tools[name] = spec
  661. log.debug("Tool definition: %s %s" % (name, spec))
  662. continue
  663. # ## Units and number format # ##
  664. match = self.units_re.match(eline)
  665. if match:
  666. self.units = self.units = {"METRIC": "MM", "INCH": "IN"}[match.group(1)]
  667. self.zeros = match.group(2) # "T" or "L". Might be empty
  668. self.excellon_format = match.group(3)
  669. if self.excellon_format:
  670. upper = len(self.excellon_format.partition('.')[0])
  671. lower = len(self.excellon_format.partition('.')[2])
  672. if self.units == 'MM':
  673. self.excellon_format_upper_mm = upper
  674. self.excellon_format_lower_mm = lower
  675. else:
  676. self.excellon_format_upper_in = upper
  677. self.excellon_format_lower_in = lower
  678. # Modified for issue #80
  679. log.warning("UNITS found inline before conversion: %s" % self.units)
  680. self.convert_units(self.units)
  681. log.warning("UNITS found inline after conversion: %s" % self.units)
  682. if self.units == 'MM':
  683. log.warning("Excellon format preset is: %s:%s" %
  684. (str(self.excellon_format_upper_mm), str(self.excellon_format_lower_mm)))
  685. else:
  686. log.warning("Excellon format preset is: %s:%s" %
  687. (str(self.excellon_format_upper_in), str(self.excellon_format_lower_in)))
  688. log.warning("Type of ZEROS found inline, in header: %s" % self.zeros)
  689. continue
  690. # Search for units type again it might be alone on the line
  691. if "INCH" in eline:
  692. line_units = "IN"
  693. # Modified for issue #80
  694. log.warning("Type of UNITS found inline, in header, before conversion: %s" % line_units)
  695. self.convert_units(line_units)
  696. log.warning("Type of UNITS found inline, in header, after conversion: %s" % self.units)
  697. log.warning("Excellon format preset is: %s:%s" %
  698. (str(self.excellon_format_upper_in), str(self.excellon_format_lower_in)))
  699. continue
  700. elif "METRIC" in eline:
  701. line_units = "MM"
  702. # Modified for issue #80
  703. log.warning("Type of UNITS found inline, in header, before conversion: %s" % line_units)
  704. self.convert_units(line_units)
  705. log.warning("Type of UNITS found inline, in header, after conversion: %s" % self.units)
  706. log.warning("Excellon format preset is: %s:%s" %
  707. (str(self.excellon_format_upper_mm), str(self.excellon_format_lower_mm)))
  708. continue
  709. # Search for zeros type again because it might be alone on the line
  710. match = re.search(r'[LT]Z', eline)
  711. if match:
  712. self.zeros = match.group()
  713. log.warning("Type of ZEROS found: %s" % self.zeros)
  714. continue
  715. # ## Units and number format outside header# ##
  716. match = self.units_re.match(eline)
  717. if match:
  718. self.units = self.units = {"METRIC": "MM", "INCH": "IN"}[match.group(1)]
  719. self.zeros = match.group(2) # "T" or "L". Might be empty
  720. self.excellon_format = match.group(3)
  721. if self.excellon_format:
  722. upper = len(self.excellon_format.partition('.')[0])
  723. lower = len(self.excellon_format.partition('.')[2])
  724. if self.units == 'MM':
  725. self.excellon_format_upper_mm = upper
  726. self.excellon_format_lower_mm = lower
  727. else:
  728. self.excellon_format_upper_in = upper
  729. self.excellon_format_lower_in = lower
  730. # Modified for issue #80
  731. log.warning("Type of UNITS found outside header, inline before conversion: %s" % self.units)
  732. self.convert_units(self.units)
  733. log.warning("Type of UNITS found outside header, inline after conversion: %s" % self.units)
  734. if self.units == 'MM':
  735. log.warning("Excellon format preset is: %s:%s" %
  736. (str(self.excellon_format_upper_mm), str(self.excellon_format_lower_mm)))
  737. else:
  738. log.warning("Excellon format preset is: %s:%s" %
  739. (str(self.excellon_format_upper_in), str(self.excellon_format_lower_in)))
  740. log.warning("Type of ZEROS found outside header, inline: %s" % self.zeros)
  741. continue
  742. log.warning("Line ignored: %s" % eline)
  743. # make sure that since we are in headerless mode, we convert the tools only after the file parsing
  744. # is finished since the tools definitions are spread in the Excellon body. We use as units the value
  745. # from self.defaults['excellon_units']
  746. log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
  747. except Exception:
  748. log.error("Excellon PARSING FAILED. Line %d: %s" % (line_num, eline))
  749. msg = '[ERROR_NOTCL] %s' % \
  750. _("An internal error has ocurred. See shell.\n")
  751. msg += _('{e_code} Excellon Parser error.\nParsing Failed. Line {l_nr}: {line}\n').format(
  752. e_code='[ERROR]',
  753. l_nr=line_num,
  754. line=eline)
  755. msg += traceback.format_exc()
  756. self.app.inform.emit(msg)
  757. return "fail"
  758. def parse_number(self, number_str):
  759. """
  760. Parses coordinate numbers without period.
  761. :param number_str: String representing the numerical value.
  762. :type number_str: str
  763. :return: Floating point representation of the number
  764. :rtype: float
  765. """
  766. match = self.leadingzeros_re.search(number_str)
  767. nr_length = len(match.group(1)) + len(match.group(2))
  768. try:
  769. if self.zeros == "L" or self.zeros == "LZ": # Leading
  770. # With leading zeros, when you type in a coordinate,
  771. # the leading zeros must always be included. Trailing zeros
  772. # are unneeded and may be left off. The CNC-7 will automatically add them.
  773. # r'^[-\+]?(0*)(\d*)'
  774. # 6 digits are divided by 10^4
  775. # If less than size digits, they are automatically added,
  776. # 5 digits then are divided by 10^3 and so on.
  777. if self.units.lower() == "in":
  778. result = float(number_str) / (10 ** (float(nr_length) - float(self.excellon_format_upper_in)))
  779. else:
  780. result = float(number_str) / (10 ** (float(nr_length) - float(self.excellon_format_upper_mm)))
  781. return result
  782. else: # Trailing
  783. # You must show all zeros to the right of the number and can omit
  784. # all zeros to the left of the number. The CNC-7 will count the number
  785. # of digits you typed and automatically fill in the missing zeros.
  786. # ## flatCAM expects 6digits
  787. # flatCAM expects the number of digits entered into the defaults
  788. if self.units.lower() == "in": # Inches is 00.0000
  789. result = float(number_str) / (10 ** (float(self.excellon_format_lower_in)))
  790. else: # Metric is 000.000
  791. result = float(number_str) / (10 ** (float(self.excellon_format_lower_mm)))
  792. return result
  793. except Exception as e:
  794. log.error("Aborted. Operation could not be completed due of %s" % str(e))
  795. return
  796. def create_geometry(self):
  797. """
  798. Creates circles of the tool diameter at every point
  799. specified in ``self.drills``. Also creates geometries (polygons)
  800. for the slots as specified in ``self.slots``
  801. All the resulting geometry is stored into self.solid_geometry list.
  802. The list self.solid_geometry has 2 elements: first is a dict with the drills geometry,
  803. and second element is another similar dict that contain the slots geometry.
  804. Each dict has as keys the tool diameters and as values lists with Shapely objects, the geometries
  805. ================ ====================================
  806. Key Value
  807. ================ ====================================
  808. tool_diameter list of (Shapely.Point) Where to drill
  809. ================ ====================================
  810. :return: None
  811. """
  812. log.debug("flatcamParsers.ParseExcellon.Excellon.create_geometry()")
  813. self.solid_geometry = []
  814. try:
  815. # clear the solid_geometry in self.tools
  816. for tool in self.tools:
  817. try:
  818. self.tools[tool]['solid_geometry'][:] = []
  819. except KeyError:
  820. self.tools[tool]['solid_geometry'] = []
  821. for drill in self.drills:
  822. # poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  823. if drill['tool'] is '':
  824. self.app.inform.emit('[WARNING] %s' %
  825. _("Excellon.create_geometry() -> a drill location was skipped "
  826. "due of not having a tool associated.\n"
  827. "Check the resulting GCode."))
  828. log.debug("flatcamParsers.ParseExcellon.Excellon.create_geometry() -> a drill location was skipped "
  829. "due of not having a tool associated")
  830. continue
  831. tooldia = self.tools[drill['tool']]['C']
  832. poly = drill['point'].buffer(tooldia / 2.0, int(int(self.geo_steps_per_circle) / 4))
  833. self.solid_geometry.append(poly)
  834. self.tools[drill['tool']]['solid_geometry'].append(poly)
  835. for slot in self.slots:
  836. slot_tooldia = self.tools[slot['tool']]['C']
  837. start = slot['start']
  838. stop = slot['stop']
  839. lines_string = LineString([start, stop])
  840. poly = lines_string.buffer(slot_tooldia / 2.0, int(int(self.geo_steps_per_circle) / 4))
  841. self.solid_geometry.append(poly)
  842. self.tools[slot['tool']]['solid_geometry'].append(poly)
  843. except Exception as e:
  844. log.debug("flatcamParsers.ParseExcellon.Excellon.create_geometry() -> "
  845. "Excellon geometry creation failed due of ERROR: %s" % str(e))
  846. return "fail"
  847. def bounds(self):
  848. """
  849. Returns coordinates of rectangular bounds
  850. of Excellon geometry: (xmin, ymin, xmax, ymax).
  851. """
  852. # fixed issue of getting bounds only for one level lists of objects
  853. # now it can get bounds for nested lists of objects
  854. log.debug("flatcamParsers.ParseExcellon.Excellon.bounds()")
  855. if self.solid_geometry is None or not self.tools:
  856. log.debug("flatcamParsers.ParseExcellon.Excellon -> solid_geometry is None")
  857. return 0, 0, 0, 0
  858. def bounds_rec(obj):
  859. if type(obj) is list:
  860. minx = np.Inf
  861. miny = np.Inf
  862. maxx = -np.Inf
  863. maxy = -np.Inf
  864. for k in obj:
  865. if type(k) is dict:
  866. for key in k:
  867. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  868. minx = min(minx, minx_)
  869. miny = min(miny, miny_)
  870. maxx = max(maxx, maxx_)
  871. maxy = max(maxy, maxy_)
  872. else:
  873. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  874. minx = min(minx, minx_)
  875. miny = min(miny, miny_)
  876. maxx = max(maxx, maxx_)
  877. maxy = max(maxy, maxy_)
  878. return minx, miny, maxx, maxy
  879. else:
  880. # it's a Shapely object, return it's bounds
  881. return obj.bounds
  882. minx_list = []
  883. miny_list = []
  884. maxx_list = []
  885. maxy_list = []
  886. for tool in self.tools:
  887. minx, miny, maxx, maxy = bounds_rec(self.tools[tool]['solid_geometry'])
  888. minx_list.append(minx)
  889. miny_list.append(miny)
  890. maxx_list.append(maxx)
  891. maxy_list.append(maxy)
  892. return min(minx_list), min(miny_list), max(maxx_list), max(maxy_list)
  893. def convert_units(self, units):
  894. """
  895. This function first convert to the the units found in the Excellon file but it converts tools that
  896. are not there yet so it has no effect other than it signal that the units are the ones in the file.
  897. On object creation, in new_object(), true conversion is done because this is done at the end of the
  898. Excellon file parsing, the tools are inside and self.tools is really converted from the units found
  899. inside the file to the FlatCAM units.
  900. Kind of convolute way to make the conversion and it is based on the assumption that the Excellon file
  901. will have detected the units before the tools are parsed and stored in self.tools
  902. :param units:
  903. :type str: IN or MM
  904. :return:
  905. """
  906. # factor = Geometry.convert_units(self, units)
  907. obj_units = units
  908. if obj_units.upper() == self.units.upper():
  909. factor = 1.0
  910. elif obj_units.upper() == "MM":
  911. factor = 25.4
  912. elif obj_units.upper() == "IN":
  913. factor = 1 / 25.4
  914. else:
  915. log.error("Unsupported units: %s" % str(obj_units))
  916. factor = 1.0
  917. log.debug("flatcamParsers.ParseExcellon.Excellon.convert_units() --> Factor: %s" % str(factor))
  918. self.units = obj_units
  919. self.scale(factor, factor)
  920. self.file_units_factor = factor
  921. # Tools
  922. for tname in self.tools:
  923. self.tools[tname]["C"] *= factor
  924. self.create_geometry()
  925. return factor
  926. def scale(self, xfactor, yfactor=None, point=None):
  927. """
  928. Scales geometry on the XY plane in the object by a given factor.
  929. Tool sizes, feedrates an Z-plane dimensions are untouched.
  930. :param xfactor: Number by which to scale the object.
  931. :type xfactor: float
  932. :param yfactor: Number by which to scale the object.
  933. :type yfactor: float
  934. :return: None
  935. :rtype: NOne
  936. """
  937. log.debug("flatcamParsers.ParseExcellon.Excellon.scale()")
  938. if yfactor is None:
  939. yfactor = xfactor
  940. if point is None:
  941. px = 0
  942. py = 0
  943. else:
  944. px, py = point
  945. if xfactor == 0 and yfactor == 0:
  946. return
  947. def scale_geom(obj):
  948. if type(obj) is list:
  949. new_obj = []
  950. for g in obj:
  951. new_obj.append(scale_geom(g))
  952. return new_obj
  953. else:
  954. try:
  955. return affinity.scale(obj, xfactor, yfactor, origin=(px, py))
  956. except AttributeError:
  957. return obj
  958. # variables to display the percentage of work done
  959. self.geo_len = 0
  960. try:
  961. for g in self.drills:
  962. self.geo_len += 1
  963. except TypeError:
  964. self.geo_len = 1
  965. self.old_disp_number = 0
  966. self.el_count = 0
  967. # Drills
  968. for drill in self.drills:
  969. drill['point'] = affinity.scale(drill['point'], xfactor, yfactor, origin=(px, py))
  970. self.el_count += 1
  971. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  972. if self.old_disp_number < disp_number <= 100:
  973. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  974. self.old_disp_number = disp_number
  975. # scale solid_geometry
  976. for tool in self.tools:
  977. self.tools[tool]['solid_geometry'] = scale_geom(self.tools[tool]['solid_geometry'])
  978. # Slots
  979. for slot in self.slots:
  980. slot['stop'] = affinity.scale(slot['stop'], xfactor, yfactor, origin=(px, py))
  981. slot['start'] = affinity.scale(slot['start'], xfactor, yfactor, origin=(px, py))
  982. self.create_geometry()
  983. self.app.proc_container.new_text = ''
  984. def offset(self, vect):
  985. """
  986. Offsets geometry on the XY plane in the object by a given vector.
  987. :param vect: (x, y) offset vector.
  988. :type vect: tuple
  989. :return: None
  990. """
  991. log.debug("flatcamParsers.ParseExcellon.Excellon.offset()")
  992. dx, dy = vect
  993. if dx == 0 and dy == 0:
  994. return
  995. def offset_geom(obj):
  996. if type(obj) is list:
  997. new_obj = []
  998. for g in obj:
  999. new_obj.append(offset_geom(g))
  1000. return new_obj
  1001. else:
  1002. try:
  1003. return affinity.translate(obj, xoff=dx, yoff=dy)
  1004. except AttributeError:
  1005. return obj
  1006. # variables to display the percentage of work done
  1007. self.geo_len = 0
  1008. try:
  1009. for g in self.drills:
  1010. self.geo_len += 1
  1011. except TypeError:
  1012. self.geo_len = 1
  1013. self.old_disp_number = 0
  1014. self.el_count = 0
  1015. # Drills
  1016. for drill in self.drills:
  1017. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  1018. self.el_count += 1
  1019. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1020. if self.old_disp_number < disp_number <= 100:
  1021. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1022. self.old_disp_number = disp_number
  1023. # offset solid_geometry
  1024. for tool in self.tools:
  1025. self.tools[tool]['solid_geometry'] = offset_geom(self.tools[tool]['solid_geometry'])
  1026. # Slots
  1027. for slot in self.slots:
  1028. slot['stop'] = affinity.translate(slot['stop'], xoff=dx, yoff=dy)
  1029. slot['start'] = affinity.translate(slot['start'], xoff=dx, yoff=dy)
  1030. # Recreate geometry
  1031. self.create_geometry()
  1032. self.app.proc_container.new_text = ''
  1033. def mirror(self, axis, point):
  1034. """
  1035. :param axis: "X" or "Y" indicates around which axis to mirror.
  1036. :type axis: str
  1037. :param point: [x, y] point belonging to the mirror axis.
  1038. :type point: list
  1039. :return: None
  1040. """
  1041. log.debug("flatcamParsers.ParseExcellon.Excellon.mirror()")
  1042. px, py = point
  1043. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1044. def mirror_geom(obj):
  1045. if type(obj) is list:
  1046. new_obj = []
  1047. for g in obj:
  1048. new_obj.append(mirror_geom(g))
  1049. return new_obj
  1050. else:
  1051. try:
  1052. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1053. except AttributeError:
  1054. return obj
  1055. # Modify data
  1056. # variables to display the percentage of work done
  1057. self.geo_len = 0
  1058. try:
  1059. for g in self.drills:
  1060. self.geo_len += 1
  1061. except TypeError:
  1062. self.geo_len = 1
  1063. self.old_disp_number = 0
  1064. self.el_count = 0
  1065. # Drills
  1066. for drill in self.drills:
  1067. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  1068. self.el_count += 1
  1069. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1070. if self.old_disp_number < disp_number <= 100:
  1071. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1072. self.old_disp_number = disp_number
  1073. # mirror solid_geometry
  1074. for tool in self.tools:
  1075. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  1076. # Slots
  1077. for slot in self.slots:
  1078. slot['stop'] = affinity.scale(slot['stop'], xscale, yscale, origin=(px, py))
  1079. slot['start'] = affinity.scale(slot['start'], xscale, yscale, origin=(px, py))
  1080. # Recreate geometry
  1081. self.create_geometry()
  1082. self.app.proc_container.new_text = ''
  1083. def skew(self, angle_x=None, angle_y=None, point=None):
  1084. """
  1085. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1086. Tool sizes, feedrates an Z-plane dimensions are untouched.
  1087. Parameters
  1088. ----------
  1089. xs, ys : float, float
  1090. The shear angle(s) for the x and y axes respectively. These can be
  1091. specified in either degrees (default) or radians by setting
  1092. use_radians=True.
  1093. See shapely manual for more information:
  1094. http://toblerity.org/shapely/manual.html#affine-transformations
  1095. """
  1096. log.debug("flatcamParsers.ParseExcellon.Excellon.skew()")
  1097. if angle_x is None:
  1098. angle_x = 0.0
  1099. if angle_y is None:
  1100. angle_y = 0.0
  1101. if angle_x == 0 and angle_y == 0:
  1102. return
  1103. def skew_geom(obj):
  1104. if type(obj) is list:
  1105. new_obj = []
  1106. for g in obj:
  1107. new_obj.append(skew_geom(g))
  1108. return new_obj
  1109. else:
  1110. try:
  1111. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1112. except AttributeError:
  1113. return obj
  1114. # variables to display the percentage of work done
  1115. self.geo_len = 0
  1116. try:
  1117. for g in self.drills:
  1118. self.geo_len += 1
  1119. except TypeError:
  1120. self.geo_len = 1
  1121. self.old_disp_number = 0
  1122. self.el_count = 0
  1123. if point is None:
  1124. px, py = 0, 0
  1125. # Drills
  1126. for drill in self.drills:
  1127. drill['point'] = affinity.skew(drill['point'], angle_x, angle_y,
  1128. origin=(px, py))
  1129. self.el_count += 1
  1130. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1131. if self.old_disp_number < disp_number <= 100:
  1132. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1133. self.old_disp_number = disp_number
  1134. # skew solid_geometry
  1135. for tool in self.tools:
  1136. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1137. # Slots
  1138. for slot in self.slots:
  1139. slot['stop'] = affinity.skew(slot['stop'], angle_x, angle_y, origin=(px, py))
  1140. slot['start'] = affinity.skew(slot['start'], angle_x, angle_y, origin=(px, py))
  1141. else:
  1142. px, py = point
  1143. # Drills
  1144. for drill in self.drills:
  1145. drill['point'] = affinity.skew(drill['point'], angle_x, angle_y,
  1146. origin=(px, py))
  1147. self.el_count += 1
  1148. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1149. if self.old_disp_number < disp_number <= 100:
  1150. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1151. self.old_disp_number = disp_number
  1152. # skew solid_geometry
  1153. for tool in self.tools:
  1154. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1155. # Slots
  1156. for slot in self.slots:
  1157. slot['stop'] = affinity.skew(slot['stop'], angle_x, angle_y, origin=(px, py))
  1158. slot['start'] = affinity.skew(slot['start'], angle_x, angle_y, origin=(px, py))
  1159. self.create_geometry()
  1160. self.app.proc_container.new_text = ''
  1161. def rotate(self, angle, point=None):
  1162. """
  1163. Rotate the geometry of an object by an angle around the 'point' coordinates
  1164. :param angle:
  1165. :param point: tuple of coordinates (x, y)
  1166. :return:
  1167. """
  1168. log.debug("flatcamParsers.ParseExcellon.Excellon.rotate()")
  1169. if angle == 0:
  1170. return
  1171. def rotate_geom(obj, origin=None):
  1172. if type(obj) is list:
  1173. new_obj = []
  1174. for g in obj:
  1175. new_obj.append(rotate_geom(g))
  1176. return new_obj
  1177. else:
  1178. if origin:
  1179. try:
  1180. return affinity.rotate(obj, angle, origin=origin)
  1181. except AttributeError:
  1182. return obj
  1183. else:
  1184. try:
  1185. return affinity.rotate(obj, angle, origin=(px, py))
  1186. except AttributeError:
  1187. return obj
  1188. # variables to display the percentage of work done
  1189. self.geo_len = 0
  1190. try:
  1191. for g in self.drills:
  1192. self.geo_len += 1
  1193. except TypeError:
  1194. self.geo_len = 1
  1195. self.old_disp_number = 0
  1196. self.el_count = 0
  1197. if point is None:
  1198. # Drills
  1199. for drill in self.drills:
  1200. drill['point'] = affinity.rotate(drill['point'], angle, origin='center')
  1201. # rotate solid_geometry
  1202. for tool in self.tools:
  1203. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'], origin='center')
  1204. self.el_count += 1
  1205. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1206. if self.old_disp_number < disp_number <= 100:
  1207. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1208. self.old_disp_number = disp_number
  1209. # Slots
  1210. for slot in self.slots:
  1211. slot['stop'] = affinity.rotate(slot['stop'], angle, origin='center')
  1212. slot['start'] = affinity.rotate(slot['start'], angle, origin='center')
  1213. else:
  1214. px, py = point
  1215. # Drills
  1216. for drill in self.drills:
  1217. drill['point'] = affinity.rotate(drill['point'], angle, origin=(px, py))
  1218. self.el_count += 1
  1219. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1220. if self.old_disp_number < disp_number <= 100:
  1221. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1222. self.old_disp_number = disp_number
  1223. # rotate solid_geometry
  1224. for tool in self.tools:
  1225. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  1226. # Slots
  1227. for slot in self.slots:
  1228. slot['stop'] = affinity.rotate(slot['stop'], angle, origin=(px, py))
  1229. slot['start'] = affinity.rotate(slot['start'], angle, origin=(px, py))
  1230. self.create_geometry()
  1231. self.app.proc_container.new_text = ''