TclCommandPanelize.py 12 KB

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