ToolDistanceMin.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 09/29/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore
  8. from FlatCAMTool import FlatCAMTool
  9. from flatcamGUI.VisPyVisuals import *
  10. from flatcamGUI.GUIElements import FCEntry
  11. from shapely.ops import nearest_points
  12. from shapely.geometry import Point, MultiPolygon
  13. from shapely.ops import cascaded_union
  14. import math
  15. import logging
  16. import gettext
  17. import FlatCAMTranslation as fcTranslate
  18. import builtins
  19. fcTranslate.apply_language('strings')
  20. if '_' not in builtins.__dict__:
  21. _ = gettext.gettext
  22. log = logging.getLogger('base')
  23. class DistanceMin(FlatCAMTool):
  24. toolName = _("Minimum Distance Tool")
  25. def __init__(self, app):
  26. FlatCAMTool.__init__(self, app)
  27. self.app = app
  28. self.canvas = self.app.plotcanvas
  29. self.units = self.app.defaults['units'].lower()
  30. self.decimals = self.app.decimals
  31. # ## Title
  32. title_label = QtWidgets.QLabel("<font size=4><b>%s</b></font><br>" % self.toolName)
  33. self.layout.addWidget(title_label)
  34. # ## Form Layout
  35. form_layout = QtWidgets.QFormLayout()
  36. self.layout.addLayout(form_layout)
  37. self.units_label = QtWidgets.QLabel('%s:' % _("Units"))
  38. self.units_label.setToolTip(_("Those are the units in which the distance is measured."))
  39. self.units_value = QtWidgets.QLabel("%s" % str({'mm': _("METRIC (mm)"), 'in': _("INCH (in)")}[self.units]))
  40. self.units_value.setDisabled(True)
  41. self.start_label = QtWidgets.QLabel("%s:" % _('First object point'))
  42. self.start_label.setToolTip(_("This is first object point coordinates.\n"
  43. "This is the start point for measuring distance."))
  44. self.stop_label = QtWidgets.QLabel("%s:" % _('Second object point'))
  45. self.stop_label.setToolTip(_("This is second object point coordinates.\n"
  46. "This is the end point for measuring distance."))
  47. self.distance_x_label = QtWidgets.QLabel('%s:' % _("Dx"))
  48. self.distance_x_label.setToolTip(_("This is the distance measured over the X axis."))
  49. self.distance_y_label = QtWidgets.QLabel('%s:' % _("Dy"))
  50. self.distance_y_label.setToolTip(_("This is the distance measured over the Y axis."))
  51. self.angle_label = QtWidgets.QLabel('%s:' % _("Angle"))
  52. self.angle_label.setToolTip(_("This is orientation angle of the measuring line."))
  53. self.total_distance_label = QtWidgets.QLabel("<b>%s:</b>" % _('DISTANCE'))
  54. self.total_distance_label.setToolTip(_("This is the point to point Euclidean distance."))
  55. self.half_point_label = QtWidgets.QLabel("<b>%s:</b>" % _('Half Point'))
  56. self.half_point_label.setToolTip(_("This is the middle point of the point to point Euclidean distance."))
  57. self.start_entry = FCEntry()
  58. self.start_entry.setReadOnly(True)
  59. self.start_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  60. self.start_entry.setToolTip(_("This is first object point coordinates.\n"
  61. "This is the start point for measuring distance."))
  62. self.stop_entry = FCEntry()
  63. self.stop_entry.setReadOnly(True)
  64. self.stop_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  65. self.stop_entry.setToolTip(_("This is second object point coordinates.\n"
  66. "This is the end point for measuring distance."))
  67. self.distance_x_entry = FCEntry()
  68. self.distance_x_entry.setReadOnly(True)
  69. self.distance_x_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  70. self.distance_x_entry.setToolTip(_("This is the distance measured over the X axis."))
  71. self.distance_y_entry = FCEntry()
  72. self.distance_y_entry.setReadOnly(True)
  73. self.distance_y_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  74. self.distance_y_entry.setToolTip(_("This is the distance measured over the Y axis."))
  75. self.angle_entry = FCEntry()
  76. self.angle_entry.setReadOnly(True)
  77. self.angle_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  78. self.angle_entry.setToolTip(_("This is orientation angle of the measuring line."))
  79. self.total_distance_entry = FCEntry()
  80. self.total_distance_entry.setReadOnly(True)
  81. self.total_distance_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  82. self.total_distance_entry.setToolTip(_("This is the point to point Euclidean distance."))
  83. self.half_point_entry = FCEntry()
  84. self.half_point_entry.setReadOnly(True)
  85. self.half_point_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  86. self.half_point_entry.setToolTip(_("This is the middle point of the point to point Euclidean distance."))
  87. self.measure_btn = QtWidgets.QPushButton(_("Measure"))
  88. self.layout.addWidget(self.measure_btn)
  89. self.jump_hp_btn = QtWidgets.QPushButton(_("Jump to Half Point"))
  90. self.layout.addWidget(self.jump_hp_btn)
  91. self.jump_hp_btn.setDisabled(True)
  92. form_layout.addRow(self.units_label, self.units_value)
  93. form_layout.addRow(self.start_label, self.start_entry)
  94. form_layout.addRow(self.stop_label, self.stop_entry)
  95. form_layout.addRow(self.distance_x_label, self.distance_x_entry)
  96. form_layout.addRow(self.distance_y_label, self.distance_y_entry)
  97. form_layout.addRow(self.angle_label, self.angle_entry)
  98. form_layout.addRow(self.total_distance_label, self.total_distance_entry)
  99. form_layout.addRow(self.half_point_label, self.half_point_entry)
  100. # initial view of the layout
  101. self.start_entry.set_value('(0, 0)')
  102. self.stop_entry.set_value('(0, 0)')
  103. self.distance_x_entry.set_value('0.0')
  104. self.distance_y_entry.set_value('0.0')
  105. self.angle_entry.set_value('0.0')
  106. self.total_distance_entry.set_value('0.0')
  107. self.half_point_entry.set_value('(0, 0)')
  108. self.layout.addStretch()
  109. self.h_point = (0, 0)
  110. self.measure_btn.clicked.connect(self.activate_measure_tool)
  111. self.jump_hp_btn.clicked.connect(self.on_jump_to_half_point)
  112. def run(self, toggle=False):
  113. self.app.report_usage("ToolDistanceMin()")
  114. if self.app.tool_tab_locked is True:
  115. return
  116. self.app.ui.notebook.setTabText(2, _("Minimum Distance Tool"))
  117. # if the splitter is hidden, display it
  118. if self.app.ui.splitter.sizes()[0] == 0:
  119. self.app.ui.splitter.setSizes([1, 1])
  120. if toggle:
  121. pass
  122. self.set_tool_ui()
  123. self.app.inform.emit('MEASURING: %s' %
  124. _("Select two objects and no more, to measure the distance between them ..."))
  125. def install(self, icon=None, separator=None, **kwargs):
  126. FlatCAMTool.install(self, icon, separator, shortcut='SHIFT+M', **kwargs)
  127. def set_tool_ui(self):
  128. # Remove anything else in the GUI
  129. self.app.ui.tool_scroll_area.takeWidget()
  130. # Put oneself in the GUI
  131. self.app.ui.tool_scroll_area.setWidget(self)
  132. # Switch notebook to tool page
  133. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  134. self.units = self.app.defaults['units'].lower()
  135. # initial view of the layout
  136. self.start_entry.set_value('(0, 0)')
  137. self.stop_entry.set_value('(0, 0)')
  138. self.distance_x_entry.set_value('0.0')
  139. self.distance_y_entry.set_value('0.0')
  140. self.angle_entry.set_value('0.0')
  141. self.total_distance_entry.set_value('0.0')
  142. self.half_point_entry.set_value('(0, 0)')
  143. self.jump_hp_btn.setDisabled(True)
  144. log.debug("Minimum Distance Tool --> tool initialized")
  145. def activate_measure_tool(self):
  146. # ENABLE the Measuring TOOL
  147. self.jump_hp_btn.setDisabled(False)
  148. self.units = self.app.defaults['units'].lower()
  149. if self.app.call_source == 'app':
  150. selected_objs = self.app.collection.get_selected()
  151. if len(selected_objs) != 2:
  152. self.app.inform.emit('[WARNING_NOTCL] %s %s' %
  153. (_("Select two objects and no more. Currently the selection has objects: "),
  154. str(len(selected_objs))))
  155. return
  156. else:
  157. if isinstance(selected_objs[0].solid_geometry, list):
  158. try:
  159. selected_objs[0].solid_geometry = MultiPolygon(selected_objs[0].solid_geometry)
  160. except Exception:
  161. selected_objs[0].solid_geometry = cascaded_union(selected_objs[0].solid_geometry)
  162. try:
  163. selected_objs[1].solid_geometry = MultiPolygon(selected_objs[1].solid_geometry)
  164. except Exception:
  165. selected_objs[1].solid_geometry = cascaded_union(selected_objs[1].solid_geometry)
  166. first_pos, last_pos = nearest_points(selected_objs[0].solid_geometry, selected_objs[1].solid_geometry)
  167. elif self.app.call_source == 'geo_editor':
  168. selected_objs = self.app.geo_editor.selected
  169. if len(selected_objs) != 2:
  170. self.app.inform.emit('[WARNING_NOTCL] %s %s' %
  171. (_("Select two objects and no more. Currently the selection has objects: "),
  172. str(len(selected_objs))))
  173. return
  174. else:
  175. first_pos, last_pos = nearest_points(selected_objs[0].geo, selected_objs[1].geo)
  176. elif self.app.call_source == 'exc_editor':
  177. selected_objs = self.app.exc_editor.selected
  178. if len(selected_objs) != 2:
  179. self.app.inform.emit('[WARNING_NOTCL] %s %s' %
  180. (_("Select two objects and no more. Currently the selection has objects: "),
  181. str(len(selected_objs))))
  182. return
  183. else:
  184. # the objects are really MultiLinesStrings made out of 2 lines in cross shape
  185. xmin, ymin, xmax, ymax = selected_objs[0].geo.bounds
  186. first_geo_radius = (xmax - xmin) / 2
  187. first_geo_center = Point(xmin + first_geo_radius, ymin + first_geo_radius)
  188. first_geo = first_geo_center.buffer(first_geo_radius)
  189. # the objects are really MultiLinesStrings made out of 2 lines in cross shape
  190. xmin, ymin, xmax, ymax = selected_objs[1].geo.bounds
  191. last_geo_radius = (xmax - xmin) / 2
  192. last_geo_center = Point(xmin + last_geo_radius, ymin + last_geo_radius)
  193. last_geo = last_geo_center.buffer(last_geo_radius)
  194. first_pos, last_pos = nearest_points(first_geo, last_geo)
  195. elif self.app.call_source == 'grb_editor':
  196. selected_objs = self.app.grb_editor.selected
  197. if len(selected_objs) != 2:
  198. self.app.inform.emit('[WARNING_NOTCL] %s %s' %
  199. (_("Select two objects and no more. Currently the selection has objects: "),
  200. str(len(selected_objs))))
  201. return
  202. else:
  203. first_pos, last_pos = nearest_points(selected_objs[0].geo['solid'], selected_objs[1].geo['solid'])
  204. else:
  205. first_pos, last_pos = 0, 0
  206. self.start_entry.set_value("(%.*f, %.*f)" % (self.decimals, first_pos.x, self.decimals, first_pos.y))
  207. self.stop_entry.set_value("(%.*f, %.*f)" % (self.decimals, last_pos.x, self.decimals, last_pos.y))
  208. dx = first_pos.x - last_pos.x
  209. dy = first_pos.y - last_pos.y
  210. self.distance_x_entry.set_value('%.*f' % (self.decimals, abs(dx)))
  211. self.distance_y_entry.set_value('%.*f' % (self.decimals, abs(dy)))
  212. try:
  213. angle = math.degrees(math.atan(dy / dx))
  214. self.angle_entry.set_value('%.*f' % (self.decimals, angle))
  215. except Exception as e:
  216. pass
  217. d = math.sqrt(dx ** 2 + dy ** 2)
  218. self.total_distance_entry.set_value('%.*f' % (self.decimals, abs(d)))
  219. self.h_point = (min(first_pos.x, last_pos.x) + (abs(dx) / 2), min(first_pos.y, last_pos.y) + (abs(dy) / 2))
  220. if d != 0:
  221. self.half_point_entry.set_value(
  222. "(%.*f, %.*f)" % (self.decimals, self.h_point[0], self.decimals, self.h_point[1])
  223. )
  224. else:
  225. self.half_point_entry.set_value(
  226. "(%.*f, %.*f)" % (self.decimals, 0.0, self.decimals, 0.0)
  227. )
  228. if d != 0:
  229. self.app.inform.emit("{tx1}: {tx2} D(x) = {d_x} | D(y) = {d_y} | {tx3} = {d_z}".format(
  230. tx1=_("MEASURING"),
  231. tx2=_("Result"),
  232. tx3=_("Distance"),
  233. d_x='%*f' % (self.decimals, abs(dx)),
  234. d_y='%*f' % (self.decimals, abs(dy)),
  235. d_z='%*f' % (self.decimals, abs(d)))
  236. )
  237. else:
  238. self.app.inform.emit('[WARNING_NOTCL] %s: %s' %
  239. (_("Objects intersects or touch at"),
  240. "(%.*f, %.*f)" % (self.decimals, self.h_point[0], self.decimals, self.h_point[1])))
  241. def on_jump_to_half_point(self):
  242. self.app.on_jump_to(custom_location=self.h_point)
  243. self.app.inform.emit('[success] %s: %s' %
  244. (_("Jumped to the half point between the two selected objects"),
  245. "(%.*f, %.*f)" % (self.decimals, self.h_point[0], self.decimals, self.h_point[1])))
  246. def set_meas_units(self, units):
  247. self.meas.units_label.setText("[" + self.app.options["units"].lower() + "]")
  248. # end of file