/
DraftEdit.py
1848 lines (1646 loc) · 75.4 KB
/
DraftEdit.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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf8 -*-
#***************************************************************************
#* Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
#* Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
#* Copyright (c) 2019, 2020 Carlo Pavan <carlopav@gmail.com> *
#* *
#* 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. *
#* *
#* This program 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 this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#***************************************************************************
__title__= "FreeCAD Draft Edit Tool"
__author__ = "Yorik van Havre, Werner Mayer, Martin Burbaum, Ken Cline, \
Dmitry Chigrin, Carlo Pavan"
__url__ = "https://www.freecadweb.org"
import FreeCAD as App
import math
import Draft
if App.GuiUp:
# Do not import GUI-related modules if GUI is not there
import FreeCADGui as Gui
import DraftTools
from DraftTrackers import editTracker, wireTracker, arcTracker, bsplineTracker, bezcurveTracker
from pivy import coin
from PySide import QtCore, QtGui
from PySide.QtCore import QT_TRANSLATE_NOOP
from DraftTools import translate
COLORS = {
"default": Gui.draftToolBar.getDefaultColor("snap"),
"black": (0., 0., 0.),
"white": (1., 1., 1.),
"grey": (.5, .5, .5),
"red": (1., 0., 0.),
"green": (0., 1., 0.),
"blue": (0., 0., 1.),
"yellow": (1., 1., 0.),
"cyan": (0., 1., 1.),
"magenta":(1., 0., 1.)
}
class Edit():
"""
The Draft_Edit FreeCAD command definition.
A tool to graphically edit FreeCAD objects.
Current implementation use many parts of pivy graphics code by user "looo".
The tool collect editpoints from objects and display Trackers on them to allow
editing their Shape and their parameters.
Callbacks
----------
selection_callback
registered when tool is launched, identify
selected objects.
editing_callbacks
self._keyPressedCB -> self.keyPressed
self._mouseMovedCB -> self._mouseMovedCB
if self._mousePressedCB -> self.mousePressed
when trackers are displayed for selected objects,
theese callbacks capture user events and forward
them to related functions
Task panel (Draft Toolbar)
----------
self.ui = Gui.draftToolBar
TODO: since we introduced context menu for interacting
with editTrackers, point 2 should become obsolete,
because not consistent with multi-object editing.
Draft_Edit uses taskpanel in 3 ways:
1 - when waiting for user to select an object
calling self.ui.selectUi()
2 - when Trackers are displayed and user must click one, a
custom task panel is displayed depending on edited
object:
self.ui.editUi() -> the default one
self.ui.editUi("Wire") -> line and wire editing
self.ui.editUi("BezCurve") -> BezCurve editing
self.ui.editUi("Circle") -> circle editing
self.ui.editUi("Arc") -> arc editing
When Draft_Edit evaluate mouse click, depending if some
ui button have been pressed (.isChecked()), decide if
the action is a startEditing or AddPoint or DelPoint or
change BezCurve Continuity, ecc.
3 - when in editing, lineUi support clicking destination point
by self.startEditing
self.ui.lineUi()
self.ui.isRelative.show()
Tracker selection
----------
If the tool recognize mouse click as an attempt to startEditing,
using soRayPickAction, it identifies the selected editTracker and
start editing it. Here is where "looo" code was very useful.
Editing preview
----------
When object editing begins, self.ghost is initiated with the
corresponding DraftTracker of the object type. The object Tracker
is deleted when user clicks again and endEditing.
Context Menu
----------
Activated with Alt+LeftClick or pressing key "e"
It's a custom context menu, that depends on clicked tracker
or on clicked object.
display_tracker_menu
populates the menu with custom actions
evaluate_menu_action
evaluate user choosen action and launch corresponding
function.
Preferences
----------
maxObjects : Int
set by "DraftEditMaxObjects" in user preferences
The max number of FreeCAD objects the tool is
allowed to edit at the same time.
pick_radius : Int
set by "DraftEditPickRadius" in user preferences
The pick radius during editing operation.
Increase if you experience problems in clicking
on a editTracker because of screen resolution.
Attributes
----------
obj : Edited object
I'm planning to discard this attribute.
In old implementation every function was supposed to
act on self.obj, self.editpoints, self.trackers,
self.pl, self.invpl.
Due to multiple object editing, i'm planning to keep
just self.trackers. Any other object will be identified
and processed starting from editTracker informations.
editing : Int
Index of the editTracker that has been clicked by the
user. Tracker selection mechanism is based on it.
if self.editing == None :
the user didn't click any node, and next click will
be processed as an attempt to start editing operation
if self.editing == o or 1 or 2 or 3 etc :
the user is editing corresponding node, so next click
will be processed as an attempt to end editing operation
editpoints : List [FreeCAD::App.Vector]
List of editpoints collected from the edited object,
on whick editTrackers will be placed.
trackers : Dictionary {object.Name : [editTrackers]}
It records the list of DraftTrackers.editTracker.
{object.Name as String : [editTrackers for the object]}
Each tracker is created with (position,obj.Name,idx),
so it's possible to recall it
self.trackers[str(node.objectName.getValue())][ep]
overNode : DraftTrackers.editTracker
It represent the editTracker under the cursor position.
It is used to preview the tracker selection action.
ghost : DraftTrackers.*
Handles the tracker to preview editing operations.
it is initialized when user clicks on a editTracker
by self.startEditing() function.
alt_edit_mode : Int
Allows alternative editing modes for objects.
ATM supported for:
- arcs: if 0 edit by 3 points, if 1 edit by center,
radius, angles
supportedObjs : List
List of supported Draft Objects.
The tool use Draft.getType(obj) to compare object type
to the list.
supportedPartObjs : List
List of supported Part Objects.
The tool use Draft.getType(obj) and obj.TypeId to compare
object type to the list.
"""
def __init__(self):
"""
Initialize Draft_Edit Command.
"""
self.running = False
self.trackers = {'object':[]}
self.overNode = None # preselected node with mouseover
self.obj = None
self.editing = None
# event callbacks
self.selection_callback = None
self._keyPressedCB = None
self._mouseMovedCB = None
self._mousePressedCB = None
# this are used to edit structure objects, it's a bit buggy i think
self.selectstate = None
self.originalDisplayMode = None
self.originalPoints = None
self.originalNodes = None
# settings
param = App.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")
self.maxObjects = param.GetInt("DraftEditMaxObjects", 5)
self.pick_radius = param.GetInt("DraftEditPickRadius", 20)
self.alt_edit_mode = 0 # alternative edit mode for objects
# preview
self.ghost = None
#list of supported Draft and Arch objects
self.supportedObjs = ["BezCurve","Wire","BSpline","Circle","Rectangle",
"Polygon","Dimension","Space","Structure","PanelCut",
"PanelSheet","Wall", "Window"]
#list of supported Part objects (they don't have a proxy)
#TODO: Add support for "Part::Circle" "Part::RegularPolygon" "Part::Plane" "Part::Ellipse" "Part::Vertex" "Part::Spiral"
self.supportedPartObjs = ["Sketch", "Sketcher::SketchObject",
"Part", "Part::Line", "Part::Box"]
def GetResources(self):
return {'Pixmap': 'Draft_Edit',
'Accel': "D, E",
'MenuText': QtCore.QT_TRANSLATE_NOOP("Draft_Edit", "Edit"),
'ToolTip': QtCore.QT_TRANSLATE_NOOP("Draft_Edit", "Edits the active object")}
#---------------------------------------------------------------------------
# MAIN FUNCTIONS
#---------------------------------------------------------------------------
def Activated(self):
"""
Activated is run when user launch Edit command.
If something is selected -> call self.proceed()
If nothing is selected -> self.register_selection_callback()
"""
if self.running:
self.finish()
DraftTools.Modifier.Activated(self,"Edit")
if not App.ActiveDocument:
self.finish()
self.ui = Gui.draftToolBar
self.view = Draft.get3DView()
if Gui.Selection.getSelection():
self.proceed()
else:
self.ui.selectUi()
App.Console.PrintMessage(translate("draft",
"Select a Draft object to edit")
+ "\n")
self.register_selection_callback()
def proceed(self):
"this method defines editpoints and set the editTrackers"
self.unregister_selection_callback()
self.edited_objects = self.getObjsFromSelection()
if not self.edited_objects:
return self.finish()
# Save selectstate and turn selectable false.
# Object can remain selectable commenting following lines:
# self.saveSelectState(self.obj)
# self.setSelectState(self.obj, False)
# start object editing
Gui.Selection.clearSelection()
Gui.Snapper.setSelectMode(True)
self.ui.editUi()
for obj in self.edited_objects:
self.setEditPoints(obj)
self.register_editing_callbacks()
# TODO: align working plane when editing starts
# App.DraftWorkingPlane.save()
# self.alignWorkingPlane()
def finish(self,closed=False):
"""
terminates Edit Tool
"""
self.unregister_selection_callback()
self.unregister_editing_callbacks()
self.editing = None
self.finalizeGhost()
Gui.Snapper.setSelectMode(False)
if self.obj and closed:
if "Closed" in self.obj.PropertiesList:
if not self.obj.Closed:
self.obj.Closed = True
if self.ui:
self.removeTrackers()
self.restoreSelectState(self.obj)
if Draft.getType(self.obj) == "Structure":
if self.originalDisplayMode is not None:
self.obj.ViewObject.DisplayMode = self.originalDisplayMode
if self.originalPoints is not None:
self.obj.ViewObject.NodeSize = self.originalPoints
if self.originalNodes is not None:
self.obj.ViewObject.ShowNodes = self.originalNodes
self.selectstate = None
self.originalDisplayMode = None
self.originalPoints = None
self.originalNodes = None
DraftTools.Modifier.finish(self)
App.DraftWorkingPlane.restore()
if Gui.Snapper.grid:
Gui.Snapper.grid.set()
self.running = False
# delay resetting edit mode otherwise it doesn't happen
from PySide import QtCore
QtCore.QTimer.singleShot(0,Gui.ActiveDocument.resetEdit)
#---------------------------------------------------------------------------
# SCENE EVENTS CALLBACKS
#---------------------------------------------------------------------------
def register_selection_callback(self):
"""
register callback for selection when command is launched
"""
self.unregister_selection_callback()
self.selection_callback = self.view.addEventCallback("SoEvent",DraftTools.selectObject)
def unregister_selection_callback(self):
"""
remove selection callback if it exhists
"""
if self.selection_callback:
self.view.removeEventCallback("SoEvent",self.selection_callback)
self.selection_callback = None
def register_editing_callbacks(self):
"""
register editing callbacks (former action function)
"""
viewer = Gui.ActiveDocument.ActiveView.getViewer()
self.render_manager = viewer.getSoRenderManager()
view = Gui.ActiveDocument.ActiveView
if self._keyPressedCB is None:
self._keyPressedCB = view.addEventCallbackPivy(
coin.SoKeyboardEvent.getClassTypeId(), self.keyPressed)
if self._mouseMovedCB is None:
self._mouseMovedCB = view.addEventCallbackPivy(
coin.SoLocation2Event.getClassTypeId(), self.mouseMoved)
if self._mousePressedCB is None:
self._mousePressedCB = view.addEventCallbackPivy(
coin.SoMouseButtonEvent.getClassTypeId(), self.mousePressed)
#App.Console.PrintMessage("Draft edit callbacks registered \n")
def unregister_editing_callbacks(self):
"""
remove callbacks used during editing if they exhist
"""
view = Gui.ActiveDocument.ActiveView
if self._keyPressedCB:
view.removeEventCallbackSWIG(coin.SoKeyboardEvent.getClassTypeId(), self._keyPressedCB)
self._keyPressedCB = None
#App.Console.PrintMessage("Draft edit keyboard callback unregistered \n")
if self._mouseMovedCB:
view.removeEventCallbackSWIG(coin.SoLocation2Event.getClassTypeId(), self._mouseMovedCB)
self._mouseMovedCB = None
#App.Console.PrintMessage("Draft edit location callback unregistered \n")
if self._mousePressedCB:
view.removeEventCallbackSWIG(coin.SoMouseButtonEvent.getClassTypeId(), self._mousePressedCB)
self._mousePressedCB = None
#App.Console.PrintMessage("Draft edit mouse button callback unregistered \n")
#---------------------------------------------------------------------------
# SCENE EVENT HANDLERS
#---------------------------------------------------------------------------
def keyPressed(self, event_callback):
"""
keyboard event handler
"""
#TODO: Get the keys from preferences
event = event_callback.getEvent()
if event.getState() == coin.SoKeyboardEvent.DOWN:
key = event.getKey()
#App.Console.PrintMessage("pressed key : "+str(key)+"\n")
if key == 65307: # ESC
self.finish()
if key == 97: # "a"
self.finish()
if key == 111: # "o"
self.finish(closed=True)
if key == 101: # "e"
self.display_tracker_menu(event)
if key == 105: # "i"
if Draft.getType(self.obj) == "Circle":
self.arcInvert(self.obj)
def mousePressed(self, event_callback):
"""
mouse button event handler, calls: startEditing, endEditing, addPoint, delPoint
"""
event = event_callback.getEvent()
if (event.getState() == coin.SoMouseButtonEvent.DOWN and
event.getButton() == event.BUTTON1
):#left click
if not event.wasAltDown():
if self.ui.addButton.isChecked():
self.addPoint(event)
return
if self.ui.delButton.isChecked():
self.delPoint(event)
return
if Draft.getType(self.obj) == "BezCurve" and (self.ui.sharpButton.isChecked()
or self.ui.tangentButton.isChecked() or
self.ui.symmetricButton.isChecked()):
pos = event.getPosition()
node = self.getEditNode(pos)
ep = self.getEditNodeIndex(node)
if ep is None:
return
doc = App.getDocument(str(node.documentName.getValue()))
self.obj = doc.getObject(str(node.objectName.getValue()))
if self.obj is None:
return
if self.ui.sharpButton.isChecked():
return self.smoothBezPoint(self.obj, ep, 'Sharp')
elif self.ui.tangentButton.isChecked():
return self.smoothBezPoint(self.obj, ep, 'Tangent')
elif self.ui.symmetricButton.isChecked():
return self.smoothBezPoint(self.obj, ep, 'Symmetric')
if self.editing is None:
self.startEditing(event)
else:
self.endEditing(self.obj,self.editing)
elif event.wasAltDown(): #left click with ctrl down
self.display_tracker_menu(event)
def mouseMoved(self, event_callback):
"mouse moved event handler, update tracker position and update preview ghost"
event = event_callback.getEvent()
if self.editing != None:
self.updateTrackerAndGhost(event)
else:
# look for a node in mouse position and highlight it
pos = event.getPosition()
node = self.getEditNode(pos)
ep = self.getEditNodeIndex(node)
if ep is not None:
if self.overNode is not None:
self.overNode.setColor(COLORS["default"])
self.trackers[str(node.objectName.getValue())][ep].setColor(COLORS["red"])
self.overNode = self.trackers[str(node.objectName.getValue())][ep]
else:
if self.overNode is not None:
self.overNode.setColor(COLORS["default"])
self.overNode = None
def startEditing(self, event):
"start editing selected EditNode"
pos = event.getPosition()
node = self.getEditNode(pos)
ep = self.getEditNodeIndex(node)
if ep is None:
return
doc = App.getDocument(str(node.documentName.getValue()))
self.obj = doc.getObject(str(node.objectName.getValue()))
if self.obj is None:
return
self.setPlacement(self.obj)
App.Console.PrintMessage(self.obj.Name
+ ": editing node number "
+ str(ep) + "\n")
self.ui.lineUi()
self.ui.isRelative.show()
self.editing = ep
self.trackers[self.obj.Name][self.editing].off()
self.finalizeGhost()
self.ghost = self.initGhost(self.obj)
self.node.append(self.trackers[self.obj.Name][self.editing].get())
Gui.Snapper.setSelectMode(False)
self.hideTrackers()
def updateTrackerAndGhost(self, event):
"updates tracker position when editing and update ghost"
pos = event.getPosition().getValue()
orthoConstrain = False
if event.wasShiftDown() == 1: orthoConstrain = True
snappedPos = Gui.Snapper.snap((pos[0],pos[1]),self.node[-1], constrain=orthoConstrain)
self.trackers[self.obj.Name][self.editing].set(snappedPos)
self.ui.displayPoint(snappedPos,self.node[-1])
if self.ghost:
self.updateGhost(obj=self.obj,idx=self.editing,pt=snappedPos)
def endEditing(self, obj, nodeIndex, v = None):
"terminate editing and start object updating process"
self.finalizeGhost()
self.trackers[obj.Name][nodeIndex].on()
Gui.Snapper.setSelectMode(True)
if v is None:
# endEditing is called by mousePressed
v = self.trackers[obj.Name][nodeIndex].get()
else:
# endEditing is called by numericInput, so tracker
# position should be updated manually
self.trackers[obj.Name][nodeIndex].set(v)
self.update(obj, nodeIndex, v)
self.alt_edit_mode = 0
self.ui.editUi(self.ui.lastMode)
self.node = []
self.editing = None
self.showTrackers()
DraftTools.redraw3DView()
#---------------------------------------------------------------------------
# UTILS
#---------------------------------------------------------------------------
def getObjsFromSelection(self):
"evaluate selection and returns a valid object to edit"
selection = Gui.Selection.getSelection()
self.edited_objects = []
if len(selection) > self.maxObjects:
App.Console.PrintMessage(translate("draft",
"Too many objects selected, max number set to: ")
+ str(self.maxObjects) + "\n")
return None
for obj in selection:
if Draft.getType(obj) in self.supportedObjs:
self.edited_objects.append(obj)
continue
elif Draft.getType(obj) in self.supportedPartObjs:
if obj.TypeId in self.supportedPartObjs:
self.edited_objects.append(obj)
continue
App.Console.PrintWarning(obj.Name
+ translate("draft",
": this object is not editable")
+ "\n")
return self.edited_objects
def get_selected_obj_at_position(self, pos):
"""return object at given position
if object is one of the edited objects (self.edited_objects)
"""
selobjs = Gui.ActiveDocument.ActiveView.getObjectsInfo((pos[0],pos[1]))
if not selobjs:
return
for info in selobjs:
if not info:
return
for obj in self.edited_objects:
if obj.Name == info["Object"]:
return obj
def numericInput(self, v, numy=None, numz=None):
"""this function gets called by the toolbar
or by the mouse click and activate the update function"""
if (numy is not None):
v = App.Vector(v,numy,numz)
self.endEditing(self.obj, self.editing, v)
App.ActiveDocument.recompute()
def setSelectState(self, obj, selState = False):
if hasattr(obj.ViewObject,"Selectable"):
obj.ViewObject.Selectable = selState
def saveSelectState(self, obj):
if hasattr(obj.ViewObject,"Selectable"):
self.selectstate = obj.ViewObject.Selectable
def restoreSelectState(self,obj):
if obj:
if hasattr(obj.ViewObject,"Selectable") and (self.selectstate is not None):
obj.ViewObject.Selectable = self.selectstate
def setPlacement(self,obj):
"set self.pl and self.invpl to self.obj placement and inverse placement"
if not obj:
return
if "Placement" in obj.PropertiesList:
self.pl = obj.getGlobalPlacement()
self.invpl = self.pl.inverse()
def alignWorkingPlane(self):
"align working plane to self.obj"
if "Shape" in self.obj.PropertiesList:
if DraftTools.plane.weak:
DraftTools.plane.alignToFace(self.obj.Shape)
if self.planetrack:
self.planetrack.set(self.editpoints[0])
def getEditNode(self, pos):
"get edit node from given screen position"
node = self.sendRay(pos)
return node
def sendRay(self, mouse_pos):
"sends a ray trough the scene and return the nearest entity"
ray_pick = coin.SoRayPickAction(self.render_manager.getViewportRegion())
ray_pick.setPoint(coin.SbVec2s(*mouse_pos))
ray_pick.setRadius(self.pick_radius)
ray_pick.setPickAll(True)
ray_pick.apply(self.render_manager.getSceneGraph())
picked_point = ray_pick.getPickedPointList()
return self.searchEditNode(picked_point)
def searchEditNode(self, picked_point):
"search edit node inside picked point list and retrurn node number"
for point in picked_point:
path = point.getPath()
length = path.getLength()
point = path.getNode(length - 2)
#import DraftTrackers
if hasattr(point,"subElementName") and 'EditNode' in str(point.subElementName.getValue()):
return point
return None
def getEditNodeIndex(self, point):
"get edit node index from given screen position"
if point:
subElement = str(point.subElementName.getValue())
ep = int(subElement[8:])
return ep
else:
return None
#---------------------------------------------------------------------------
# EDIT TRACKERS functions
#---------------------------------------------------------------------------
def setTrackers(self, obj, points=None):
"set Edit Trackers for editpoints collected from self.obj"
if points is None or len(points) == 0:
App.Console.PrintWarning(translate("draft",
"No edit point found for selected object")
+ "\n")
# do not finish if some trackers are still present
if self.trackers == {'object':[]}:
self.finish()
return
self.trackers[obj.Name] = []
if Draft.getType(obj) == "BezCurve":
self.resetTrackersBezier(obj)
else:
if obj.Name in self.trackers:
self.removeTrackers(obj)
for ep in range(len(points)):
self.trackers[obj.Name].append(editTracker(pos=points[ep],name=obj.Name,idx=ep))
def resetTrackers(self, obj):
"reset Edit Trackers and set them again"
self.removeTrackers(obj)
self.setTrackers(obj, self.getEditPoints(obj))
def removeTrackers(self, obj = None):
"reset Edit Trackers and set them again"
if obj:
if obj.Name in self.trackers:
for t in self.trackers[obj.Name]:
t.finalize()
self.trackers[obj.Name] = []
else:
for key in self.trackers.keys():
for t in self.trackers[key]:
t.finalize()
self.trackers = {'object':[]}
def hideTrackers(self, obj=None):
"""hide Edit Trackers
Attributes
----------
obj : FreeCAD object
hides trackers only for given object,
if obj is None, hides all trackers
"""
if obj is None:
for key in self.trackers:
for t in self.trackers[key]:
t.off()
else:
for t in self.trackers[obj.Name]:
t.off()
def showTrackers(self, obj=None):
"""show Edit Trackers
Attributes
----------
obj : FreeCAD object
shows trackers only for given object,
if obj is None, shows all trackers
"""
if obj is None:
for key in self.trackers:
for t in self.trackers[key]:
t.on()
else:
for t in self.trackers[obj.Name]:
t.on()
#---------------------------------------------------------------------------
# PREVIEW
#---------------------------------------------------------------------------
def initGhost(self,obj):
"initialize preview ghost"
if Draft.getType(obj) == "Wire":
return wireTracker(obj.Shape)
elif Draft.getType(obj) == "BSpline":
return bsplineTracker()
elif Draft.getType(obj) == "BezCurve":
return bezcurveTracker()
elif Draft.getType(obj) == "Circle":
return arcTracker()
def updateGhost(self,obj,idx,pt):
if Draft.getType(obj) in ["Wire"]:
self.ghost.on()
pointList = self.applyPlacement(obj.Points)
pointList[idx] = pt
if obj.Closed:
pointList.append(pointList[0])
self.ghost.updateFromPointlist(pointList)
elif Draft.getType(obj) == "BSpline":
self.ghost.on()
pointList = self.applyPlacement(obj.Points)
pointList[idx] = pt
if obj.Closed:
pointList.append(pointList[0])
self.ghost.update(pointList)
elif Draft.getType(obj) == "BezCurve":
self.ghost.on()
plist = self.applyPlacement(obj.Points)
pointList = self.recomputePointsBezier(obj,plist,idx,pt,obj.Degree,moveTrackers=True)
self.ghost.update(pointList,obj.Degree)
elif Draft.getType(obj) == "Circle":
self.ghost.on()
self.ghost.setCenter(obj.getGlobalPlacement().Base)
self.ghost.setRadius(obj.Radius)
if self.obj.FirstAngle == self.obj.LastAngle:
# self.obj is a circle
self.ghost.circle = True
if self.editing == 0:
self.ghost.setCenter(pt)
elif self.editing == 1:
radius = pt.sub(obj.getGlobalPlacement().Base).Length
self.ghost.setRadius(radius)
else:
if self.alt_edit_mode == 0:
# edit by 3 points
if self.editing == 0:
# center point
import DraftVecUtils
p1 = self.invpl.multVec(self.obj.Shape.Vertexes[0].Point)
p2 = self.invpl.multVec(self.obj.Shape.Vertexes[1].Point)
p0 = DraftVecUtils.project(self.invpl.multVec(pt),self.invpl.multVec(self.getArcMid(obj, global_placement=True)))
self.ghost.autoinvert=False
self.ghost.setRadius(p1.sub(p0).Length)
self.ghost.setStartPoint(self.obj.Shape.Vertexes[1].Point)
self.ghost.setEndPoint(self.obj.Shape.Vertexes[0].Point)
self.ghost.setCenter(self.pl.multVec(p0))
return
else:
p1=self.getArcStart(obj,global_placement=True)
p2=self.getArcMid(obj,global_placement=True)
p3=self.getArcEnd(obj,global_placement=True)
if self.editing == 1:
p1=pt
elif self.editing == 3:
p2=pt
elif self.editing == 2:
p3=pt
self.ghost.setBy3Points(p1,p2,p3)
elif self.alt_edit_mode == 1:
# edit by center radius angles
self.ghost.setStartAngle(math.radians(obj.FirstAngle))
self.ghost.setEndAngle(math.radians(obj.LastAngle))
if self.editing == 0:
self.ghost.setCenter(pt)
elif self.editing == 1:
self.ghost.setStartPoint(pt)
elif self.editing == 2:
self.ghost.setEndPoint(pt)
elif self.editing == 3:
self.ghost.setRadius(self.invpl.multVec(pt).Length)
DraftTools.redraw3DView()
def applyPlacement(self,pointList):
if self.pl:
plist = []
for p in pointList:
point = self.pl.multVec(p)
plist.append(point)
return plist
else:
return pointList
def finalizeGhost(self):
try:
self.ghost.finalize()
self.ghost = None
except:
return
#---------------------------------------------------------------------------
# EDIT OBJECT TOOLS : Add/Delete Vertexes
#---------------------------------------------------------------------------
def addPoint(self,event):
"called by action, add point to obj and reset trackers"
pos = event.getPosition()
#self.setSelectState(self.obj, True)
selobjs = Gui.ActiveDocument.ActiveView.getObjectsInfo((pos[0],pos[1]))
if not selobjs:
return
for info in selobjs:
if not info:
return
for o in self.edited_objects:
if o.Name != info["Object"]:
continue
self.obj = o
break
self.setPlacement(self.obj)
if Draft.getType(self.obj) == "Wire" and 'Edge' in info["Component"]:
pt = App.Vector(info["x"], info["y"], info["z"])
self.addPointToWire(self.obj, pt, int(info["Component"][4:]))
elif Draft.getType(self.obj) in ["BSpline", "BezCurve"]: #to fix double vertex created
#pt = self.point
if "x" in info:# prefer "real" 3D location over working-plane-driven one if possible
pt = App.Vector(info["x"], info["y"], info["z"])
else:
continue
self.addPointToCurve(pt,info)
self.obj.recompute()
self.removeTrackers(self.obj)
self.setEditPoints(self.obj)
#self.setSelectState(self.obj, False)
return
def addPointToWire(self, obj, newPoint, edgeIndex):
newPoints = []
hasAddedPoint = False
if hasattr(obj, "ChamferSize") and hasattr(obj, "FilletRadius"):
if obj.ChamferSize > 0 and obj.FilletRadius > 0:
edgeIndex = (edgeIndex +3) / 4
elif obj.ChamferSize > 0 or obj.FilletRadius > 0:
edgeIndex = (edgeIndex +1) / 2
for index, point in enumerate(self.obj.Points):
if index == edgeIndex:
hasAddedPoint = True
newPoints.append(self.invpl.multVec(newPoint))
newPoints.append(point)
if obj.Closed and edgeIndex == len(obj.Points):
# last segment when object is closed
newPoints.append(self.invpl.multVec(newPoint))
obj.Points = newPoints
def addPointToCurve(self,point,info=None):
import Part
if not (Draft.getType(self.obj) in ["BSpline","BezCurve"]):
return
pts = self.obj.Points
if Draft.getType(self.obj) == "BezCurve":
if not info['Component'].startswith('Edge'):
return # clicked control point
edgeindex = int(info['Component'].lstrip('Edge')) -1
wire = self.obj.Shape.Wires[0]
bz = wire.Edges[edgeindex].Curve
param = bz.parameter(point)
seg1 = wire.Edges[edgeindex].copy().Curve
seg2 = wire.Edges[edgeindex].copy().Curve
seg1.segment(seg1.FirstParameter,param)
seg2.segment(param,seg2.LastParameter)
if edgeindex == len(wire.Edges):
#we hit the last segment, we need to fix the degree
degree=wire.Edges[0].Curve.Degree
seg1.increase(degree)
seg2.increase(degree)
edges = wire.Edges[0:edgeindex] + [Part.Edge(seg1),Part.Edge(seg2)] \
+ wire.Edges[edgeindex + 1:]
pts = edges[0].Curve.getPoles()[0:1]
for edge in edges:
pts.extend(edge.Curve.getPoles()[1:])
if self.obj.Closed:
pts.pop()
c = self.obj.Continuity
# assume we have a tangent continuity for an arbitrarily split
# segment, unless it's linear
cont = 1 if (self.obj.Degree >= 2) else 0
self.obj.Continuity = c[0:edgeindex] + [cont] + c[edgeindex:]
else:
if (Draft.getType(self.obj) in ["BSpline"]):
if (self.obj.Closed == True):
curve = self.obj.Shape.Edges[0].Curve
else:
curve = self.obj.Shape.Curve
uNewPoint = curve.parameter(point)
uPoints = []
for p in self.obj.Points:
uPoints.append(curve.parameter(p))
for i in range(len(uPoints) -1):
if ( uNewPoint > uPoints[i] ) and ( uNewPoint < uPoints[i+1] ):
pts.insert(i + 1, self.invpl.multVec(point))
break
# DNC: fix: add points to last segment if curve is closed
if ( self.obj.Closed ) and ( uNewPoint > uPoints[-1] ) :
pts.append(self.invpl.multVec(point))
self.obj.Points = pts
def delPoint(self,event):
pos = event.getPosition()
node = self.getEditNode(pos)
ep = self.getEditNodeIndex(node)
if ep is None:
return App.Console.PrintWarning(translate("draft",
"Node not found")
+ "\n")
doc = App.getDocument(str(node.documentName.getValue()))
self.obj = doc.getObject(str(node.objectName.getValue()))
if self.obj is None:
return
if not (Draft.getType(self.obj) in ["Wire","BSpline","BezCurve"]):
return
if len(self.obj.Points) <= 2:
App.Console.PrintWarning(translate("draft",
"Active object must have more than two points/nodes")
+ "\n")
return
pts = self.obj.Points
pts.pop(ep)
self.obj.Points = pts
if Draft.getType(self.obj) =="BezCurve":
self.obj.Proxy.resetcontinuity(self.obj)
self.obj.recompute()
# don't do tan/sym on DWire/BSpline!
self.removeTrackers(self.obj)
self.setEditPoints(self.obj)
#---------------------------------------------------------------------------
# EDIT OBJECT TOOLS : GENERAL
#---------------------------------------------------------------------------
def setEditPoints(self,obj):
"append given object's editpoints to self.edipoints and set EditTrackers"
self.setPlacement(obj)
self.editpoints = self.getEditPoints(obj)
if self.editpoints: # set trackers and align plane
self.setTrackers(obj, self.editpoints)
self.editpoints = []
def getEditPoints(self, obj):