/
gui_dimensions.py
580 lines (532 loc) · 26 KB
/
gui_dimensions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# ***************************************************************************
# * (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""Provides tools for creating dimension objects with the Draft Workbench.
The objects can be simple linear dimensions that measure between two arbitrary
points, or linear dimensions linked to an edge.
It can also be radius or diameter dimensions that measure circles
and circular arcs.
And it can also be an angular dimension measuring the angle between
two straight lines.
"""
## @package gui_dimensions
# \ingroup DRAFT
# \brief Provides tools for creating dimensions with the Draft Workbench.
import math
import lazy_loader.lazy_loader as lz
from PySide.QtCore import QT_TRANSLATE_NOOP
import FreeCAD as App
import FreeCADGui as Gui
import Draft_rc
import DraftVecUtils
import draftguitools.gui_base_original as gui_base_original
import draftguitools.gui_tool_utils as gui_tool_utils
import draftguitools.gui_trackers as trackers
from draftutils.translate import translate
from draftutils.messages import _msg
DraftGeomUtils = lz.LazyLoader("DraftGeomUtils", globals(), "DraftGeomUtils")
# The module is used to prevent complaints from code checkers (flake8)
True if Draft_rc.__name__ else False
class Dimension(gui_base_original.Creator):
"""Gui command for the Dimension tool.
This includes at the moment linear, radial, diametrical,
and angular dimensions depending on the selected object
and the modifier key (ALT) used.
Maybe in the future each type can be in its own class,
and they can inherit their basic properties from a parent class.
"""
def __init__(self):
self.max = 2
self.cont = None
self.dir = None
def GetResources(self):
"""Set icon, menu and tooltip."""
_tip = ("Creates a dimension.\n"
"\n"
"- Pick three points to create a simple linear dimension.\n"
"- Select a straight line to create a linear dimension "
"linked to that line.\n"
"- Select an arc or circle to create a radius or diameter "
"dimension linked to that arc.\n"
"- Select two straight lines to create an angular dimension "
"between them.\n"
"CTRL to snap, SHIFT to constrain, "
"ALT to select an edge or arc.\n"
"\n"
"You may select a single line or single circular arc "
"before launching this command\n"
"to create the corresponding linked dimension.\n"
"You may also select an 'App::MeasureDistance' object "
"before launching this command\n"
"to turn it into a 'Draft Dimension' object.")
return {'Pixmap': 'Draft_Dimension',
'Accel': "D, I",
'MenuText': QT_TRANSLATE_NOOP("Draft_Dimension", "Dimension"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Dimension", _tip)}
def Activated(self):
"""Execute when the command is called."""
name = translate("draft", "Dimension")
if self.cont:
self.finish()
elif self.selected_app_measure():
super(Dimension, self).Activated(name)
self.dimtrack = trackers.dimTracker()
self.arctrack = trackers.arcTracker()
self.create_with_app_measure()
self.finish()
else:
super(Dimension, self).Activated(name)
if self.ui:
self.ui.pointUi(name)
self.ui.continueCmd.show()
self.ui.selectButton.show()
self.altdown = False
self.call = self.view.addEventCallback("SoEvent", self.action)
self.dimtrack = trackers.dimTracker()
self.arctrack = trackers.arcTracker()
self.link = None
self.edges = []
self.pts = []
self.angledata = None
self.indices = []
self.center = None
self.arcmode = False
self.point2 = None
self.force = None
self.info = None
self.selectmode = False
self.set_selection()
_msg(translate("draft", "Pick first point"))
Gui.draftToolBar.show()
def set_selection(self):
"""Fill the nodes according to the selected geometry."""
sel = Gui.Selection.getSelectionEx()
if (len(sel) == 1
and len(sel[0].SubElementNames) == 1
and "Edge" in sel[0].SubElementNames[0]):
# The selection is just a single `Edge`
sel_object = sel[0]
edge = sel_object.SubObjects[0]
# `n` is the edge number starting from 0 not from 1.
# The reason is lists in Python start from 0, although
# in the object's `Shape`, they start from 1
n = int(sel_object.SubElementNames[0].lstrip("Edge")) - 1
self.indices.append(n)
if DraftGeomUtils.geomType(edge) == "Line":
self.node.extend([edge.Vertexes[0].Point,
edge.Vertexes[1].Point])
# Iterate over the vertices of the parent `Object`;
# when the vertices match those of the selected `edge`
# save the index of vertex in the parent object
v1 = None
v2 = None
for i, v in enumerate(sel_object.Object.Shape.Vertexes):
if v.Point == edge.Vertexes[0].Point:
v1 = i
if v.Point == edge.Vertexes[1].Point:
v2 = i
if v1 and v2:
self.link = [sel_object.Object, v1, v2]
elif DraftGeomUtils.geomType(edge) == "Circle":
self.node.extend([edge.Curve.Center,
edge.Vertexes[0].Point])
self.edges = [edge]
self.arcmode = "diameter"
self.link = [sel_object.Object, n]
def selected_app_measure(self):
"""Check if App::MeasureDistance objects are selected."""
sel = Gui.Selection.getSelection()
if not sel:
return False
for o in sel:
if not o.isDerivedFrom("App::MeasureDistance"):
return False
return True
def finish(self, closed=False):
"""Terminate the operation."""
self.cont = None
self.dir = None
super(Dimension, self).finish()
if self.ui:
self.dimtrack.finalize()
self.arctrack.finalize()
def create_with_app_measure(self):
"""Create on measurement objects.
This is used when the selection is an `'App::MeasureDistance'`,
which is created with the basic tool `Std_MeasureDistance`.
This object is removed and in its place a `Draft Dimension`
is created.
"""
for o in Gui.Selection.getSelection():
p1 = o.P1
p2 = o.P2
_root = o.ViewObject.RootNode
_ch = _root.getChildren()[1].getChildren()[0].getChildren()[0]
pt = _ch.getChildren()[3]
p3 = App.Vector(pt.point.getValues()[2].getValue())
Gui.addModule("Draft")
_cmd = 'Draft.make_linear_dimension'
_cmd += '('
_cmd += DraftVecUtils.toString(p1) + ', '
_cmd += DraftVecUtils.toString(p2) + ', '
_cmd += 'dim_line=' + DraftVecUtils.toString(p3)
_cmd += ')'
_rem = 'FreeCAD.ActiveDocument.removeObject("' + o.Name + '")'
_cmd_list = ['_dim_ = ' + _cmd,
_rem,
'Draft.autogroup(_dim_)',
'FreeCAD.ActiveDocument.recompute()']
self.commit(translate("draft", "Create Dimension"),
_cmd_list)
def create_angle_dimension(self):
"""Create an angular dimension from a center and two angles."""
normal_str = "None"
if len(self.edges) == 2:
v1 = DraftGeomUtils.vec(self.edges[0])
v2 = DraftGeomUtils.vec(self.edges[1])
norm = v1.cross(v2)
norm.normalize()
normal_str = DraftVecUtils.toString(norm)
ang1 = math.degrees(self.angledata[1])
ang2 = math.degrees(self.angledata[0])
if ang1 > 360:
ang1 = ang1 - 360
if ang2 > 360:
ang2 = ang2 - 360
_cmd = 'Draft.make_angular_dimension'
_cmd += '('
_cmd += 'center=' + DraftVecUtils.toString(self.center) + ', '
_cmd += 'angles='
_cmd += '['
_cmd += str(ang1) + ', '
_cmd += str(ang2)
_cmd += '], '
_cmd += 'dim_line=' + DraftVecUtils.toString(self.node[-1]) + ', '
_cmd += 'normal=' + normal_str
_cmd += ')'
_cmd_list = ['_dim_ = ' + _cmd,
'Draft.autogroup(_dim_)',
'FreeCAD.ActiveDocument.recompute()']
self.commit(translate("draft", "Create Dimension"),
_cmd_list)
def create_linear_dimension(self):
"""Create a simple linear dimension, not linked to an edge."""
_cmd = 'Draft.make_linear_dimension'
_cmd += '('
_cmd += DraftVecUtils.toString(self.node[0]) + ', '
_cmd += DraftVecUtils.toString(self.node[1]) + ', '
_cmd += 'dim_line=' + DraftVecUtils.toString(self.node[2])
_cmd += ')'
_cmd_list = ['_dim_ = ' + _cmd,
'Draft.autogroup(_dim_)',
'FreeCAD.ActiveDocument.recompute()']
self.commit(translate("draft", "Create Dimension"),
_cmd_list)
def create_linear_dimension_obj(self, direction=None):
"""Create a linear dimension linked to an edge.
The `link` attribute has indices of vertices as they appear
in the list `Shape.Vertexes`, so they start as zero 0.
The `LinearDimension` class, created by `make_linear_dimension_obj`,
considers the vertices of a `Shape` which are numbered to start
with 1, that is, `Vertex1`.
Therefore the value in `link` has to be incremented by 1.
"""
_cmd = 'Draft.make_linear_dimension_obj'
_cmd += '('
_cmd += 'FreeCAD.ActiveDocument.' + self.link[0].Name + ', '
_cmd += 'i1=' + str(self.link[1] + 1) + ', '
_cmd += 'i2=' + str(self.link[2] + 1) + ', '
_cmd += 'dim_line=' + DraftVecUtils.toString(self.node[2])
_cmd += ')'
_cmd_list = ['_dim_ = ' + _cmd]
if direction == "X":
_cmd_list += ['_dim_.Direction = FreeCAD.Vector(1, 0, 0)']
elif direction == "Y":
_cmd_list += ['_dim_.Direction = FreeCAD.Vector(0, 1, 0)']
_cmd_list += ['Draft.autogroup(_dim_)',
'FreeCAD.ActiveDocument.recompute()']
self.commit(translate("draft", "Create Dimension"),
_cmd_list)
def create_radial_dimension_obj(self):
"""Create a radial dimension linked to a circular edge."""
_cmd = 'Draft.make_dimension'
_cmd += '('
_cmd += 'FreeCAD.ActiveDocument.' + self.link[0].Name + ', '
_cmd += str(self.link[1]) + ', '
_cmd += '"' + str(self.arcmode) + '", '
_cmd += DraftVecUtils.toString(self.node[2])
_cmd += ')'
_cmd_list = ['_dim_ = ' + _cmd,
'Draft.autogroup(_dim_)',
'FreeCAD.ActiveDocument.recompute()']
self.commit(translate("draft", "Create Dimension (radial)"),
_cmd_list)
def createObject(self):
"""Create the actual object in the current document."""
Gui.addModule("Draft")
if self.angledata:
# Angle dimension, with two angles provided
self.create_angle_dimension()
elif self.link and not self.arcmode:
# Linear dimension, linked to a straight edge
if self.force == 1:
self.create_linear_dimension_obj("Y")
elif self.force == 2:
self.create_linear_dimension_obj("X")
else:
self.create_linear_dimension_obj()
elif self.arcmode:
# Radius or dimeter dimension, linked to a circular edge
self.create_radial_dimension_obj()
else:
# Linear dimension, not linked to any edge
self.create_linear_dimension()
if self.ui.continueMode:
self.cont = self.node[2]
if not self.dir:
if self.link:
v1 = self.link[0].Shape.Vertexes[self.link[1]].Point
v2 = self.link[0].Shape.Vertexes[self.link[2]].Point
self.dir = v2.sub(v1)
else:
self.dir = self.node[1].sub(self.node[0])
self.node = [self.node[1]]
self.link = None
def selectEdge(self):
"""Toggle the select mode to the opposite state."""
self.selectmode = not self.selectmode
def action(self, arg):
"""Handle the 3D scene events.
This is installed as an EventCallback in the Inventor view.
Parameters
----------
arg: dict
Dictionary with strings that indicates the type of event received
from the 3D view.
"""
if arg["Type"] == "SoKeyboardEvent":
if arg["Key"] == "ESCAPE":
self.finish()
elif arg["Type"] == "SoLocation2Event": # mouse movement detection
shift = gui_tool_utils.hasMod(arg, gui_tool_utils.MODCONSTRAIN)
if self.arcmode or self.point2:
gui_tool_utils.setMod(arg, gui_tool_utils.MODCONSTRAIN, False)
(self.point,
ctrlPoint, self.info) = gui_tool_utils.getPoint(self, arg,
noTracker=(len(self.node)>0))
if (gui_tool_utils.hasMod(arg, gui_tool_utils.MODALT)
or self.selectmode) and (len(self.node) < 3):
self.dimtrack.off()
if not self.altdown:
self.altdown = True
self.ui.switchUi(True)
if hasattr(Gui, "Snapper"):
Gui.Snapper.setSelectMode(True)
snapped = self.view.getObjectInfo((arg["Position"][0],
arg["Position"][1]))
if snapped:
ob = self.doc.getObject(snapped['Object'])
if "Edge" in snapped['Component']:
num = int(snapped['Component'].lstrip('Edge')) - 1
ed = ob.Shape.Edges[num]
v1 = ed.Vertexes[0].Point
v2 = ed.Vertexes[-1].Point
self.dimtrack.update([v1, v2, self.cont])
else:
if self.node and (len(self.edges) < 2):
self.dimtrack.on()
if len(self.edges) == 2:
# angular dimension
self.dimtrack.off()
r = self.point.sub(self.center)
self.arctrack.setRadius(r.Length)
a = self.arctrack.getAngle(self.point)
pair = DraftGeomUtils.getBoundaryAngles(a, self.pts)
if not (pair[0] < a < pair[1]):
self.angledata = [4 * math.pi - pair[0],
2 * math.pi - pair[1]]
else:
self.angledata = [2 * math.pi - pair[0],
2 * math.pi - pair[1]]
self.arctrack.setStartAngle(self.angledata[0])
self.arctrack.setEndAngle(self.angledata[1])
if self.altdown:
self.altdown = False
self.ui.switchUi(False)
if hasattr(Gui, "Snapper"):
Gui.Snapper.setSelectMode(False)
if self.dir:
_p = DraftVecUtils.project(self.point.sub(self.node[0]),
self.dir)
self.point = self.node[0].add(_p)
if len(self.node) == 2:
if self.arcmode and self.edges:
cen = self.edges[0].Curve.Center
rad = self.edges[0].Curve.Radius
baseray = self.point.sub(cen)
v2 = DraftVecUtils.scaleTo(baseray, rad)
v1 = v2.negative()
if shift:
self.node = [cen, cen.add(v2)]
self.arcmode = "radius"
else:
self.node = [cen.add(v1), cen.add(v2)]
self.arcmode = "diameter"
self.dimtrack.update(self.node)
# Draw constraint tracker line.
if shift and (not self.arcmode):
if len(self.node) == 2:
if not self.point2:
self.point2 = self.node[1]
else:
self.node[1] = self.point2
if not self.force:
_p = self.point.sub(self.node[0])
a = abs(_p.getAngle(App.DraftWorkingPlane.u))
if (a > math.pi/4) and (a <= 0.75*math.pi):
self.force = 1
else:
self.force = 2
if self.force == 1:
self.node[1] = App.Vector(self.node[0].x,
self.node[1].y,
self.node[0].z)
elif self.force == 2:
self.node[1] = App.Vector(self.node[1].x,
self.node[0].y,
self.node[0].z)
else:
self.force = None
if self.point2 and (len(self.node) > 1):
self.node[1] = self.point2
self.point2 = None
# update the dimline
if self.node and not self.arcmode:
self.dimtrack.update(self.node
+ [self.point] + [self.cont])
gui_tool_utils.redraw3DView()
elif arg["Type"] == "SoMouseButtonEvent":
if (arg["State"] == "DOWN") and (arg["Button"] == "BUTTON1"):
if self.point:
self.ui.redraw()
if (not self.node) and (not self.support):
gui_tool_utils.getSupport(arg)
if (gui_tool_utils.hasMod(arg, gui_tool_utils.MODALT)
or self.selectmode) and (len(self.node) < 3):
# print("snapped: ",self.info)
if self.info:
ob = self.doc.getObject(self.info['Object'])
if 'Edge' in self.info['Component']:
num = int(self.info['Component'].lstrip('Edge')) - 1
ed = ob.Shape.Edges[num]
v1 = ed.Vertexes[0].Point
v2 = ed.Vertexes[-1].Point
i1 = i2 = None
for i in range(len(ob.Shape.Vertexes)):
if v1 == ob.Shape.Vertexes[i].Point:
i1 = i
if v2 == ob.Shape.Vertexes[i].Point:
i2 = i
if (i1 is not None) and (i2 is not None):
self.indices.append(num)
if not self.edges:
# nothing snapped yet, we treat it
# as a normal edge-snapped dimension
self.node = [v1, v2]
self.link = [ob, i1, i2]
self.edges.append(ed)
if DraftGeomUtils.geomType(ed) == "Circle":
# snapped edge is an arc
self.arcmode = "diameter"
self.link = [ob, num]
else:
# there is already a snapped edge,
# so we start angular dimension
self.edges.append(ed)
# self.node now has the 4 endpoints
self.node.extend([v1, v2])
c = DraftGeomUtils.findIntersection(self.node[0],
self.node[1],
self.node[2],
self.node[3],
True, True)
if c:
# print("centers:",c)
self.center = c[0]
self.arctrack.setCenter(self.center)
self.arctrack.on()
for e in self.edges:
for v in e.Vertexes:
self.pts.append(self.arctrack.getAngle(v.Point))
self.link = [self.link[0], ob]
else:
_msg(translate("draft", "Edges don't intersect!"))
self.finish()
return
self.dimtrack.on()
else:
self.node.append(self.point)
self.selectmode = False
# print("node", self.node)
self.dimtrack.update(self.node)
if len(self.node) == 2:
self.point2 = self.node[1]
if len(self.node) == 1:
self.dimtrack.on()
if self.planetrack:
self.planetrack.set(self.node[0])
elif len(self.node) == 2 and self.cont:
self.node.append(self.cont)
self.createObject()
if not self.cont:
self.finish()
elif len(self.node) == 3:
# for unlinked arc mode:
# if self.arcmode:
# v = self.node[1].sub(self.node[0])
# v.multiply(0.5)
# cen = self.node[0].add(v)
# self.node = [self.node[0], self.node[1], cen]
self.createObject()
if not self.cont:
self.finish()
elif self.angledata:
self.node.append(self.point)
self.createObject()
self.finish()
def numericInput(self, numx, numy, numz):
"""Validate the entry fields in the user interface.
This function is called by the toolbar or taskpanel interface
when valid x, y, and z have been entered in the input fields.
"""
self.point = App.Vector(numx, numy, numz)
self.node.append(self.point)
self.dimtrack.update(self.node)
if len(self.node) == 1:
self.dimtrack.on()
elif len(self.node) == 3:
self.createObject()
if not self.cont:
self.finish()
Gui.addCommand('Draft_Dimension', Dimension())