ToolCutOut.py 19 KB

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