ToolCutOut.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. FlatCAMTool.run(self)
  167. self.set_tool_ui()
  168. # if the splitter us hidden, display it
  169. if self.app.ui.splitter.sizes()[0] == 0:
  170. self.app.ui.splitter.setSizes([1, 1])
  171. self.app.ui.notebook.setTabText(2, "Cutout Tool")
  172. def install(self, icon=None, separator=None, **kwargs):
  173. FlatCAMTool.install(self, icon, separator, shortcut='ALT+U', **kwargs)
  174. def set_tool_ui(self):
  175. self.reset_fields()
  176. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  177. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  178. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  179. self.gaps.set_value(4)
  180. self.gaps_rect_radio.set_value(str(self.app.defaults["tools_gaps_rect"]))
  181. def on_freeform_cutout(self):
  182. def subtract_rectangle(obj_, x0, y0, x1, y1):
  183. pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  184. obj_.subtract_polygon(pts)
  185. name = self.obj_combo.currentText()
  186. # Get source object.
  187. try:
  188. cutout_obj = self.app.collection.get_by_name(str(name))
  189. except:
  190. self.app.inform.emit("[ERROR_NOTCL]Could not retrieve object: %s" % name)
  191. return "Could not retrieve object: %s" % name
  192. if cutout_obj is None:
  193. self.app.inform.emit("[ERROR_NOTCL]There is no object selected for Cutout.\nSelect one and try again.")
  194. return
  195. try:
  196. dia = float(self.dia.get_value())
  197. except ValueError:
  198. # try to convert comma to decimal point. if it's still not working error message and return
  199. try:
  200. dia = float(self.dia.get_value().replace(',', '.'))
  201. except ValueError:
  202. self.app.inform.emit("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  203. "Add it and retry.")
  204. return
  205. try:
  206. margin = float(self.margin.get_value())
  207. except ValueError:
  208. # try to convert comma to decimal point. if it's still not working error message and return
  209. try:
  210. margin = float(self.margin.get_value().replace(',', '.'))
  211. except ValueError:
  212. self.app.inform.emit("[WARNING_NOTCL] Margin value is missing or wrong format. "
  213. "Add it and retry.")
  214. return
  215. try:
  216. gapsize = float(self.gapsize.get_value())
  217. except ValueError:
  218. # try to convert comma to decimal point. if it's still not working error message and return
  219. try:
  220. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  221. except ValueError:
  222. self.app.inform.emit("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  223. "Add it and retry.")
  224. return
  225. try:
  226. gaps = self.gaps.get_value()
  227. except TypeError:
  228. self.app.inform.emit("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry.")
  229. return
  230. if 0 in {dia}:
  231. self.app.inform.emit("[WARNING_NOTCL]Tool Diameter is zero value. Change it to a positive integer.")
  232. return "Tool Diameter is zero value. Change it to a positive integer."
  233. if gaps not in ['LR', 'TB', '2LR', '2TB', '4', '8']:
  234. self.app.inform.emit("[WARNING_NOTCL] Gaps value can be only one of: 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  235. "Fill in a correct value and retry. ")
  236. return
  237. if cutout_obj.multigeo is True:
  238. self.app.inform.emit("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  239. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  240. "and after that perform Cutout.")
  241. return
  242. # Get min and max data for each object as we just cut rectangles across X or Y
  243. xmin, ymin, xmax, ymax = cutout_obj.bounds()
  244. px = 0.5 * (xmin + xmax) + margin
  245. py = 0.5 * (ymin + ymax) + margin
  246. lenghtx = (xmax - xmin) + (margin * 2)
  247. lenghty = (ymax - ymin) + (margin * 2)
  248. gapsize = gapsize / 2 + (dia / 2)
  249. if isinstance(cutout_obj,FlatCAMGeometry):
  250. # rename the obj name so it can be identified as cutout
  251. cutout_obj.options["name"] += "_cutout"
  252. else:
  253. cutout_obj.isolate(dia=dia, passes=1, overlap=1, combine=False, outname="_temp")
  254. ext_obj = self.app.collection.get_by_name("_temp")
  255. def geo_init(geo_obj, app_obj):
  256. geo_obj.solid_geometry = obj_exteriors
  257. outname = cutout_obj.options["name"] + "_cutout"
  258. obj_exteriors = ext_obj.get_exteriors()
  259. self.app.new_object('geometry', outname, geo_init)
  260. self.app.collection.set_all_inactive()
  261. self.app.collection.set_active("_temp")
  262. self.app.on_delete()
  263. cutout_obj = self.app.collection.get_by_name(outname)
  264. if gaps == '8' or gaps == '2LR':
  265. subtract_rectangle(cutout_obj,
  266. xmin - gapsize, # botleft_x
  267. py - gapsize + lenghty / 4, # botleft_y
  268. xmax + gapsize, # topright_x
  269. py + gapsize + lenghty / 4) # topright_y
  270. subtract_rectangle(cutout_obj,
  271. xmin - gapsize,
  272. py - gapsize - lenghty / 4,
  273. xmax + gapsize,
  274. py + gapsize - lenghty / 4)
  275. if gaps == '8' or gaps == '2TB':
  276. subtract_rectangle(cutout_obj,
  277. px - gapsize + lenghtx / 4,
  278. ymin - gapsize,
  279. px + gapsize + lenghtx / 4,
  280. ymax + gapsize)
  281. subtract_rectangle(cutout_obj,
  282. px - gapsize - lenghtx / 4,
  283. ymin - gapsize,
  284. px + gapsize - lenghtx / 4,
  285. ymax + gapsize)
  286. if gaps == '4' or gaps == 'LR':
  287. subtract_rectangle(cutout_obj,
  288. xmin - gapsize,
  289. py - gapsize,
  290. xmax + gapsize,
  291. py + gapsize)
  292. if gaps == '4' or gaps == 'TB':
  293. subtract_rectangle(cutout_obj,
  294. px - gapsize,
  295. ymin - gapsize,
  296. px + gapsize,
  297. ymax + gapsize)
  298. cutout_obj.plot()
  299. self.app.inform.emit("[success] Any form CutOut operation finished.")
  300. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  301. self.app.should_we_save = True
  302. def on_rectangular_cutout(self):
  303. name = self.obj_combo.currentText()
  304. # Get source object.
  305. try:
  306. cutout_obj = self.app.collection.get_by_name(str(name))
  307. except:
  308. self.app.inform.emit("[ERROR_NOTCL]Could not retrieve object: %s" % name)
  309. return "Could not retrieve object: %s" % name
  310. if cutout_obj is None:
  311. self.app.inform.emit("[ERROR_NOTCL]Object not found: %s" % cutout_obj)
  312. try:
  313. dia = float(self.dia.get_value())
  314. except ValueError:
  315. # try to convert comma to decimal point. if it's still not working error message and return
  316. try:
  317. dia = float(self.dia.get_value().replace(',', '.'))
  318. except ValueError:
  319. self.app.inform.emit("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  320. "Add it and retry.")
  321. return
  322. try:
  323. margin = float(self.margin.get_value())
  324. except ValueError:
  325. # try to convert comma to decimal point. if it's still not working error message and return
  326. try:
  327. margin = float(self.margin.get_value().replace(',', '.'))
  328. except ValueError:
  329. self.app.inform.emit("[WARNING_NOTCL] Margin value is missing or wrong format. "
  330. "Add it and retry.")
  331. return
  332. try:
  333. gapsize = float(self.gapsize.get_value())
  334. except ValueError:
  335. # try to convert comma to decimal point. if it's still not working error message and return
  336. try:
  337. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  338. except ValueError:
  339. self.app.inform.emit("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  340. "Add it and retry.")
  341. return
  342. try:
  343. gaps = self.gaps_rect_radio.get_value()
  344. except TypeError:
  345. self.app.inform.emit("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry.")
  346. return
  347. if 0 in {dia}:
  348. self.app.inform.emit("[ERROR_NOTCL]Tool Diameter is zero value. Change it to a positive integer.")
  349. return "Tool Diameter is zero value. Change it to a positive integer."
  350. if cutout_obj.multigeo is True:
  351. self.app.inform.emit("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  352. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  353. "and after that perform Cutout.")
  354. return
  355. def geo_init(geo_obj, app_obj):
  356. real_margin = margin + (dia / 2)
  357. real_gap_size = gapsize + dia
  358. minx, miny, maxx, maxy = cutout_obj.bounds()
  359. minx -= real_margin
  360. maxx += real_margin
  361. miny -= real_margin
  362. maxy += real_margin
  363. midx = 0.5 * (minx + maxx)
  364. midy = 0.5 * (miny + maxy)
  365. hgap = 0.5 * real_gap_size
  366. pts = [[midx - hgap, maxy],
  367. [minx, maxy],
  368. [minx, midy + hgap],
  369. [minx, midy - hgap],
  370. [minx, miny],
  371. [midx - hgap, miny],
  372. [midx + hgap, miny],
  373. [maxx, miny],
  374. [maxx, midy - hgap],
  375. [maxx, midy + hgap],
  376. [maxx, maxy],
  377. [midx + hgap, maxy]]
  378. cases = {"TB": [[pts[0], pts[1], pts[4], pts[5]],
  379. [pts[6], pts[7], pts[10], pts[11]]],
  380. "LR": [[pts[9], pts[10], pts[1], pts[2]],
  381. [pts[3], pts[4], pts[7], pts[8]]],
  382. "4": [[pts[0], pts[1], pts[2]],
  383. [pts[3], pts[4], pts[5]],
  384. [pts[6], pts[7], pts[8]],
  385. [pts[9], pts[10], pts[11]]]}
  386. cuts = cases[gaps]
  387. geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
  388. # TODO: Check for None
  389. self.app.new_object("geometry", name + "_cutout", geo_init)
  390. self.app.inform.emit("[success] Rectangular CutOut operation finished.")
  391. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  392. def reset_fields(self):
  393. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))