TclCommandGeoCutout.py 16 KB

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