TclCommandGeoCutout.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. from tclCommands.TclCommand import TclCommandSignaled
  2. from FlatCAMObj import FlatCAMGerber, FlatCAMGeometry
  3. import logging
  4. import collections
  5. from copy import deepcopy
  6. from shapely.ops import cascaded_union
  7. from shapely.geometry import Polygon, LineString, LinearRing
  8. log = logging.getLogger('base')
  9. class TclCommandGeoCutout(TclCommandSignaled):
  10. """
  11. Tcl shell command to create a board cutout geometry.
  12. Allow cutout for any shape.
  13. Cuts holding gaps from geometry.
  14. example:
  15. """
  16. # List of all command aliases, to be able use old
  17. # names for backward compatibility (add_poly, add_polygon)
  18. aliases = ['geocutout', 'geoc']
  19. description = '%s %s' % ("--", "Creates board cutout from an object (Gerber or Geometry) of any shape.")
  20. # Dictionary of types from Tcl command, needs to be ordered
  21. arg_names = collections.OrderedDict([
  22. ('name', str),
  23. ])
  24. # Dictionary of types from Tcl command, needs to be ordered,
  25. # this is for options like -optionname value
  26. option_types = collections.OrderedDict([
  27. ('dia', float),
  28. ('margin', float),
  29. ('gapsize', float),
  30. ('gaps', str),
  31. ('outname', str)
  32. ])
  33. # array of mandatory options for current Tcl command: required = {'name','outname'}
  34. required = ['name']
  35. # structured help for current command, args needs to be ordered
  36. help = {
  37. 'main': 'Creates board cutout from an object (Gerber or Geometry) of any shape.',
  38. 'args': collections.OrderedDict([
  39. ('name', 'Name of the object to be cutout. Required'),
  40. ('dia', 'Tool diameter.'),
  41. ('margin', 'Margin over bounds.'),
  42. ('gapsize', 'size of gap.'),
  43. ('gaps', "type of gaps. Can be: 'tb' = top-bottom, 'lr' = left-right, '2tb' = 2top-2bottom, "
  44. "'2lr' = 2left-2right, '4' = 4 cuts, '8' = 8 cuts"),
  45. ('outname', 'Name of the resulting Geometry object.'),
  46. ]),
  47. 'examples': [" #isolate margin for example from Fritzing arduino shield or any svg etc\n" +
  48. " isolate BCu_margin -dia 3 -overlap 1\n" +
  49. "\n" +
  50. " #create exteriors from isolated object\n" +
  51. " exteriors BCu_margin_iso -outname BCu_margin_iso_exterior\n" +
  52. "\n" +
  53. " #delete isolated object if you dond need id anymore\n" +
  54. " delete BCu_margin_iso\n" +
  55. "\n" +
  56. " #finally cut holding gaps\n" +
  57. " geocutout BCu_margin_iso_exterior -dia 3 -gapsize 0.6 -gaps 4 -outname cutout_geo\n"]
  58. }
  59. flat_geometry = []
  60. def execute(self, args, unnamed_args):
  61. """
  62. :param args:
  63. :param unnamed_args:
  64. :return:
  65. """
  66. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  67. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  68. # obj_.subtract_polygon(pts)
  69. def substract_rectangle_geo(geo, x0, y0, x1, y1):
  70. pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  71. def flatten(geometry=None, reset=True, pathonly=False):
  72. """
  73. Creates a list of non-iterable linear geometry objects.
  74. Polygons are expanded into its exterior and interiors if specified.
  75. Results are placed in flat_geometry
  76. :param geometry: Shapely type or list or list of list of such.
  77. :param reset: Clears the contents of self.flat_geometry.
  78. :param pathonly: Expands polygons into linear elements.
  79. """
  80. if reset:
  81. self.flat_geometry = []
  82. # If iterable, expand recursively.
  83. try:
  84. for geo_el in geometry:
  85. if geo_el is not None:
  86. flatten(geometry=geo_el,
  87. reset=False,
  88. pathonly=pathonly)
  89. # Not iterable, do the actual indexing and add.
  90. except TypeError:
  91. if pathonly and type(geometry) == Polygon:
  92. self.flat_geometry.append(geometry.exterior)
  93. flatten(geometry=geometry.interiors,
  94. reset=False,
  95. pathonly=True)
  96. else:
  97. self.flat_geometry.append(geometry)
  98. return self.flat_geometry
  99. flat_geometry = flatten(geo, pathonly=True)
  100. polygon = Polygon(pts)
  101. toolgeo = cascaded_union(polygon)
  102. diffs = []
  103. for target in flat_geometry:
  104. if type(target) == LineString or type(target) == LinearRing:
  105. diffs.append(target.difference(toolgeo))
  106. else:
  107. log.warning("Not implemented.")
  108. return cascaded_union(diffs)
  109. if 'name' in args:
  110. name = args['name']
  111. else:
  112. self.app.inform.emit(
  113. "[WARNING]The name of the object for which cutout is done is missing. Add it and retry.")
  114. return
  115. if 'margin' in args:
  116. margin = float(args['margin'])
  117. else:
  118. margin = float(self.app.defaults["tools_cutoutmargin"])
  119. if 'dia' in args:
  120. dia = float(args['dia'])
  121. else:
  122. dia = float(self.app.defaults["tools_cutouttooldia"])
  123. if 'gaps' in args:
  124. gaps = args['gaps']
  125. else:
  126. gaps = str(self.app.defaults["tools_gaps_ff"])
  127. if 'gapsize' in args:
  128. gapsize = float(args['gapsize'])
  129. else:
  130. gapsize = float(self.app.defaults["tools_cutoutgapsize"])
  131. if 'outname' in args:
  132. outname = args['outname']
  133. else:
  134. outname = str(name) + "_cutout"
  135. # Get source object.
  136. try:
  137. cutout_obj = self.app.collection.get_by_name(str(name))
  138. except Exception as e:
  139. log.debug("TclCommandGeoCutout --> %s" % str(e))
  140. return "Could not retrieve object: %s" % name
  141. if 0 in {dia}:
  142. self.app.inform.emit("[WARNING]Tool Diameter is zero value. Change it to a positive real number.")
  143. return "Tool Diameter is zero value. Change it to a positive real number."
  144. if gaps not in ['lr', 'tb', '2lr', '2tb', '4', '8']:
  145. self.app.inform.emit("[WARNING]Gaps value can be only one of: 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  146. "Fill in a correct value and retry. ")
  147. return
  148. # Get min and max data for each object as we just cut rectangles across X or Y
  149. xmin, ymin, xmax, ymax = cutout_obj.bounds()
  150. cutout_obj.options['xmin'] = xmin
  151. cutout_obj.options['ymin'] = ymin
  152. cutout_obj.options['xmax'] = xmax
  153. cutout_obj.options['ymax'] = ymax
  154. px = 0.5 * (xmin + xmax) + margin
  155. py = 0.5 * (ymin + ymax) + margin
  156. lenghtx = (xmax - xmin) + (margin * 2)
  157. lenghty = (ymax - ymin) + (margin * 2)
  158. gapsize = gapsize / 2 + (dia / 2)
  159. try:
  160. gaps_u = int(gaps)
  161. except ValueError:
  162. gaps_u = gaps
  163. if isinstance(cutout_obj, FlatCAMGeometry):
  164. # rename the obj name so it can be identified as cutout
  165. # cutout_obj.options["name"] += "_cutout"
  166. # if gaps_u == 8 or gaps_u == '2lr':
  167. # subtract_rectangle(cutout_obj,
  168. # xmin - gapsize, # botleft_x
  169. # py - gapsize + lenghty / 4, # botleft_y
  170. # xmax + gapsize, # topright_x
  171. # py + gapsize + lenghty / 4) # topright_y
  172. # subtract_rectangle(cutout_obj,
  173. # xmin - gapsize,
  174. # py - gapsize - lenghty / 4,
  175. # xmax + gapsize,
  176. # py + gapsize - lenghty / 4)
  177. #
  178. # if gaps_u == 8 or gaps_u == '2tb':
  179. # subtract_rectangle(cutout_obj,
  180. # px - gapsize + lenghtx / 4,
  181. # ymin - gapsize,
  182. # px + gapsize + lenghtx / 4,
  183. # ymax + gapsize)
  184. # subtract_rectangle(cutout_obj,
  185. # px - gapsize - lenghtx / 4,
  186. # ymin - gapsize,
  187. # px + gapsize - lenghtx / 4,
  188. # ymax + gapsize)
  189. #
  190. # if gaps_u == 4 or gaps_u == 'lr':
  191. # subtract_rectangle(cutout_obj,
  192. # xmin - gapsize,
  193. # py - gapsize,
  194. # xmax + gapsize,
  195. # py + gapsize)
  196. #
  197. # if gaps_u == 4 or gaps_u == 'tb':
  198. # subtract_rectangle(cutout_obj,
  199. # px - gapsize,
  200. # ymin - gapsize,
  201. # px + gapsize,
  202. # ymax + gapsize)
  203. def geo_init(geo_obj, app_obj):
  204. geo = deepcopy(cutout_obj.solid_geometry)
  205. if gaps_u == 8 or gaps_u == '2lr':
  206. geo = substract_rectangle_geo(geo,
  207. xmin - gapsize, # botleft_x
  208. py - gapsize + lenghty / 4, # botleft_y
  209. xmax + gapsize, # topright_x
  210. py + gapsize + lenghty / 4) # topright_y
  211. geo = substract_rectangle_geo(geo,
  212. xmin - gapsize,
  213. py - gapsize - lenghty / 4,
  214. xmax + gapsize,
  215. py + gapsize - lenghty / 4)
  216. if gaps_u == 8 or gaps_u == '2tb':
  217. geo = substract_rectangle_geo(geo,
  218. px - gapsize + lenghtx / 4,
  219. ymin - gapsize,
  220. px + gapsize + lenghtx / 4,
  221. ymax + gapsize)
  222. geo = substract_rectangle_geo(geo,
  223. px - gapsize - lenghtx / 4,
  224. ymin - gapsize,
  225. px + gapsize - lenghtx / 4,
  226. ymax + gapsize)
  227. if gaps_u == 4 or gaps_u == 'lr':
  228. geo = substract_rectangle_geo(geo,
  229. xmin - gapsize,
  230. py - gapsize,
  231. xmax + gapsize,
  232. py + gapsize)
  233. if gaps_u == 4 or gaps_u == 'tb':
  234. geo = substract_rectangle_geo(geo,
  235. px - gapsize,
  236. ymin - gapsize,
  237. px + gapsize,
  238. ymax + gapsize)
  239. geo_obj.solid_geometry = deepcopy(geo)
  240. geo_obj.options['xmin'] = cutout_obj.options['xmin']
  241. geo_obj.options['ymin'] = cutout_obj.options['ymin']
  242. geo_obj.options['xmax'] = cutout_obj.options['xmax']
  243. geo_obj.options['ymax'] = cutout_obj.options['ymax']
  244. app_obj.disable_plots(objects=[cutout_obj])
  245. app_obj.inform.emit("[success] Any-form Cutout operation finished.")
  246. self.app.new_object('geometry', outname, geo_init, plot=False)
  247. # cutout_obj.plot()
  248. # self.app.inform.emit("[success] Any-form Cutout operation finished.")
  249. # self.app.plots_updated.emit()
  250. elif isinstance(cutout_obj, FlatCAMGerber):
  251. def geo_init(geo_obj, app_obj):
  252. try:
  253. geo = cutout_obj.isolation_geometry((dia / 2), iso_type=0, corner=2, follow=None)
  254. except Exception as exc:
  255. log.debug("TclCommandGeoCutout.execute() --> %s" % str(exc))
  256. return 'fail'
  257. if gaps_u == 8 or gaps_u == '2lr':
  258. geo = substract_rectangle_geo(geo,
  259. xmin - gapsize, # botleft_x
  260. py - gapsize + lenghty / 4, # botleft_y
  261. xmax + gapsize, # topright_x
  262. py + gapsize + lenghty / 4) # topright_y
  263. geo = substract_rectangle_geo(geo,
  264. xmin - gapsize,
  265. py - gapsize - lenghty / 4,
  266. xmax + gapsize,
  267. py + gapsize - lenghty / 4)
  268. if gaps_u == 8 or gaps_u == '2tb':
  269. geo = substract_rectangle_geo(geo,
  270. px - gapsize + lenghtx / 4,
  271. ymin - gapsize,
  272. px + gapsize + lenghtx / 4,
  273. ymax + gapsize)
  274. geo = substract_rectangle_geo(geo,
  275. px - gapsize - lenghtx / 4,
  276. ymin - gapsize,
  277. px + gapsize - lenghtx / 4,
  278. ymax + gapsize)
  279. if gaps_u == 4 or gaps_u == 'lr':
  280. geo = substract_rectangle_geo(geo,
  281. xmin - gapsize,
  282. py - gapsize,
  283. xmax + gapsize,
  284. py + gapsize)
  285. if gaps_u == 4 or gaps_u == 'tb':
  286. geo = substract_rectangle_geo(geo,
  287. px - gapsize,
  288. ymin - gapsize,
  289. px + gapsize,
  290. ymax + gapsize)
  291. geo_obj.solid_geometry = deepcopy(geo)
  292. geo_obj.options['xmin'] = cutout_obj.options['xmin']
  293. geo_obj.options['ymin'] = cutout_obj.options['ymin']
  294. geo_obj.options['xmax'] = cutout_obj.options['xmax']
  295. geo_obj.options['ymax'] = cutout_obj.options['ymax']
  296. app_obj.inform.emit("[success] Any-form Cutout operation finished.")
  297. self.app.new_object('geometry', outname, geo_init, plot=False)
  298. cutout_obj = self.app.collection.get_by_name(outname)
  299. else:
  300. self.app.inform.emit("[ERROR]Cancelled. Object type is not supported.")
  301. return