ToolPanelize.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtGui, QtCore
  8. from appTool import AppTool
  9. from appGUI.GUIElements import FCSpinner, FCDoubleSpinner, RadioSet, FCCheckBox, OptionalInputSection, FCComboBox
  10. from camlib import grace
  11. from copy import deepcopy
  12. import numpy as np
  13. import shapely.affinity as affinity
  14. from shapely.ops import unary_union, linemerge, snap
  15. from shapely.geometry import LineString, MultiLineString
  16. import gettext
  17. import appTranslation as fcTranslate
  18. import builtins
  19. import logging
  20. fcTranslate.apply_language('strings')
  21. if '_' not in builtins.__dict__:
  22. _ = gettext.gettext
  23. log = logging.getLogger('base')
  24. class Panelize(AppTool):
  25. toolName = _("Panelize PCB")
  26. def __init__(self, app):
  27. AppTool.__init__(self, app)
  28. self.decimals = app.decimals
  29. self.app = app
  30. # #############################################################################
  31. # ######################### Tool GUI ##########################################
  32. # #############################################################################
  33. self.ui = PanelizeUI(layout=self.layout, app=self.app)
  34. self.toolName = self.ui.toolName
  35. # Signals
  36. self.ui.reference_radio.activated_custom.connect(self.on_reference_radio_changed)
  37. self.ui.panelize_object_button.clicked.connect(self.on_panelize)
  38. self.ui.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  39. self.ui.type_box_combo.currentIndexChanged.connect(self.on_type_box_index_changed)
  40. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  41. # list to hold the temporary objects
  42. self.objs = []
  43. # final name for the panel object
  44. self.outname = ""
  45. # flag to signal the constrain was activated
  46. self.constrain_flag = False
  47. def run(self, toggle=True):
  48. self.app.defaults.report_usage("ToolPanelize()")
  49. if toggle:
  50. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  51. if self.app.ui.splitter.sizes()[0] == 0:
  52. self.app.ui.splitter.setSizes([1, 1])
  53. else:
  54. try:
  55. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  56. # if tab is populated with the tool but it does not have the focus, focus on it
  57. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  58. # focus on Tool Tab
  59. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  60. else:
  61. self.app.ui.splitter.setSizes([0, 1])
  62. except AttributeError:
  63. pass
  64. else:
  65. if self.app.ui.splitter.sizes()[0] == 0:
  66. self.app.ui.splitter.setSizes([1, 1])
  67. AppTool.run(self)
  68. self.set_tool_ui()
  69. self.app.ui.notebook.setTabText(2, _("Panel. Tool"))
  70. def install(self, icon=None, separator=None, **kwargs):
  71. AppTool.install(self, icon, separator, shortcut='Alt+Z', **kwargs)
  72. def set_tool_ui(self):
  73. self.reset_fields()
  74. self.ui.reference_radio.set_value('bbox')
  75. sp_c = self.app.defaults["tools_panelize_spacing_columns"] if \
  76. self.app.defaults["tools_panelize_spacing_columns"] else 0.0
  77. self.ui.spacing_columns.set_value(float(sp_c))
  78. sp_r = self.app.defaults["tools_panelize_spacing_rows"] if \
  79. self.app.defaults["tools_panelize_spacing_rows"] else 0.0
  80. self.ui.spacing_rows.set_value(float(sp_r))
  81. rr = self.app.defaults["tools_panelize_rows"] if \
  82. self.app.defaults["tools_panelize_rows"] else 0.0
  83. self.ui.rows.set_value(int(rr))
  84. cc = self.app.defaults["tools_panelize_columns"] if \
  85. self.app.defaults["tools_panelize_columns"] else 0.0
  86. self.ui.columns.set_value(int(cc))
  87. optimized_path_cb = self.app.defaults["tools_panelize_optimization"] if \
  88. self.app.defaults["tools_panelize_optimization"] else True
  89. self.ui.optimization_cb.set_value(optimized_path_cb)
  90. c_cb = self.app.defaults["tools_panelize_constrain"] if \
  91. self.app.defaults["tools_panelize_constrain"] else False
  92. self.ui.constrain_cb.set_value(c_cb)
  93. x_w = self.app.defaults["tools_panelize_constrainx"] if \
  94. self.app.defaults["tools_panelize_constrainx"] else 0.0
  95. self.ui.x_width_entry.set_value(float(x_w))
  96. y_w = self.app.defaults["tools_panelize_constrainy"] if \
  97. self.app.defaults["tools_panelize_constrainy"] else 0.0
  98. self.ui.y_height_entry.set_value(float(y_w))
  99. panel_type = self.app.defaults["tools_panelize_panel_type"] if \
  100. self.app.defaults["tools_panelize_panel_type"] else 'gerber'
  101. self.ui.panel_type_radio.set_value(panel_type)
  102. self.ui.on_panel_type(val=panel_type)
  103. # run once the following so the obj_type attribute is updated in the FCComboBoxes
  104. # such that the last loaded object is populated in the combo boxes
  105. self.on_type_obj_index_changed()
  106. self.on_type_box_index_changed()
  107. def on_type_obj_index_changed(self):
  108. obj_type = self.ui.type_obj_combo.currentIndex()
  109. self.ui.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  110. self.ui.object_combo.setCurrentIndex(0)
  111. self.ui.object_combo.obj_type = {
  112. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  113. }[self.ui.type_obj_combo.get_value()]
  114. # hide the panel type for Excellons, the panel can be only of type Geometry
  115. if self.ui.type_obj_combo.currentText() != 'Excellon':
  116. self.ui.panel_type_label.setDisabled(False)
  117. self.ui.panel_type_radio.setDisabled(False)
  118. self.ui.on_panel_type(val=self.ui.panel_type_radio.get_value())
  119. else:
  120. self.ui.panel_type_label.setDisabled(True)
  121. self.ui.panel_type_radio.setDisabled(True)
  122. self.ui.panel_type_radio.set_value('geometry')
  123. self.ui.optimization_cb.setDisabled(True)
  124. def on_type_box_index_changed(self):
  125. obj_type = self.ui.type_box_combo.currentIndex()
  126. obj_type = 2 if obj_type == 1 else obj_type
  127. self.ui.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  128. self.ui.box_combo.setCurrentIndex(0)
  129. self.ui.box_combo.obj_type = {
  130. _("Gerber"): "Gerber", _("Geometry"): "Geometry"
  131. }[self.ui.type_box_combo.get_value()]
  132. def on_reference_radio_changed(self, current_val):
  133. if current_val == 'object':
  134. self.ui.type_box_combo.setDisabled(False)
  135. self.ui.type_box_combo_label.setDisabled(False)
  136. self.ui.box_combo.setDisabled(False)
  137. else:
  138. self.ui.type_box_combo.setDisabled(True)
  139. self.ui.type_box_combo_label.setDisabled(True)
  140. self.ui.box_combo.setDisabled(True)
  141. def on_panelize(self):
  142. name = self.ui.object_combo.currentText()
  143. # delete any selection box
  144. self.app.delete_selection_shape()
  145. # Get source object to be panelized.
  146. try:
  147. panel_source_obj = self.app.collection.get_by_name(str(name))
  148. except Exception as e:
  149. log.debug("Panelize.on_panelize() --> %s" % str(e))
  150. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  151. return
  152. if panel_source_obj is None:
  153. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  154. (_("Object not found"), panel_source_obj))
  155. return
  156. boxname = self.ui.box_combo.currentText()
  157. try:
  158. box = self.app.collection.get_by_name(boxname)
  159. except Exception as e:
  160. log.debug("Panelize.on_panelize() --> %s" % str(e))
  161. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), boxname))
  162. return
  163. if box is None:
  164. self.app.inform.emit('[WARNING_NOTCL] %s: %s' % (_("No object Box. Using instead"), panel_source_obj))
  165. self.ui.reference_radio.set_value('bbox')
  166. if self.ui.reference_radio.get_value() == 'bbox':
  167. box = panel_source_obj
  168. self.outname = name + '_panelized'
  169. spacing_columns = float(self.ui.spacing_columns.get_value())
  170. spacing_columns = spacing_columns if spacing_columns is not None else 0
  171. spacing_rows = float(self.ui.spacing_rows.get_value())
  172. spacing_rows = spacing_rows if spacing_rows is not None else 0
  173. rows = int(self.ui.rows.get_value())
  174. rows = rows if rows is not None else 1
  175. columns = int(self.ui.columns.get_value())
  176. columns = columns if columns is not None else 1
  177. constrain_dx = float(self.ui.x_width_entry.get_value())
  178. constrain_dy = float(self.ui.y_height_entry.get_value())
  179. panel_type = str(self.ui.panel_type_radio.get_value())
  180. if 0 in {columns, rows}:
  181. self.app.inform.emit('[ERROR_NOTCL] %s' %
  182. _("Columns or Rows are zero value. Change them to a positive integer."))
  183. return
  184. xmin, ymin, xmax, ymax = box.bounds()
  185. lenghtx = xmax - xmin + spacing_columns
  186. lenghty = ymax - ymin + spacing_rows
  187. # check if constrain within an area is desired
  188. if self.ui.constrain_cb.isChecked():
  189. panel_lengthx = ((xmax - xmin) * columns) + (spacing_columns * (columns - 1))
  190. panel_lengthy = ((ymax - ymin) * rows) + (spacing_rows * (rows - 1))
  191. # adjust the number of columns and/or rows so the panel will fit within the panel constraint area
  192. if (panel_lengthx > constrain_dx) or (panel_lengthy > constrain_dy):
  193. self.constrain_flag = True
  194. while panel_lengthx > constrain_dx:
  195. columns -= 1
  196. panel_lengthx = ((xmax - xmin) * columns) + (spacing_columns * (columns - 1))
  197. while panel_lengthy > constrain_dy:
  198. rows -= 1
  199. panel_lengthy = ((ymax - ymin) * rows) + (spacing_rows * (rows - 1))
  200. if panel_source_obj.kind == 'excellon' or panel_source_obj.kind == 'geometry':
  201. # make a copy of the panelized Excellon or Geometry tools
  202. copied_tools = {}
  203. for tt, tt_val in list(panel_source_obj.tools.items()):
  204. copied_tools[tt] = deepcopy(tt_val)
  205. if panel_source_obj.kind == 'gerber':
  206. # make a copy of the panelized Gerber apertures
  207. copied_apertures = {}
  208. for tt, tt_val in list(panel_source_obj.apertures.items()):
  209. copied_apertures[tt] = deepcopy(tt_val)
  210. to_optimize = self.ui.optimization_cb.get_value()
  211. def panelize_worker():
  212. if panel_source_obj is not None:
  213. self.app.inform.emit(_("Generating panel ... "))
  214. def job_init_excellon(obj_fin, app_obj):
  215. currenty = 0.0
  216. # init the storage for drills and for slots
  217. for tool in copied_tools:
  218. copied_tools[tool]['drills'] = []
  219. copied_tools[tool]['slots'] = []
  220. obj_fin.tools = copied_tools
  221. obj_fin.solid_geometry = []
  222. for option in panel_source_obj.options:
  223. if option != 'name':
  224. try:
  225. obj_fin.options[option] = panel_source_obj.options[option]
  226. except KeyError:
  227. log.warning("Failed to copy option. %s" % str(option))
  228. # calculate the total number of drills and slots
  229. geo_len_drills = 0
  230. geo_len_slots = 0
  231. for tool in copied_tools:
  232. geo_len_drills += len(copied_tools[tool]['drills'])
  233. geo_len_slots += len(copied_tools[tool]['slots'])
  234. # panelization
  235. element = 0
  236. for row in range(rows):
  237. currentx = 0.0
  238. for col in range(columns):
  239. element += 1
  240. old_disp_number = 0
  241. for tool in panel_source_obj.tools:
  242. if panel_source_obj.tools[tool]['drills']:
  243. drill_nr = 0
  244. for drill in panel_source_obj.tools[tool]['drills']:
  245. # graceful abort requested by the user
  246. if self.app.abort_flag:
  247. raise grace
  248. # offset / panelization
  249. point_offseted = affinity.translate(drill, currentx, currenty)
  250. obj_fin.tools[tool]['drills'].append(point_offseted)
  251. # update progress
  252. drill_nr += 1
  253. disp_number = int(np.interp(drill_nr, [0, geo_len_drills], [0, 100]))
  254. if old_disp_number < disp_number <= 100:
  255. self.app.proc_container.update_view_text(' %s: %d D:%d%%' %
  256. (_("Copy"),
  257. int(element),
  258. disp_number))
  259. old_disp_number = disp_number
  260. if panel_source_obj.tools[tool]['slots']:
  261. slot_nr = 0
  262. for slot in panel_source_obj.tools[tool]['slots']:
  263. # graceful abort requested by the user
  264. if self.app.abort_flag:
  265. raise grace
  266. # offset / panelization
  267. start_offseted = affinity.translate(slot[0], currentx, currenty)
  268. stop_offseted = affinity.translate(slot[1], currentx, currenty)
  269. offseted_slot = (
  270. start_offseted,
  271. stop_offseted
  272. )
  273. obj_fin.tools[tool]['slots'].append(offseted_slot)
  274. # update progress
  275. slot_nr += 1
  276. disp_number = int(np.interp(slot_nr, [0, geo_len_slots], [0, 100]))
  277. if old_disp_number < disp_number <= 100:
  278. self.app.proc_container.update_view_text(' %s: %d S:%d%%' %
  279. (_("Copy"),
  280. int(element),
  281. disp_number))
  282. old_disp_number = disp_number
  283. currentx += lenghtx
  284. currenty += lenghty
  285. obj_fin.create_geometry()
  286. obj_fin.zeros = panel_source_obj.zeros
  287. obj_fin.units = panel_source_obj.units
  288. app_obj.inform.emit('%s' % _("Generating panel ... Adding the source code."))
  289. obj_fin.source_file = self.app.export_excellon(obj_name=self.outname, filename=None,
  290. local_use=obj_fin, use_thread=False)
  291. app_obj.proc_container.update_view_text('')
  292. def job_init_geometry(obj_fin, app_obj):
  293. currentx = 0.0
  294. currenty = 0.0
  295. def translate_recursion(geom):
  296. if type(geom) == list:
  297. geoms = []
  298. for local_geom in geom:
  299. res_geo = translate_recursion(local_geom)
  300. try:
  301. geoms += res_geo
  302. except TypeError:
  303. geoms.append(res_geo)
  304. return geoms
  305. else:
  306. return affinity.translate(geom, xoff=currentx, yoff=currenty)
  307. obj_fin.solid_geometry = []
  308. # create the initial structure on which to create the panel
  309. if panel_source_obj.kind == 'geometry':
  310. obj_fin.multigeo = panel_source_obj.multigeo
  311. obj_fin.tools = copied_tools
  312. if panel_source_obj.multigeo is True:
  313. for tool in panel_source_obj.tools:
  314. obj_fin.tools[tool]['solid_geometry'] = []
  315. elif panel_source_obj.kind == 'gerber':
  316. obj_fin.apertures = copied_apertures
  317. for ap in obj_fin.apertures:
  318. obj_fin.apertures[ap]['geometry'] = []
  319. # find the number of polygons in the source solid_geometry
  320. geo_len = 0
  321. if panel_source_obj.kind == 'geometry':
  322. if panel_source_obj.multigeo is True:
  323. for tool in panel_source_obj.tools:
  324. try:
  325. geo_len += len(panel_source_obj.tools[tool]['solid_geometry'])
  326. except TypeError:
  327. geo_len += 1
  328. elif panel_source_obj.kind == 'gerber':
  329. for ap in panel_source_obj.apertures:
  330. if 'geometry' in panel_source_obj.apertures[ap]:
  331. try:
  332. geo_len += len(panel_source_obj.apertures[ap]['geometry'])
  333. except TypeError:
  334. geo_len += 1
  335. element = 0
  336. for row in range(rows):
  337. currentx = 0.0
  338. for col in range(columns):
  339. element += 1
  340. old_disp_number = 0
  341. # Will panelize a Geometry Object
  342. if panel_source_obj.kind == 'geometry':
  343. if panel_source_obj.multigeo is True:
  344. for tool in panel_source_obj.tools:
  345. # graceful abort requested by the user
  346. if app_obj.abort_flag:
  347. raise grace
  348. # calculate the number of polygons
  349. try:
  350. geo_len = len(panel_source_obj.tools[tool]['solid_geometry'])
  351. except TypeError:
  352. geo_len = 1
  353. # panelization
  354. pol_nr = 0
  355. for geo_el in panel_source_obj.tools[tool]['solid_geometry']:
  356. trans_geo = translate_recursion(geo_el)
  357. obj_fin.tools[tool]['solid_geometry'].append(trans_geo)
  358. # update progress
  359. pol_nr += 1
  360. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  361. if old_disp_number < disp_number <= 100:
  362. app_obj.proc_container.update_view_text(
  363. ' %s: %d %d%%' % (_("Copy"), int(element), disp_number))
  364. old_disp_number = disp_number
  365. else:
  366. # graceful abort requested by the user
  367. if app_obj.abort_flag:
  368. raise grace
  369. # calculate the number of polygons
  370. try:
  371. geo_len = len(panel_source_obj.solid_geometry)
  372. except TypeError:
  373. geo_len = 1
  374. # panelization
  375. pol_nr = 0
  376. try:
  377. for geo_el in panel_source_obj.solid_geometry:
  378. if app_obj.abort_flag:
  379. # graceful abort requested by the user
  380. raise grace
  381. trans_geo = translate_recursion(geo_el)
  382. obj_fin.solid_geometry.append(trans_geo)
  383. # update progress
  384. pol_nr += 1
  385. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  386. if old_disp_number < disp_number <= 100:
  387. app_obj.proc_container.update_view_text(
  388. ' %s: %d %d%%' % (_("Copy"), int(element), disp_number))
  389. old_disp_number = disp_number
  390. except TypeError:
  391. trans_geo = translate_recursion(panel_source_obj.solid_geometry)
  392. obj_fin.solid_geometry.append(trans_geo)
  393. # Will panelize a Gerber Object
  394. else:
  395. # graceful abort requested by the user
  396. if self.app.abort_flag:
  397. raise grace
  398. # panelization solid_geometry
  399. try:
  400. for geo_el in panel_source_obj.solid_geometry:
  401. # graceful abort requested by the user
  402. if app_obj.abort_flag:
  403. raise grace
  404. trans_geo = translate_recursion(geo_el)
  405. obj_fin.solid_geometry.append(trans_geo)
  406. except TypeError:
  407. trans_geo = translate_recursion(panel_source_obj.solid_geometry)
  408. obj_fin.solid_geometry.append(trans_geo)
  409. for apid in panel_source_obj.apertures:
  410. # graceful abort requested by the user
  411. if app_obj.abort_flag:
  412. raise grace
  413. if 'geometry' in panel_source_obj.apertures[apid]:
  414. # calculate the number of polygons
  415. try:
  416. geo_len = len(panel_source_obj.apertures[apid]['geometry'])
  417. except TypeError:
  418. geo_len = 1
  419. # panelization -> tools
  420. pol_nr = 0
  421. for el in panel_source_obj.apertures[apid]['geometry']:
  422. if app_obj.abort_flag:
  423. # graceful abort requested by the user
  424. raise grace
  425. new_el = {}
  426. if 'solid' in el:
  427. geo_aper = translate_recursion(el['solid'])
  428. new_el['solid'] = geo_aper
  429. if 'clear' in el:
  430. geo_aper = translate_recursion(el['clear'])
  431. new_el['clear'] = geo_aper
  432. if 'follow' in el:
  433. geo_aper = translate_recursion(el['follow'])
  434. new_el['follow'] = geo_aper
  435. obj_fin.apertures[apid]['geometry'].append(deepcopy(new_el))
  436. # update progress
  437. pol_nr += 1
  438. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  439. if old_disp_number < disp_number <= 100:
  440. app_obj.proc_container.update_view_text(
  441. ' %s: %d %d%%' % (_("Copy"), int(element), disp_number))
  442. old_disp_number = disp_number
  443. currentx += lenghtx
  444. currenty += lenghty
  445. if panel_source_obj.kind == 'geometry' and panel_source_obj.multigeo is True:
  446. # I'm going to do this only here as a fix for panelizing cutouts
  447. # I'm going to separate linestrings out of the solid geometry from other
  448. # possible type of elements and apply unary_union on them to fuse them
  449. if to_optimize is True:
  450. app_obj.inform.emit('%s' % _("Optimizing the overlapping paths."))
  451. for tool in obj_fin.tools:
  452. lines = []
  453. other_geo = []
  454. for geo in obj_fin.tools[tool]['solid_geometry']:
  455. if isinstance(geo, LineString):
  456. lines.append(geo)
  457. elif isinstance(geo, MultiLineString):
  458. for line in geo:
  459. lines.append(line)
  460. else:
  461. other_geo.append(geo)
  462. if to_optimize is True:
  463. for idx, line in enumerate(lines):
  464. for idx_s in range(idx+1, len(lines)):
  465. line_mod = lines[idx_s]
  466. dist = line.distance(line_mod)
  467. if dist < 1e-8:
  468. print("Disjoint %d: %d -> %s" % (idx, idx_s, str(dist)))
  469. print("Distance %f" % dist)
  470. res = snap(line_mod, line, tolerance=1e-7)
  471. if res and not res.is_empty:
  472. lines[idx_s] = res
  473. fused_lines = linemerge(lines)
  474. fused_lines = [unary_union(fused_lines)]
  475. obj_fin.tools[tool]['solid_geometry'] = fused_lines + other_geo
  476. if to_optimize is True:
  477. app_obj.inform.emit('%s' % _("Optimization complete."))
  478. app_obj.inform.emit('%s' % _("Generating panel ... Adding the source code."))
  479. if panel_type == 'gerber':
  480. obj_fin.source_file = self.app.export_gerber(obj_name=self.outname, filename=None,
  481. local_use=obj_fin, use_thread=False)
  482. if panel_type == 'geometry':
  483. obj_fin.source_file = self.app.export_dxf(obj_name=self.outname, filename=None,
  484. local_use=obj_fin, use_thread=False)
  485. # obj_fin.solid_geometry = unary_union(obj_fin.solid_geometry)
  486. # app_obj.log.debug("Finished creating a unary_union for the panel.")
  487. app_obj.proc_container.update_view_text('')
  488. self.app.inform.emit('%s: %d' % (_("Generating panel... Spawning copies"), (int(rows * columns))))
  489. if panel_source_obj.kind == 'excellon':
  490. self.app.app_obj.new_object(
  491. "excellon", self.outname, job_init_excellon, plot=True, autoselected=True)
  492. else:
  493. self.app.app_obj.new_object(
  494. panel_type, self.outname, job_init_geometry, plot=True, autoselected=True)
  495. if self.constrain_flag is False:
  496. self.app.inform.emit('[success] %s' % _("Panel done..."))
  497. else:
  498. self.constrain_flag = False
  499. self.app.inform.emit(_("{text} Too big for the constrain area. "
  500. "Final panel has {col} columns and {row} rows").format(
  501. text='[WARNING] ', col=columns, row=rows))
  502. proc = self.app.proc_container.new(_("Working..."))
  503. def job_thread(app_obj):
  504. try:
  505. panelize_worker()
  506. app_obj.inform.emit('[success] %s' % _("Panel created successfully."))
  507. except Exception as ee:
  508. proc.done()
  509. log.debug(str(ee))
  510. return
  511. proc.done()
  512. self.app.collection.promise(self.outname)
  513. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  514. def reset_fields(self):
  515. self.ui.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  516. self.ui.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  517. class PanelizeUI:
  518. toolName = _("Panelize PCB")
  519. def __init__(self, layout, app):
  520. self.app = app
  521. self.decimals = self.app.decimals
  522. self.layout = layout
  523. # ## Title
  524. title_label = QtWidgets.QLabel("%s" % self.toolName)
  525. title_label.setStyleSheet("""
  526. QLabel
  527. {
  528. font-size: 16px;
  529. font-weight: bold;
  530. }
  531. """)
  532. self.layout.addWidget(title_label)
  533. self.object_label = QtWidgets.QLabel('<b>%s:</b>' % _("Source Object"))
  534. self.object_label.setToolTip(
  535. _("Specify the type of object to be panelized\n"
  536. "It can be of type: Gerber, Excellon or Geometry.\n"
  537. "The selection here decide the type of objects that will be\n"
  538. "in the Object combobox.")
  539. )
  540. self.layout.addWidget(self.object_label)
  541. # Form Layout
  542. form_layout_0 = QtWidgets.QFormLayout()
  543. self.layout.addLayout(form_layout_0)
  544. # Type of object to be panelized
  545. self.type_obj_combo = FCComboBox()
  546. self.type_obj_combo.addItem("Gerber")
  547. self.type_obj_combo.addItem("Excellon")
  548. self.type_obj_combo.addItem("Geometry")
  549. self.type_obj_combo.setItemIcon(0, QtGui.QIcon(self.app.resource_location + "/flatcam_icon16.png"))
  550. self.type_obj_combo.setItemIcon(1, QtGui.QIcon(self.app.resource_location + "/drill16.png"))
  551. self.type_obj_combo.setItemIcon(2, QtGui.QIcon(self.app.resource_location + "/geometry16.png"))
  552. self.type_object_label = QtWidgets.QLabel('%s:' % _("Object Type"))
  553. form_layout_0.addRow(self.type_object_label, self.type_obj_combo)
  554. # Object to be panelized
  555. self.object_combo = FCComboBox()
  556. self.object_combo.setModel(self.app.collection)
  557. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  558. self.object_combo.is_last = True
  559. self.object_combo.setToolTip(
  560. _("Object to be panelized. This means that it will\n"
  561. "be duplicated in an array of rows and columns.")
  562. )
  563. form_layout_0.addRow(self.object_combo)
  564. # Form Layout
  565. form_layout = QtWidgets.QFormLayout()
  566. self.layout.addLayout(form_layout)
  567. # Type of box Panel object
  568. self.reference_radio = RadioSet([{'label': _('Object'), 'value': 'object'},
  569. {'label': _('Bounding Box'), 'value': 'bbox'}])
  570. self.box_label = QtWidgets.QLabel("<b>%s:</b>" % _("Penelization Reference"))
  571. self.box_label.setToolTip(
  572. _("Choose the reference for panelization:\n"
  573. "- Object = the bounding box of a different object\n"
  574. "- Bounding Box = the bounding box of the object to be panelized\n"
  575. "\n"
  576. "The reference is useful when doing panelization for more than one\n"
  577. "object. The spacings (really offsets) will be applied in reference\n"
  578. "to this reference object therefore maintaining the panelized\n"
  579. "objects in sync.")
  580. )
  581. form_layout.addRow(self.box_label)
  582. form_layout.addRow(self.reference_radio)
  583. # Type of Box Object to be used as an envelope for panelization
  584. self.type_box_combo = FCComboBox()
  585. self.type_box_combo.addItems([_("Gerber"), _("Geometry")])
  586. # we get rid of item1 ("Excellon") as it is not suitable for use as a "box" for panelizing
  587. # self.type_box_combo.view().setRowHidden(1, True)
  588. self.type_box_combo.setItemIcon(0, QtGui.QIcon(self.app.resource_location + "/flatcam_icon16.png"))
  589. self.type_box_combo.setItemIcon(1, QtGui.QIcon(self.app.resource_location + "/geometry16.png"))
  590. self.type_box_combo_label = QtWidgets.QLabel('%s:' % _("Box Type"))
  591. self.type_box_combo_label.setToolTip(
  592. _("Specify the type of object to be used as an container for\n"
  593. "panelization. It can be: Gerber or Geometry type.\n"
  594. "The selection here decide the type of objects that will be\n"
  595. "in the Box Object combobox.")
  596. )
  597. form_layout.addRow(self.type_box_combo_label, self.type_box_combo)
  598. # Box
  599. self.box_combo = FCComboBox()
  600. self.box_combo.setModel(self.app.collection)
  601. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  602. # self.box_combo.is_last = True
  603. self.box_combo.setToolTip(
  604. _("The actual object that is used as container for the\n "
  605. "selected object that is to be panelized.")
  606. )
  607. form_layout.addRow(self.box_combo)
  608. separator_line = QtWidgets.QFrame()
  609. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  610. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  611. form_layout.addRow(separator_line)
  612. panel_data_label = QtWidgets.QLabel("<b>%s:</b>" % _("Panel Data"))
  613. panel_data_label.setToolTip(
  614. _("This informations will shape the resulting panel.\n"
  615. "The number of rows and columns will set how many\n"
  616. "duplicates of the original geometry will be generated.\n"
  617. "\n"
  618. "The spacings will set the distance between any two\n"
  619. "elements of the panel array.")
  620. )
  621. form_layout.addRow(panel_data_label)
  622. # Spacing Columns
  623. self.spacing_columns = FCDoubleSpinner(callback=self.confirmation_message)
  624. self.spacing_columns.set_range(0, 9999)
  625. self.spacing_columns.set_precision(4)
  626. self.spacing_columns_label = QtWidgets.QLabel('%s:' % _("Spacing cols"))
  627. self.spacing_columns_label.setToolTip(
  628. _("Spacing between columns of the desired panel.\n"
  629. "In current units.")
  630. )
  631. form_layout.addRow(self.spacing_columns_label, self.spacing_columns)
  632. # Spacing Rows
  633. self.spacing_rows = FCDoubleSpinner(callback=self.confirmation_message)
  634. self.spacing_rows.set_range(0, 9999)
  635. self.spacing_rows.set_precision(4)
  636. self.spacing_rows_label = QtWidgets.QLabel('%s:' % _("Spacing rows"))
  637. self.spacing_rows_label.setToolTip(
  638. _("Spacing between rows of the desired panel.\n"
  639. "In current units.")
  640. )
  641. form_layout.addRow(self.spacing_rows_label, self.spacing_rows)
  642. # Columns
  643. self.columns = FCSpinner(callback=self.confirmation_message_int)
  644. self.columns.set_range(0, 9999)
  645. self.columns_label = QtWidgets.QLabel('%s:' % _("Columns"))
  646. self.columns_label.setToolTip(
  647. _("Number of columns of the desired panel")
  648. )
  649. form_layout.addRow(self.columns_label, self.columns)
  650. # Rows
  651. self.rows = FCSpinner(callback=self.confirmation_message_int)
  652. self.rows.set_range(0, 9999)
  653. self.rows_label = QtWidgets.QLabel('%s:' % _("Rows"))
  654. self.rows_label.setToolTip(
  655. _("Number of rows of the desired panel")
  656. )
  657. form_layout.addRow(self.rows_label, self.rows)
  658. separator_line = QtWidgets.QFrame()
  659. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  660. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  661. form_layout.addRow(separator_line)
  662. # Type of resulting Panel object
  663. self.panel_type_radio = RadioSet([{'label': _('Gerber'), 'value': 'gerber'},
  664. {'label': _('Geo'), 'value': 'geometry'}])
  665. self.panel_type_label = QtWidgets.QLabel("<b>%s:</b>" % _("Panel Type"))
  666. self.panel_type_label.setToolTip(
  667. _("Choose the type of object for the panel object:\n"
  668. "- Geometry\n"
  669. "- Gerber")
  670. )
  671. form_layout.addRow(self.panel_type_label)
  672. form_layout.addRow(self.panel_type_radio)
  673. # Path optimization
  674. self.optimization_cb = FCCheckBox('%s' % _("Path Optimization"))
  675. self.optimization_cb.setToolTip(
  676. _("Active only for Geometry panel type.\n"
  677. "When checked the application will find\n"
  678. "any two overlapping Line elements in the panel\n"
  679. "and remove the overlapping parts, keeping only one of them.")
  680. )
  681. form_layout.addRow(self.optimization_cb)
  682. # Constrains
  683. self.constrain_cb = FCCheckBox('%s:' % _("Constrain panel within"))
  684. self.constrain_cb.setToolTip(
  685. _("Area define by DX and DY within to constrain the panel.\n"
  686. "DX and DY values are in current units.\n"
  687. "Regardless of how many columns and rows are desired,\n"
  688. "the final panel will have as many columns and rows as\n"
  689. "they fit completely within selected area.")
  690. )
  691. form_layout.addRow(self.constrain_cb)
  692. self.x_width_entry = FCDoubleSpinner(callback=self.confirmation_message)
  693. self.x_width_entry.set_precision(4)
  694. self.x_width_entry.set_range(0, 9999)
  695. self.x_width_lbl = QtWidgets.QLabel('%s:' % _("Width (DX)"))
  696. self.x_width_lbl.setToolTip(
  697. _("The width (DX) within which the panel must fit.\n"
  698. "In current units.")
  699. )
  700. form_layout.addRow(self.x_width_lbl, self.x_width_entry)
  701. self.y_height_entry = FCDoubleSpinner(callback=self.confirmation_message)
  702. self.y_height_entry.set_range(0, 9999)
  703. self.y_height_entry.set_precision(4)
  704. self.y_height_lbl = QtWidgets.QLabel('%s:' % _("Height (DY)"))
  705. self.y_height_lbl.setToolTip(
  706. _("The height (DY)within which the panel must fit.\n"
  707. "In current units.")
  708. )
  709. form_layout.addRow(self.y_height_lbl, self.y_height_entry)
  710. self.constrain_sel = OptionalInputSection(
  711. self.constrain_cb, [self.x_width_lbl, self.x_width_entry, self.y_height_lbl, self.y_height_entry])
  712. separator_line = QtWidgets.QFrame()
  713. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  714. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  715. form_layout.addRow(separator_line)
  716. # Buttons
  717. self.panelize_object_button = QtWidgets.QPushButton(_("Panelize Object"))
  718. self.panelize_object_button.setToolTip(
  719. _("Panelize the specified object around the specified box.\n"
  720. "In other words it creates multiple copies of the source object,\n"
  721. "arranged in a 2D array of rows and columns.")
  722. )
  723. self.panelize_object_button.setStyleSheet("""
  724. QPushButton
  725. {
  726. font-weight: bold;
  727. }
  728. """)
  729. self.layout.addWidget(self.panelize_object_button)
  730. self.layout.addStretch()
  731. # ## Reset Tool
  732. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  733. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  734. self.reset_button.setToolTip(
  735. _("Will reset the tool parameters.")
  736. )
  737. self.reset_button.setStyleSheet("""
  738. QPushButton
  739. {
  740. font-weight: bold;
  741. }
  742. """)
  743. self.layout.addWidget(self.reset_button)
  744. # #################################### FINSIHED GUI ###########################
  745. # #############################################################################
  746. self.panel_type_radio.activated_custom.connect(self.on_panel_type)
  747. def on_panel_type(self, val):
  748. if val == 'geometry':
  749. self.optimization_cb.setDisabled(False)
  750. else:
  751. self.optimization_cb.setDisabled(True)
  752. def confirmation_message(self, accepted, minval, maxval):
  753. if accepted is False:
  754. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  755. self.decimals,
  756. minval,
  757. self.decimals,
  758. maxval), False)
  759. else:
  760. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  761. def confirmation_message_int(self, accepted, minval, maxval):
  762. if accepted is False:
  763. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  764. (_("Edited value is out of range"), minval, maxval), False)
  765. else:
  766. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)