TclCommandPanelize.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. from tclCommands.TclCommand import TclCommand
  2. from FlatCAMObj import FlatCAMGeometry, FlatCAMExcellon
  3. import shapely.affinity as affinity
  4. import logging
  5. from copy import deepcopy
  6. import collections
  7. log = logging.getLogger('base')
  8. class TclCommandPanelize(TclCommand):
  9. """
  10. Tcl shell command to panelize an object.
  11. example:
  12. """
  13. # List of all command aliases, to be able use old names for backward compatibility (add_poly, add_polygon)
  14. aliases = ['panelize', 'pan', 'panel']
  15. description = '%s %s' % ("--", "Create a new object with an array of duplicates of the original geometry, "
  16. "arranged in a grid.")
  17. # Dictionary of types from Tcl command, needs to be ordered
  18. arg_names = collections.OrderedDict([
  19. ('name', str),
  20. ])
  21. # Dictionary of types from Tcl command, needs to be ordered , this is for options like -optionname value
  22. option_types = collections.OrderedDict([
  23. ('rows', int),
  24. ('columns', int),
  25. ('spacing_columns', float),
  26. ('spacing_rows', float),
  27. ('box', str),
  28. ('outname', str),
  29. ('use_thread', str)
  30. ])
  31. # array of mandatory options for current Tcl command: required = {'name','outname'}
  32. required = ['name']
  33. # structured help for current command, args needs to be ordered
  34. help = {
  35. 'main': 'Create a new object with an array of duplicates of the original geometry, arranged in a grid.',
  36. 'args': collections.OrderedDict([
  37. ('name', 'Name of the object to panelize.'),
  38. ('box', 'Name of object which acts as box (cutout for example.)'
  39. 'for cutout boundary. Object from name is used if not specified.'),
  40. ('spacing_columns', 'Spacing between columns.'),
  41. ('spacing_rows', 'Spacing between rows.'),
  42. ('columns', 'Number of columns.'),
  43. ('rows', 'Number of rows;'),
  44. ('outname', 'Name of the new geometry object.'),
  45. ('use_thread', 'False (0) = non-threaded execution or True (1) = threaded execution')
  46. ]),
  47. 'examples': [
  48. 'panelize obj_name',
  49. 'panel obj_name -rows 2 -columns 2 -spacing_columns 0.4 -spacing_rows 1.3 -box box_obj_name '
  50. '-outname panelized_name',
  51. 'panel obj_name -columns 2 -box box_obj_name -outname panelized_name',
  52. ]
  53. }
  54. def execute(self, args, unnamed_args):
  55. """
  56. :param args:
  57. :param unnamed_args:
  58. :return:
  59. """
  60. name = args['name']
  61. # Get source object.
  62. try:
  63. obj = self.app.collection.get_by_name(str(name))
  64. except Exception:
  65. return "Could not retrieve object: %s" % name
  66. if obj is None:
  67. return "Object not found: %s" % name
  68. if 'box' in args:
  69. boxname = args['box']
  70. try:
  71. box = self.app.collection.get_by_name(boxname)
  72. except Exception:
  73. return "Could not retrieve object: %s" % name
  74. else:
  75. box = obj
  76. if 'columns' in args:
  77. columns = int(args['columns'])
  78. else:
  79. columns = int(0)
  80. if 'rows' in args:
  81. rows = int(args['rows'])
  82. else:
  83. rows = int(0)
  84. if 'columns' not in args and 'rows' not in args:
  85. return "ERROR: Specify either -columns or -rows. The one not specified it will assumed to be 0"
  86. if 'outname' in args:
  87. outname = args['outname']
  88. else:
  89. outname = name + '_panelized'
  90. if 'use_thread' in args:
  91. try:
  92. par = args['use_thread'].capitalize()
  93. except AttributeError:
  94. par = args['use_thread']
  95. threaded = bool(eval(par))
  96. else:
  97. threaded = False
  98. if 'spacing_columns' in args:
  99. spacing_columns = int(args['spacing_columns'])
  100. else:
  101. spacing_columns = 5
  102. if 'spacing_rows' in args:
  103. spacing_rows = int(args['spacing_rows'])
  104. else:
  105. spacing_rows = 5
  106. xmin, ymin, xmax, ymax = box.bounds()
  107. lenghtx = xmax - xmin + spacing_columns
  108. lenghty = ymax - ymin + spacing_rows
  109. # def panelize():
  110. # currenty = 0
  111. #
  112. # def initialize_local(obj_init, app):
  113. # obj_init.solid_geometry = obj.solid_geometry
  114. # obj_init.offset([float(currentx), float(currenty)])
  115. # objs.append(obj_init)
  116. #
  117. # def initialize_local_excellon(obj_init, app):
  118. # obj_init.tools = obj.tools
  119. # # drills are offset, so they need to be deep copied
  120. # obj_init.drills = deepcopy(obj.drills)
  121. # obj_init.offset([float(currentx), float(currenty)])
  122. # obj_init.create_geometry()
  123. # objs.append(obj_init)
  124. #
  125. # def initialize_geometry(obj_init, app):
  126. # FlatCAMGeometry.merge(objs, obj_init)
  127. #
  128. # def initialize_excellon(obj_init, app):
  129. # # merge expects tools to exist in the target object
  130. # obj_init.tools = obj.tools.copy()
  131. # FlatCAMExcellon.merge(objs, obj_init)
  132. #
  133. # objs = []
  134. # if obj is not None:
  135. #
  136. # for row in range(rows):
  137. # currentx = 0
  138. # for col in range(columns):
  139. # local_outname = outname + ".tmp." + str(col) + "." + str(row)
  140. # if isinstance(obj, FlatCAMExcellon):
  141. # self.app.new_object("excellon", local_outname, initialize_local_excellon, plot=False,
  142. # autoselected=False)
  143. # else:
  144. # self.app.new_object("geometry", local_outname, initialize_local, plot=False,
  145. # autoselected=False)
  146. #
  147. # currentx += lenghtx
  148. # currenty += lenghty
  149. #
  150. # if isinstance(obj, FlatCAMExcellon):
  151. # self.app.new_object("excellon", outname, initialize_excellon)
  152. # else:
  153. # self.app.new_object("geometry", outname, initialize_geometry)
  154. #
  155. # # deselect all to avoid delete selected object when run delete from shell
  156. # self.app.collection.set_all_inactive()
  157. # for delobj in objs:
  158. # self.app.collection.set_active(delobj.options['name'])
  159. # self.app.on_delete()
  160. # else:
  161. # return "fail"
  162. #
  163. # ret_value = panelize()
  164. # if ret_value == 'fail':
  165. # return 'fail'
  166. def panelize_2():
  167. if obj is not None:
  168. self.app.inform.emit("Generating panel ... Please wait.")
  169. def job_init_excellon(obj_fin, app_obj):
  170. currenty = 0.0
  171. obj_fin.tools = obj.tools.copy()
  172. obj_fin.drills = []
  173. obj_fin.slots = []
  174. obj_fin.solid_geometry = []
  175. for option in obj.options:
  176. if option != 'name':
  177. try:
  178. obj_fin.options[option] = obj.options[option]
  179. except Exception as e:
  180. log.warning("Failed to copy option: %s" % str(option))
  181. log.debug("TclCommandPanelize.execute().panelize2() --> %s" % str(e))
  182. for row in range(rows):
  183. currentx = 0.0
  184. for col in range(columns):
  185. if obj.drills:
  186. for tool_dict in obj.drills:
  187. point_offseted = affinity.translate(tool_dict['point'], currentx, currenty)
  188. obj_fin.drills.append(
  189. {
  190. "point": point_offseted,
  191. "tool": tool_dict['tool']
  192. }
  193. )
  194. if obj.slots:
  195. for tool_dict in obj.slots:
  196. start_offseted = affinity.translate(tool_dict['start'], currentx, currenty)
  197. stop_offseted = affinity.translate(tool_dict['stop'], currentx, currenty)
  198. obj_fin.slots.append(
  199. {
  200. "start": start_offseted,
  201. "stop": stop_offseted,
  202. "tool": tool_dict['tool']
  203. }
  204. )
  205. currentx += lenghtx
  206. currenty += lenghty
  207. obj_fin.create_geometry()
  208. obj_fin.zeros = obj.zeros
  209. obj_fin.units = obj.units
  210. def job_init_geometry(obj_fin, app_obj):
  211. currentx = 0.0
  212. currenty = 0.0
  213. def translate_recursion(geom):
  214. if type(geom) == list:
  215. geoms = []
  216. for local_geom in geom:
  217. geoms.append(translate_recursion(local_geom))
  218. return geoms
  219. else:
  220. return affinity.translate(geom, xoff=currentx, yoff=currenty)
  221. obj_fin.solid_geometry = []
  222. if isinstance(obj, FlatCAMGeometry):
  223. obj_fin.multigeo = obj.multigeo
  224. obj_fin.tools = deepcopy(obj.tools)
  225. if obj.multigeo is True:
  226. for tool in obj.tools:
  227. obj_fin.tools[tool]['solid_geometry'][:] = []
  228. for row in range(rows):
  229. currentx = 0.0
  230. for col in range(columns):
  231. if isinstance(obj, FlatCAMGeometry):
  232. if obj.multigeo is True:
  233. for tool in obj.tools:
  234. obj_fin.tools[tool]['solid_geometry'].append(translate_recursion(
  235. obj.tools[tool]['solid_geometry'])
  236. )
  237. else:
  238. obj_fin.solid_geometry.append(
  239. translate_recursion(obj.solid_geometry)
  240. )
  241. else:
  242. obj_fin.solid_geometry.append(
  243. translate_recursion(obj.solid_geometry)
  244. )
  245. currentx += lenghtx
  246. currenty += lenghty
  247. if isinstance(obj, FlatCAMExcellon):
  248. self.app.new_object("excellon", outname, job_init_excellon, plot=False, autoselected=True)
  249. else:
  250. self.app.new_object("geometry", outname, job_init_geometry, plot=False, autoselected=True)
  251. if threaded is True:
  252. proc = self.app.proc_container.new("Generating panel ... Please wait.")
  253. def job_thread(app_obj):
  254. try:
  255. panelize_2()
  256. self.app.inform.emit("[success] Panel created successfully.")
  257. except Exception as ee:
  258. proc.done()
  259. log.debug(str(ee))
  260. return
  261. proc.done()
  262. self.app.collection.promise(outname)
  263. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  264. else:
  265. panelize_2()
  266. self.app.inform.emit("[success] Panel created successfully.")