ParseExcellon.py 65 KB

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