ToolCutOut.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. from FlatCAMTool import FlatCAMTool
  2. from copy import copy,deepcopy
  3. from ObjectCollection import *
  4. from FlatCAMApp import *
  5. from PyQt5 import QtGui, QtCore, QtWidgets
  6. from GUIElements import IntEntry, RadioSet, LengthEntry
  7. from FlatCAMObj import FlatCAMGeometry, FlatCAMExcellon, FlatCAMGerber
  8. class ToolCutOut(FlatCAMTool):
  9. toolName = "Cutout PCB"
  10. def __init__(self, app):
  11. FlatCAMTool.__init__(self, app)
  12. ## Title
  13. title_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % self.toolName)
  14. self.layout.addWidget(title_label)
  15. ## Form Layout
  16. form_layout = QtWidgets.QFormLayout()
  17. self.layout.addLayout(form_layout)
  18. ## Type of object to be cutout
  19. self.type_obj_combo = QtWidgets.QComboBox()
  20. self.type_obj_combo.addItem("Gerber")
  21. self.type_obj_combo.addItem("Excellon")
  22. self.type_obj_combo.addItem("Geometry")
  23. # we get rid of item1 ("Excellon") as it is not suitable for creating film
  24. self.type_obj_combo.view().setRowHidden(1, True)
  25. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  26. # self.type_obj_combo.setItemIcon(1, QtGui.QIcon("share/drill16.png"))
  27. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  28. self.type_obj_combo_label = QtWidgets.QLabel("Object Type:")
  29. self.type_obj_combo_label.setToolTip(
  30. "Specify the type of object to be cutout.\n"
  31. "It can be of type: Gerber or Geometry.\n"
  32. "What is selected here will dictate the kind\n"
  33. "of objects that will populate the 'Object' combobox."
  34. )
  35. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  36. ## Object to be cutout
  37. self.obj_combo = QtWidgets.QComboBox()
  38. self.obj_combo.setModel(self.app.collection)
  39. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  40. self.object_label = QtWidgets.QLabel("Object:")
  41. self.object_label.setToolTip(
  42. "Object to be cutout. "
  43. )
  44. form_layout.addRow(self.object_label, self.obj_combo)
  45. # Tool Diameter
  46. self.dia = FCEntry()
  47. self.dia_label = QtWidgets.QLabel("Tool Dia:")
  48. self.dia_label.setToolTip(
  49. "Diameter of the tool used to cutout\n"
  50. "the PCB shape out of the surrounding material."
  51. )
  52. form_layout.addRow(self.dia_label, self.dia)
  53. # Margin
  54. self.margin = FCEntry()
  55. self.margin_label = QtWidgets.QLabel("Margin:")
  56. self.margin_label.setToolTip(
  57. "Margin over bounds. A positive value here\n"
  58. "will make the cutout of the PCB further from\n"
  59. "the actual PCB border"
  60. )
  61. form_layout.addRow(self.margin_label, self.margin)
  62. # Gapsize
  63. self.gapsize = FCEntry()
  64. self.gapsize_label = QtWidgets.QLabel("Gap size:")
  65. self.gapsize_label.setToolTip(
  66. "The size of the gaps in the cutout\n"
  67. "used to keep the board connected to\n"
  68. "the surrounding material (the one \n"
  69. "from which the PCB is cutout)."
  70. )
  71. form_layout.addRow(self.gapsize_label, self.gapsize)
  72. ## Title2
  73. title_ff_label = QtWidgets.QLabel("<font size=4><b>FreeForm Cutout</b></font>")
  74. self.layout.addWidget(title_ff_label)
  75. ## Form Layout
  76. form_layout_2 = QtWidgets.QFormLayout()
  77. self.layout.addLayout(form_layout_2)
  78. # How gaps wil be rendered:
  79. # lr - left + right
  80. # tb - top + bottom
  81. # 4 - left + right +top + bottom
  82. # 2lr - 2*left + 2*right
  83. # 2tb - 2*top + 2*bottom
  84. # 8 - 2*left + 2*right +2*top + 2*bottom
  85. # Gaps
  86. gaps_ff_label = QtWidgets.QLabel('Gaps FF: ')
  87. gaps_ff_label.setToolTip(
  88. "Number of gaps used for the FreeForm cutout.\n"
  89. "There can be maximum 8 bridges/gaps.\n"
  90. "The choices are:\n"
  91. "- lr - left + right\n"
  92. "- tb - top + bottom\n"
  93. "- 4 - left + right +top + bottom\n"
  94. "- 2lr - 2*left + 2*right\n"
  95. "- 2tb - 2*top + 2*bottom\n"
  96. "- 8 - 2*left + 2*right +2*top + 2*bottom"
  97. )
  98. self.gaps = FCComboBox()
  99. gaps_items = ['LR', 'TB', '4', '2LR', '2TB', '8']
  100. for it in gaps_items:
  101. self.gaps.addItem(it)
  102. self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  103. form_layout_2.addRow(gaps_ff_label, self.gaps)
  104. ## Buttons
  105. hlay = QtWidgets.QHBoxLayout()
  106. self.layout.addLayout(hlay)
  107. hlay.addStretch()
  108. self.ff_cutout_object_btn = QtWidgets.QPushButton(" FreeForm Cutout Object ")
  109. self.ff_cutout_object_btn.setToolTip(
  110. "Cutout the selected object.\n"
  111. "The cutout shape can be any shape.\n"
  112. "Useful when the PCB has a non-rectangular shape.\n"
  113. "But if the object to be cutout is of Gerber Type,\n"
  114. "it needs to be an outline of the actual board shape."
  115. )
  116. hlay.addWidget(self.ff_cutout_object_btn)
  117. ## Title3
  118. title_rct_label = QtWidgets.QLabel("<font size=4><b>Rectangular Cutout</b></font>")
  119. self.layout.addWidget(title_rct_label)
  120. ## Form Layout
  121. form_layout_3 = QtWidgets.QFormLayout()
  122. self.layout.addLayout(form_layout_3)
  123. gapslabel_rect = QtWidgets.QLabel('Type of gaps:')
  124. gapslabel_rect.setToolTip(
  125. "Where to place the gaps:\n"
  126. "- one gap Top / one gap Bottom\n"
  127. "- one gap Left / one gap Right\n"
  128. "- one gap on each of the 4 sides."
  129. )
  130. self.gaps_rect_radio = RadioSet([{'label': '2(T/B)', 'value': 'tb'},
  131. {'label': '2(L/R)', 'value': 'lr'},
  132. {'label': '4', 'value': '4'}])
  133. form_layout_3.addRow(gapslabel_rect, self.gaps_rect_radio)
  134. hlay2 = QtWidgets.QHBoxLayout()
  135. self.layout.addLayout(hlay2)
  136. hlay2.addStretch()
  137. self.rect_cutout_object_btn = QtWidgets.QPushButton("Rectangular Cutout Object")
  138. self.rect_cutout_object_btn.setToolTip(
  139. "Cutout the selected object.\n"
  140. "The resulting cutout shape is\n"
  141. "always of a rectangle form and it will be\n"
  142. "the bounding box of the Object."
  143. )
  144. hlay2.addWidget(self.rect_cutout_object_btn)
  145. self.layout.addStretch()
  146. ## Init GUI
  147. # self.dia.set_value(1)
  148. # self.margin.set_value(0)
  149. # self.gapsize.set_value(1)
  150. # self.gaps.set_value(4)
  151. # self.gaps_rect_radio.set_value("4")
  152. ## Signals
  153. self.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  154. self.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  155. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  156. def on_type_obj_index_changed(self, index):
  157. obj_type = self.type_obj_combo.currentIndex()
  158. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  159. self.obj_combo.setCurrentIndex(0)
  160. def run(self):
  161. FlatCAMTool.run(self)
  162. self.set_tool_ui()
  163. self.app.ui.notebook.setTabText(2, "Cutout Tool")
  164. def install(self, icon=None, separator=None, **kwargs):
  165. FlatCAMTool.install(self, icon, separator, shortcut='ALT+U', **kwargs)
  166. def set_tool_ui(self):
  167. self.reset_fields()
  168. self.obj_combo.setCurrentIndex(1)
  169. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  170. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  171. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  172. self.gaps.set_value(4)
  173. self.gaps_rect_radio.set_value(str(self.app.defaults["tools_gaps_rect"]))
  174. def on_freeform_cutout(self):
  175. def subtract_rectangle(obj_, x0, y0, x1, y1):
  176. pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  177. obj_.subtract_polygon(pts)
  178. name = self.obj_combo.currentText()
  179. # Get source object.
  180. try:
  181. cutout_obj = self.app.collection.get_by_name(str(name))
  182. except:
  183. self.app.inform.emit("[error_notcl]Could not retrieve object: %s" % name)
  184. return "Could not retrieve object: %s" % name
  185. if cutout_obj is None:
  186. self.app.inform.emit("[error_notcl]There is no object selected for Cutout.\nSelect one and try again.")
  187. return
  188. try:
  189. dia = float(self.dia.get_value())
  190. except ValueError:
  191. # try to convert comma to decimal point. if it's still not working error message and return
  192. try:
  193. dia = float(self.dia.get_value().replace(',', '.'))
  194. except ValueError:
  195. self.app.inform.emit("[warning_notcl] Tool diameter value is missing or wrong format. "
  196. "Add it and retry.")
  197. return
  198. try:
  199. margin = float(self.margin.get_value())
  200. except ValueError:
  201. # try to convert comma to decimal point. if it's still not working error message and return
  202. try:
  203. margin = float(self.margin.get_value().replace(',', '.'))
  204. except ValueError:
  205. self.app.inform.emit("[warning_notcl] Margin value is missing or wrong format. "
  206. "Add it and retry.")
  207. return
  208. try:
  209. gapsize = float(self.gapsize.get_value())
  210. except ValueError:
  211. # try to convert comma to decimal point. if it's still not working error message and return
  212. try:
  213. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  214. except ValueError:
  215. self.app.inform.emit("[warning_notcl] Gap size value is missing or wrong format. "
  216. "Add it and retry.")
  217. return
  218. try:
  219. gaps = self.gaps.get_value()
  220. except TypeError:
  221. self.app.inform.emit("[warning_notcl] Number of gaps value is missing. Add it and retry.")
  222. return
  223. if 0 in {dia}:
  224. self.app.inform.emit("[warning_notcl]Tool Diameter is zero value. Change it to a positive integer.")
  225. return "Tool Diameter is zero value. Change it to a positive integer."
  226. if gaps not in ['lr', 'tb', '2lr', '2tb', '4', '8']:
  227. self.app.inform.emit("[warning_notcl] Gaps value can be only one of: 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  228. "Fill in a correct value and retry. ")
  229. return
  230. if cutout_obj.multigeo is True:
  231. self.app.inform.emit("[error]Cutout operation cannot be done on a multi-geo Geometry.\n"
  232. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  233. "and after that perform Cutout.")
  234. return
  235. # Get min and max data for each object as we just cut rectangles across X or Y
  236. xmin, ymin, xmax, ymax = cutout_obj.bounds()
  237. px = 0.5 * (xmin + xmax) + margin
  238. py = 0.5 * (ymin + ymax) + margin
  239. lenghtx = (xmax - xmin) + (margin * 2)
  240. lenghty = (ymax - ymin) + (margin * 2)
  241. gapsize = gapsize / 2 + (dia / 2)
  242. if isinstance(cutout_obj,FlatCAMGeometry):
  243. # rename the obj name so it can be identified as cutout
  244. cutout_obj.options["name"] += "_cutout"
  245. else:
  246. cutout_obj.isolate(dia=dia, passes=1, overlap=1, combine=False, outname="_temp")
  247. ext_obj = self.app.collection.get_by_name("_temp")
  248. def geo_init(geo_obj, app_obj):
  249. geo_obj.solid_geometry = obj_exteriors
  250. outname = cutout_obj.options["name"] + "_cutout"
  251. obj_exteriors = ext_obj.get_exteriors()
  252. self.app.new_object('geometry', outname, geo_init)
  253. self.app.collection.set_all_inactive()
  254. self.app.collection.set_active("_temp")
  255. self.app.on_delete()
  256. cutout_obj = self.app.collection.get_by_name(outname)
  257. if int(gaps) == 8 or gaps == '2lr':
  258. subtract_rectangle(cutout_obj,
  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. subtract_rectangle(cutout_obj,
  264. xmin - gapsize,
  265. py - gapsize - lenghty / 4,
  266. xmax + gapsize,
  267. py + gapsize - lenghty / 4)
  268. if int(gaps) == 8 or gaps == '2tb':
  269. subtract_rectangle(cutout_obj,
  270. px - gapsize + lenghtx / 4,
  271. ymin - gapsize,
  272. px + gapsize + lenghtx / 4,
  273. ymax + gapsize)
  274. subtract_rectangle(cutout_obj,
  275. px - gapsize - lenghtx / 4,
  276. ymin - gapsize,
  277. px + gapsize - lenghtx / 4,
  278. ymax + gapsize)
  279. if int(gaps) == 4 or gaps == 'lr':
  280. subtract_rectangle(cutout_obj,
  281. xmin - gapsize,
  282. py - gapsize,
  283. xmax + gapsize,
  284. py + gapsize)
  285. if int(gaps) == 4 or gaps == 'tb':
  286. subtract_rectangle(cutout_obj,
  287. px - gapsize,
  288. ymin - gapsize,
  289. px + gapsize,
  290. ymax + gapsize)
  291. cutout_obj.plot()
  292. self.app.inform.emit("[success] Any form CutOut operation finished.")
  293. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  294. def on_rectangular_cutout(self):
  295. name = self.obj_combo.currentText()
  296. # Get source object.
  297. try:
  298. cutout_obj = self.app.collection.get_by_name(str(name))
  299. except:
  300. self.app.inform.emit("[error_notcl]Could not retrieve object: %s" % name)
  301. return "Could not retrieve object: %s" % name
  302. if cutout_obj is None:
  303. self.app.inform.emit("[error_notcl]Object not found: %s" % cutout_obj)
  304. try:
  305. dia = float(self.dia.get_value())
  306. except ValueError:
  307. # try to convert comma to decimal point. if it's still not working error message and return
  308. try:
  309. dia = float(self.dia.get_value().replace(',', '.'))
  310. except ValueError:
  311. self.app.inform.emit("[warning_notcl] Tool diameter value is missing or wrong format. "
  312. "Add it and retry.")
  313. return
  314. try:
  315. margin = float(self.margin.get_value())
  316. except ValueError:
  317. # try to convert comma to decimal point. if it's still not working error message and return
  318. try:
  319. margin = float(self.margin.get_value().replace(',', '.'))
  320. except ValueError:
  321. self.app.inform.emit("[warning_notcl] Margin value is missing or wrong format. "
  322. "Add it and retry.")
  323. return
  324. try:
  325. gapsize = float(self.gapsize.get_value())
  326. except ValueError:
  327. # try to convert comma to decimal point. if it's still not working error message and return
  328. try:
  329. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  330. except ValueError:
  331. self.app.inform.emit("[warning_notcl] Gap size value is missing or wrong format. "
  332. "Add it and retry.")
  333. return
  334. try:
  335. gaps = self.gaps_rect_radio.get_value()
  336. except TypeError:
  337. self.app.inform.emit("[warning_notcl] Number of gaps value is missing. Add it and retry.")
  338. return
  339. if 0 in {dia}:
  340. self.app.inform.emit("[error_notcl]Tool Diameter is zero value. Change it to a positive integer.")
  341. return "Tool Diameter is zero value. Change it to a positive integer."
  342. if cutout_obj.multigeo is True:
  343. self.app.inform.emit("[error]Cutout operation cannot be done on a multi-geo Geometry.\n"
  344. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  345. "and after that perform Cutout.")
  346. return
  347. def geo_init(geo_obj, app_obj):
  348. real_margin = margin + (dia / 2)
  349. real_gap_size = gapsize + dia
  350. minx, miny, maxx, maxy = cutout_obj.bounds()
  351. minx -= real_margin
  352. maxx += real_margin
  353. miny -= real_margin
  354. maxy += real_margin
  355. midx = 0.5 * (minx + maxx)
  356. midy = 0.5 * (miny + maxy)
  357. hgap = 0.5 * real_gap_size
  358. pts = [[midx - hgap, maxy],
  359. [minx, maxy],
  360. [minx, midy + hgap],
  361. [minx, midy - hgap],
  362. [minx, miny],
  363. [midx - hgap, miny],
  364. [midx + hgap, miny],
  365. [maxx, miny],
  366. [maxx, midy - hgap],
  367. [maxx, midy + hgap],
  368. [maxx, maxy],
  369. [midx + hgap, maxy]]
  370. cases = {"tb": [[pts[0], pts[1], pts[4], pts[5]],
  371. [pts[6], pts[7], pts[10], pts[11]]],
  372. "lr": [[pts[9], pts[10], pts[1], pts[2]],
  373. [pts[3], pts[4], pts[7], pts[8]]],
  374. "4": [[pts[0], pts[1], pts[2]],
  375. [pts[3], pts[4], pts[5]],
  376. [pts[6], pts[7], pts[8]],
  377. [pts[9], pts[10], pts[11]]]}
  378. cuts = cases[gaps]
  379. geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
  380. # TODO: Check for None
  381. self.app.new_object("geometry", name + "_cutout", geo_init)
  382. self.app.inform.emit("[success] Rectangular CutOut operation finished.")
  383. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  384. def reset_fields(self):
  385. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))