TclCommandGeoCutout.py 15 KB

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