ParseExcellon.py 64 KB

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