ParseExcellon.py 62 KB

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