TclCommandPaint.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. from tclCommands.TclCommand import TclCommand
  2. import collections
  3. import logging
  4. import gettext
  5. import FlatCAMTranslation as fcTranslate
  6. import builtins
  7. fcTranslate.apply_language('strings')
  8. if '_' not in builtins.__dict__:
  9. _ = gettext.gettext
  10. log = logging.getLogger('base')
  11. class TclCommandPaint(TclCommand):
  12. """
  13. Paint the interior of polygons
  14. """
  15. # Array of all command aliases, to be able use old names for backward compatibility (add_poly, add_polygon)
  16. aliases = ['paint']
  17. description = '%s %s' % ("--", "Paint polygons in the specified object by covering them with toolpaths.")
  18. # dictionary of types from Tcl command, needs to be ordered
  19. arg_names = collections.OrderedDict([
  20. ('name', str),
  21. ])
  22. # dictionary of types from Tcl command, needs to be ordered , this is for options like -optionname value
  23. option_types = collections.OrderedDict([
  24. ('tooldia', str),
  25. ('overlap', float),
  26. ('order', str),
  27. ('margin', float),
  28. ('method', str),
  29. ('connect', str),
  30. ('contour', str),
  31. ('all', str),
  32. ('single', str),
  33. ('ref', str),
  34. ('box', str),
  35. ('x', float),
  36. ('y', float),
  37. ('outname', str),
  38. ])
  39. # array of mandatory options for current Tcl command: required = {'name','outname'}
  40. required = ['name']
  41. # structured help for current command, args needs to be ordered
  42. help = {
  43. 'main': "Paint polygons in the specified object by covering them with toolpaths.",
  44. 'args': collections.OrderedDict([
  45. ('name', 'Name of the source Geometry object. String.'),
  46. ('tooldia', 'Diameter of the tool to be used. Can be a comma separated list of diameters. No space is '
  47. 'allowed between tool diameters. E.g: correct: 0.5,1 / incorrect: 0.5, 1'),
  48. ('overlap', 'Percentage of tool diameter to overlap current pass over previous pass. Float [0, 99.9999]\n'
  49. 'E.g: for a 25% from tool diameter overlap use -overlap 25'),
  50. ('margin', 'Bounding box margin. Float number.'),
  51. ('order', 'Can have the values: "no", "fwd" and "rev". String.'
  52. 'It is useful when there are multiple tools in tooldia parameter.'
  53. '"no" -> the order used is the one provided.'
  54. '"fwd" -> tools are ordered from smallest to biggest.'
  55. '"rev" -> tools are ordered from biggest to smallest.'),
  56. ('method', 'Algorithm for painting. Can be: "standard", "seed", "lines", "laser_lines", "combo".'),
  57. ('connect', 'Draw lines to minimize tool lifts. True (1) or False (0)'),
  58. ('contour', 'Cut around the perimeter of the painting. True (1) or False (0)'),
  59. ('all', 'If used, paint all polygons in the object.'),
  60. ('box', 'name of the object to be used as paint reference. String.'),
  61. ('single', 'Paint a single polygon specified by "x" and "y" parameters. True (1) or False (0)'),
  62. ('x', 'X value of coordinate for the selection of a single polygon. Float number.'),
  63. ('y', 'Y value of coordinate for the selection of a single polygon. Float number.'),
  64. ('outname', 'Name of the resulting Geometry object. String.'),
  65. ]),
  66. 'examples': ["paint obj_name -tooldia 0.3 -margin 0.1 -method 'seed' -all"]
  67. }
  68. def execute(self, args, unnamed_args):
  69. """
  70. execute current TCL shell command
  71. :param args: array of known named arguments and options
  72. :param unnamed_args: array of other values which were passed into command
  73. without -somename and we do not have them in known arg_names
  74. :return: None or exception
  75. """
  76. name = args['name']
  77. # Get source object.
  78. try:
  79. obj = self.app.collection.get_by_name(str(name))
  80. except Exception as e:
  81. log.debug("TclCommandPaint.execute() --> %s" % str(e))
  82. self.raise_tcl_error("%s: %s" % (_("Could not retrieve object"), name))
  83. return "Could not retrieve object: %s" % name
  84. if 'tooldia' in args:
  85. tooldia = str(args['tooldia'])
  86. else:
  87. tooldia = float(self.app.defaults["tools_paintoverlap"])
  88. if 'overlap' in args:
  89. overlap = float(args['overlap']) / 100.0
  90. else:
  91. overlap = float(self.app.defaults["tools_paintoverlap"]) / 100.0
  92. if 'order' in args:
  93. order = args['order']
  94. else:
  95. order = str(self.app.defaults["tools_paintorder"])
  96. if 'margin' in args:
  97. margin = float(args['margin'])
  98. else:
  99. margin = float(self.app.defaults["tools_paintmargin"])
  100. if 'method' in args:
  101. method = args['method']
  102. if method == "standard":
  103. method = _("Standard")
  104. elif method == "seed":
  105. method = _("Seed")
  106. elif method == "lines":
  107. method = _("Lines")
  108. elif method == "laser_lines":
  109. method = _("Laser_lines")
  110. else:
  111. method = _("Combo")
  112. else:
  113. method = str(self.app.defaults["tools_paintmethod"])
  114. if 'connect' in args:
  115. try:
  116. par = args['connect'].capitalize()
  117. except AttributeError:
  118. par = args['connect']
  119. connect = bool(eval(par))
  120. else:
  121. connect = bool(eval(str(self.app.defaults["tools_pathconnect"])))
  122. if 'contour' in args:
  123. try:
  124. par = args['contour'].capitalize()
  125. except AttributeError:
  126. par = args['contour']
  127. contour = bool(eval(par))
  128. else:
  129. contour = bool(eval(str(self.app.defaults["tools_paintcontour"])))
  130. if 'outname' in args:
  131. outname = args['outname']
  132. else:
  133. outname = name + "_paint"
  134. # used only to have correct information's in the obj.tools[tool]['data'] dict
  135. if "all" in args:
  136. select = _("All Polygons")
  137. elif "single" in args:
  138. select = _("Polygon Selection")
  139. else:
  140. select = _("Reference Object")
  141. try:
  142. tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  143. except AttributeError:
  144. tools = [float(tooldia)]
  145. # store here the default data for Geometry Data
  146. default_data = {}
  147. default_data.update({
  148. "name": outname,
  149. "plot": False,
  150. "cutz": self.app.defaults["geometry_cutz"],
  151. "vtipdia": 0.1,
  152. "vtipangle": 30,
  153. "travelz": self.app.defaults["geometry_travelz"],
  154. "feedrate": self.app.defaults["geometry_feedrate"],
  155. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  156. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  157. "dwell": self.app.defaults["geometry_dwell"],
  158. "dwelltime": self.app.defaults["geometry_dwelltime"],
  159. "multidepth": self.app.defaults["geometry_multidepth"],
  160. "ppname_g": self.app.defaults["geometry_ppname_g"],
  161. "depthperpass": self.app.defaults["geometry_depthperpass"],
  162. "extracut": self.app.defaults["geometry_extracut"],
  163. "extracut_length": self.app.defaults["geometry_extracut_length"],
  164. "toolchange": self.app.defaults["geometry_toolchange"],
  165. "toolchangez": self.app.defaults["geometry_toolchangez"],
  166. "endz": self.app.defaults["geometry_endz"],
  167. "endxy": self.app.defaults["geometry_endxy"],
  168. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  169. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  170. "startz": self.app.defaults["geometry_startz"],
  171. "tooldia": self.app.defaults["tools_painttooldia"],
  172. "paintmargin": margin,
  173. "paintmethod": method,
  174. "selectmethod": select,
  175. "pathconnect": connect,
  176. "paintcontour": contour,
  177. "paintoverlap": overlap
  178. })
  179. paint_tools = {}
  180. tooluid = 0
  181. for tool in tools:
  182. tooluid += 1
  183. paint_tools.update({
  184. int(tooluid): {
  185. 'tooldia': float('%.*f' % (obj.decimals, tool)),
  186. 'offset': 'Path',
  187. 'offset_value': 0.0,
  188. 'type': 'Iso',
  189. 'tool_type': 'C1',
  190. 'data': dict(default_data),
  191. 'solid_geometry': []
  192. }
  193. })
  194. paint_tools[int(tooluid)]['data']['tooldia'] = float('%.*f' % (obj.decimals, tool))
  195. if obj is None:
  196. return "Object not found: %s" % name
  197. # Paint all polygons in the painted object
  198. if 'all' in args:
  199. self.app.paint_tool.paint_poly_all(obj=obj,
  200. tooldia=tooldia,
  201. order=order,
  202. method=method,
  203. outname=outname,
  204. tools_storage=paint_tools,
  205. plot=False,
  206. run_threaded=False)
  207. return
  208. # Paint single polygon in the painted object
  209. if 'single' in args:
  210. if 'x' not in args and 'y' not in args:
  211. self.raise_tcl_error('%s' % _("Expected -x <value> and -y <value>."))
  212. else:
  213. x = args['x']
  214. y = args['y']
  215. self.app.paint_tool.paint_poly(obj=obj,
  216. inside_pt=[x, y],
  217. tooldia=tooldia,
  218. order=order,
  219. method=method,
  220. outname=outname,
  221. tools_storage=paint_tools,
  222. plot=False,
  223. run_threaded=False)
  224. return
  225. # Paint all polygons found within the box object from the the painted object
  226. if 'box' in args:
  227. box_name = args['box']
  228. if box_name is None:
  229. self.raise_tcl_error('%s' % _("Expected -box <value>."))
  230. # Get box source object.
  231. try:
  232. box_obj = self.app.collection.get_by_name(str(box_name))
  233. except Exception as e:
  234. log.debug("TclCommandPaint.execute() --> %s" % str(e))
  235. self.raise_tcl_error("%s: %s" % (_("Could not retrieve box object"), name))
  236. return "Could not retrieve object: %s" % name
  237. self.app.paint_tool.paint_poly_ref(obj=obj,
  238. sel_obj=box_obj,
  239. tooldia=tooldia,
  240. order=order,
  241. method=method,
  242. outname=outname,
  243. tools_storage=paint_tools,
  244. plot=False,
  245. run_threaded=False)
  246. return
  247. self.raise_tcl_error("%s:" % _("None of the following args: 'box', 'single', 'all' were used.\n"
  248. "Paint failed."))
  249. return "None of the following args: 'box', 'single', 'all' were used. Paint failed."