-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Draft.py
4388 lines (3951 loc) · 177 KB
/
Draft.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: utf-8 -*-
# ***************************************************************************
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.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 *
# * *
# ***************************************************************************
"""Provide the Draft Workbench public programming interface.
The Draft module offers tools to create and manipulate 2D objects.
The functions in this file must be usable without requiring the
graphical user interface.
These functions can be used as the backend for the graphical commands
defined in `DraftTools.py`.
"""
## \addtogroup DRAFT
# \brief Create and manipulate basic 2D objects
#
# This module offers tools to create and manipulate basic 2D objects
#
# The module allows to create 2D geometric objects such as line, rectangle,
# circle, etc., modify these objects by moving, scaling or rotating them,
# and offers a couple of other utilities to manipulate further these objects,
# such as decompose them (downgrade) into smaller elements.
#
# The functionality of the module is divided into GUI tools, usable from the
# visual interface, and corresponding python functions, that can perform
# the same operation programmatically.
#
# @{
import math
import sys
from PySide.QtCore import QT_TRANSLATE_NOOP
import FreeCAD
from FreeCAD import Vector
import DraftVecUtils
import WorkingPlane
from draftutils.translate import translate
if FreeCAD.GuiUp:
import FreeCADGui
import Draft_rc
gui = True
# To prevent complaints from code checkers (flake8)
True if Draft_rc.__name__ else False
else:
gui = False
__title__ = "FreeCAD Draft Workbench"
__author__ = ("Yorik van Havre, Werner Mayer, Martin Burbaum, Ken Cline, "
"Dmitry Chigrin, Daniel Falck")
__url__ = "https://www.freecadweb.org"
# ---------------------------------------------------------------------------
# Backwards compatibility
# ---------------------------------------------------------------------------
from DraftLayer import Layer as _VisGroup
from DraftLayer import ViewProviderLayer as _ViewProviderVisGroup
from DraftLayer import makeLayer
# import DraftFillet
# Fillet = DraftFillet.Fillet
# makeFillet = DraftFillet.makeFillet
# ---------------------------------------------------------------------------
# General functions
# ---------------------------------------------------------------------------
from draftutils.utils import ARROW_TYPES as arrowtypes
from draftutils.utils import stringencodecoin
from draftutils.utils import string_encode_coin
from draftutils.utils import typecheck
from draftutils.utils import type_check
from draftutils.utils import getParamType
from draftutils.utils import get_param_type
from draftutils.utils import getParam
from draftutils.utils import get_param
from draftutils.utils import setParam
from draftutils.utils import set_param
from draftutils.utils import precision
from draftutils.utils import tolerance
from draftutils.utils import epsilon
from draftutils.utils import getRealName
from draftutils.utils import get_real_name
from draftutils.utils import getType
from draftutils.utils import get_type
from draftutils.utils import getObjectsOfType
from draftutils.utils import get_objects_of_type
from draftutils.utils import isClone
from draftutils.utils import is_clone
from draftutils.utils import getGroupNames
from draftutils.utils import get_group_names
from draftutils.utils import ungroup
from draftutils.utils import getGroupContents
from draftutils.utils import get_group_contents
from draftutils.utils import printShape
from draftutils.utils import print_shape
from draftutils.utils import compareObjects
from draftutils.utils import compare_objects
from draftutils.utils import shapify
from draftutils.utils import loadSvgPatterns
from draftutils.utils import load_svg_patterns
from draftutils.utils import svgpatterns
from draftutils.utils import svg_patterns
from draftutils.utils import getMovableChildren
from draftutils.utils import get_movable_children
from draftutils.gui_utils import get3DView
from draftutils.gui_utils import get_3d_view
from draftutils.gui_utils import autogroup
from draftutils.gui_utils import dimSymbol
from draftutils.gui_utils import dim_symbol
from draftutils.gui_utils import dimDash
from draftutils.gui_utils import dim_dash
from draftutils.gui_utils import removeHidden
from draftutils.gui_utils import remove_hidden
from draftutils.gui_utils import formatObject
from draftutils.gui_utils import format_object
from draftutils.gui_utils import getSelection
from draftutils.gui_utils import get_selection
from draftutils.gui_utils import getSelectionEx
from draftutils.gui_utils import get_selection_ex
from draftutils.gui_utils import select
from draftutils.gui_utils import loadTexture
from draftutils.gui_utils import load_texture
#---------------------------------------------------------------------------
# Draft functions
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
# Draft objects
#---------------------------------------------------------------------------
# base object
from draftobjects.base import DraftObject
from draftobjects.base import _DraftObject
# base viewprovider
from draftviewproviders.view_base import ViewProviderDraft
from draftviewproviders.view_base import _ViewProviderDraft
from draftviewproviders.view_base import ViewProviderDraftAlt
from draftviewproviders.view_base import _ViewProviderDraftAlt
from draftviewproviders.view_base import ViewProviderDraftPart
from draftviewproviders.view_base import _ViewProviderDraftPart
# circle
from draftmake.make_circle import make_circle, makeCircle
from draftobjects.circle import Circle, _Circle
# rectangle
from draftmake.make_rectangle import make_rectangle, makeRectangle
from draftobjects.rectangle import Rectangle, _Rectangle
if FreeCAD.GuiUp:
from draftviewproviders.view_rectangle import ViewProviderRectangle
from draftviewproviders.view_rectangle import _ViewProviderRectangle
# polygon
from draftmake.make_polygon import make_polygon, makePolygon
from draftobjects.polygon import Polygon, _Polygon
# wire and line
from draftmake.make_line import make_line, makeLine
from draftmake.make_wire import make_wire, makeWire
from draftobjects.wire import Wire, _Wire
if FreeCAD.GuiUp:
from draftviewproviders.view_wire import ViewProviderWire
from draftviewproviders.view_wire import _ViewProviderWire
# bspline
from draftmake.make_bspline import make_bspline, makeBSpline
from draftobjects.bspline import BSpline, _BSpline
if FreeCAD.GuiUp:
# for compatibility with older versions
_ViewProviderBSpline = ViewProviderWire
# bezcurve
from draftmake.make_bezcurve import make_bezcurve, makeBezCurve
from draftobjects.bezcurve import BezCurve, _BezCurve
if FreeCAD.GuiUp:
# for compatibility with older versions
_ViewProviderBezCurve = ViewProviderWire
#---------------------------------------------------------------------------
# Draft annotation objects
#---------------------------------------------------------------------------
from draftobjects.dimension import make_dimension, make_angular_dimension
from draftobjects.dimension import LinearDimension, AngularDimension
makeDimension = make_dimension
makeAngularDimension = make_angular_dimension
_Dimension = LinearDimension
_AngularDimension = AngularDimension
if gui:
from draftviewproviders.view_dimension import ViewProviderLinearDimension
from draftviewproviders.view_dimension import ViewProviderAngularDimension
_ViewProviderDimension = ViewProviderLinearDimension
_ViewProviderAngularDimension = ViewProviderAngularDimension
from draftobjects.label import make_label
from draftobjects.label import Label
makeLabel = make_label
DraftLabel = Label
if gui:
from draftviewproviders.view_label import ViewProviderLabel
ViewProviderDraftLabel = ViewProviderLabel
from draftobjects.text import make_text
from draftobjects.text import Text
makeText = make_text
DraftText = Text
if gui:
from draftviewproviders.view_text import ViewProviderText
ViewProviderDraftText = ViewProviderText
def convertDraftTexts(textslist=[]):
"""
converts the given Draft texts (or all that is found
in the active document) to the new object
This function was already present at splitting time during v 0.19
"""
if not isinstance(textslist,list):
textslist = [textslist]
if not textslist:
for o in FreeCAD.ActiveDocument.Objects:
if o.TypeId == "App::Annotation":
textslist.append(o)
todelete = []
for o in textslist:
l = o.Label
o.Label = l+".old"
obj = makeText(o.LabelText,point=o.Position)
obj.Label = l
todelete.append(o.Name)
for p in o.InList:
if p.isDerivedFrom("App::DocumentObjectGroup"):
if o in p.Group:
g = p.Group
g.append(obj)
p.Group = g
for n in todelete:
FreeCAD.ActiveDocument.removeObject(n)
def makeWire(pointslist,closed=False,placement=None,face=None,support=None,bs2wire=False):
"""makeWire(pointslist,[closed],[placement]): Creates a Wire object
from the given list of vectors. If closed is True or first
and last points are identical, the wire is closed. If face is
true (and wire is closed), the wire will appear filled. Instead of
a pointslist, you can also pass a Part Wire."""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
import DraftGeomUtils, Part
if not isinstance(pointslist,list):
e = pointslist.Wires[0].Edges
pointslist = Part.Wire(Part.__sortEdges__(e))
nlist = []
for v in pointslist.Vertexes:
nlist.append(v.Point)
if DraftGeomUtils.isReallyClosed(pointslist):
closed = True
pointslist = nlist
if len(pointslist) == 0:
print("Invalid input points: ",pointslist)
#print(pointslist)
#print(closed)
if placement:
typecheck([(placement,FreeCAD.Placement)], "makeWire")
ipl = placement.inverse()
if not bs2wire:
pointslist = [ipl.multVec(p) for p in pointslist]
if len(pointslist) == 2: fname = "Line"
else: fname = "Wire"
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython",fname)
_Wire(obj)
obj.Points = pointslist
obj.Closed = closed
obj.Support = support
if face != None:
obj.MakeFace = face
if placement: obj.Placement = placement
if gui:
_ViewProviderWire(obj.ViewObject)
formatObject(obj)
select(obj)
return obj
def makeCopy(obj,force=None,reparent=False):
"""makeCopy(object): returns an exact copy of an object"""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
if (getType(obj) == "Rectangle") or (force == "Rectangle"):
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
_Rectangle(newobj)
if gui:
_ViewProviderRectangle(newobj.ViewObject)
elif (getType(obj) == "Point") or (force == "Point"):
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
_Point(newobj)
if gui:
_ViewProviderPoint(newobj.ViewObject)
elif (getType(obj) in ["Dimension","LinearDimension"]) or (force == "Dimension"):
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
_Dimension(newobj)
if gui:
_ViewProviderDimension(newobj.ViewObject)
elif (getType(obj) == "Wire") or (force == "Wire"):
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
_Wire(newobj)
if gui:
_ViewProviderWire(newobj.ViewObject)
elif (getType(obj) == "Circle") or (force == "Circle"):
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
_Circle(newobj)
if gui:
_ViewProviderDraft(newobj.ViewObject)
elif (getType(obj) == "Polygon") or (force == "Polygon"):
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
_Polygon(newobj)
if gui:
_ViewProviderDraft(newobj.ViewObject)
elif (getType(obj) == "BSpline") or (force == "BSpline"):
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
_BSpline(newobj)
if gui:
_ViewProviderWire(newobj.ViewObject)
elif (getType(obj) == "Block") or (force == "BSpline"):
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
_Block(newobj)
if gui:
_ViewProviderDraftPart(newobj.ViewObject)
elif (getType(obj) == "DrawingView") or (force == "DrawingView"):
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
_DrawingView(newobj)
elif (getType(obj) == "Structure") or (force == "Structure"):
import ArchStructure
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
ArchStructure._Structure(newobj)
if gui:
ArchStructure._ViewProviderStructure(newobj.ViewObject)
elif (getType(obj) == "Wall") or (force == "Wall"):
import ArchWall
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
ArchWall._Wall(newobj)
if gui:
ArchWall._ViewProviderWall(newobj.ViewObject)
elif (getType(obj) == "Window") or (force == "Window"):
import ArchWindow
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
ArchWindow._Window(newobj)
if gui:
ArchWindow._ViewProviderWindow(newobj.ViewObject)
elif (getType(obj) == "Panel") or (force == "Panel"):
import ArchPanel
newobj = FreeCAD.ActiveDocument.addObject(obj.TypeId,getRealName(obj.Name))
ArchPanel._Panel(newobj)
if gui:
ArchPanel._ViewProviderPanel(newobj.ViewObject)
elif (getType(obj) == "Sketch") or (force == "Sketch"):
newobj = FreeCAD.ActiveDocument.addObject("Sketcher::SketchObject",getRealName(obj.Name))
for geo in obj.Geometry:
newobj.addGeometry(geo)
for con in obj.Constraints:
newobj.addConstraint(con)
elif hasattr(obj, 'Shape'):
newobj = FreeCAD.ActiveDocument.addObject("Part::Feature",getRealName(obj.Name))
newobj.Shape = obj.Shape
else:
print("Error: Object type cannot be copied")
return None
for p in obj.PropertiesList:
if not p in ["Proxy","ExpressionEngine"]:
if p in newobj.PropertiesList:
if not "ReadOnly" in newobj.getEditorMode(p):
try:
setattr(newobj,p,obj.getPropertyByName(p))
except AttributeError:
try:
setattr(newobj,p,obj.getPropertyByName(p).Value)
except AttributeError:
pass
if reparent:
parents = obj.InList
if parents:
for par in parents:
if par.isDerivedFrom("App::DocumentObjectGroup"):
par.addObject(newobj)
else:
for prop in par.PropertiesList:
if getattr(par,prop) == obj:
setattr(par,prop,newobj)
formatObject(newobj,obj)
return newobj
def makeBlock(objectslist):
"""makeBlock(objectslist): Creates a Draft Block from the given objects"""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython","Block")
_Block(obj)
obj.Components = objectslist
if gui:
_ViewProviderDraftPart(obj.ViewObject)
for o in objectslist:
o.ViewObject.Visibility = False
select(obj)
return obj
def makeArray(baseobject,arg1,arg2,arg3,arg4=None,arg5=None,arg6=None,name="Array",use_link=False):
"""makeArray(object,xvector,yvector,xnum,ynum,[name]) for rectangular array, or
makeArray(object,xvector,yvector,zvector,xnum,ynum,znum,[name]) for rectangular array, or
makeArray(object,center,totalangle,totalnum,[name]) for polar array, or
makeArray(object,rdistance,tdistance,axis,center,ncircles,symmetry,[name]) for circular array:
Creates an array of the given object
with, in case of rectangular array, xnum of iterations in the x direction
at xvector distance between iterations, same for y direction with yvector and ynum,
same for z direction with zvector and znum. In case of polar array, center is a vector,
totalangle is the angle to cover (in degrees) and totalnum is the number of objects,
including the original. In case of a circular array, rdistance is the distance of the
circles, tdistance is the distance within circles, axis the rotation-axes, center the
center of rotation, ncircles the number of circles and symmetry the number
of symmetry-axis of the distribution. The result is a parametric Draft Array.
"""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
if use_link:
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",name,_Array(None),None,True)
else:
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",name)
_Array(obj)
obj.Base = baseobject
if arg6:
if isinstance(arg1, (int, float, FreeCAD.Units.Quantity)):
obj.ArrayType = "circular"
obj.RadialDistance = arg1
obj.TangentialDistance = arg2
obj.Axis = arg3
obj.Center = arg4
obj.NumberCircles = arg5
obj.Symmetry = arg6
else:
obj.ArrayType = "ortho"
obj.IntervalX = arg1
obj.IntervalY = arg2
obj.IntervalZ = arg3
obj.NumberX = arg4
obj.NumberY = arg5
obj.NumberZ = arg6
elif arg4:
obj.ArrayType = "ortho"
obj.IntervalX = arg1
obj.IntervalY = arg2
obj.NumberX = arg3
obj.NumberY = arg4
else:
obj.ArrayType = "polar"
obj.Center = arg1
obj.Angle = arg2
obj.NumberPolar = arg3
if gui:
if use_link:
_ViewProviderDraftLink(obj.ViewObject)
else:
_ViewProviderDraftArray(obj.ViewObject)
formatObject(obj,obj.Base)
if len(obj.Base.ViewObject.DiffuseColor) > 1:
obj.ViewObject.Proxy.resetColors(obj.ViewObject)
baseobject.ViewObject.hide()
select(obj)
return obj
def makePathArray(baseobject,pathobject,count,xlate=None,align=False,pathobjsubs=[],use_link=False):
"""makePathArray(docobj,path,count,xlate,align,pathobjsubs,use_link): distribute
count copies of a document baseobject along a pathobject or subobjects of a
pathobject. Optionally translates each copy by FreeCAD.Vector xlate direction
and distance to adjust for difference in shape centre vs shape reference point.
Optionally aligns baseobject to tangent/normal/binormal of path."""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
if use_link:
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","PathArray",_PathArray(None),None,True)
else:
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","PathArray")
_PathArray(obj)
obj.Base = baseobject
obj.PathObj = pathobject
if pathobjsubs:
sl = []
for sub in pathobjsubs:
sl.append((obj.PathObj,sub))
obj.PathSubs = list(sl)
if count > 1:
obj.Count = count
if xlate:
obj.Xlate = xlate
obj.Align = align
if gui:
if use_link:
_ViewProviderDraftLink(obj.ViewObject)
else:
_ViewProviderDraftArray(obj.ViewObject)
formatObject(obj,obj.Base)
if len(obj.Base.ViewObject.DiffuseColor) > 1:
obj.ViewObject.Proxy.resetColors(obj.ViewObject)
baseobject.ViewObject.hide()
select(obj)
return obj
def makePointArray(base, ptlst):
"""makePointArray(base,pointlist):"""
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","PointArray")
_PointArray(obj, base, ptlst)
obj.Base = base
obj.PointList = ptlst
if gui:
_ViewProviderDraftArray(obj.ViewObject)
base.ViewObject.hide()
formatObject(obj,obj.Base)
if len(obj.Base.ViewObject.DiffuseColor) > 1:
obj.ViewObject.Proxy.resetColors(obj.ViewObject)
select(obj)
return obj
def makeEllipse(majradius,minradius,placement=None,face=True,support=None):
"""makeEllipse(majradius,minradius,[placement],[face],[support]): makes
an ellipse with the given major and minor radius, and optionally
a placement."""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython","Ellipse")
_Ellipse(obj)
if minradius > majradius:
majradius,minradius = minradius,majradius
obj.MajorRadius = majradius
obj.MinorRadius = minradius
obj.Support = support
if placement:
obj.Placement = placement
if gui:
_ViewProviderDraft(obj.ViewObject)
#if not face:
# obj.ViewObject.DisplayMode = "Wireframe"
formatObject(obj)
select(obj)
return obj
def extrude(obj,vector,solid=False):
"""makeExtrusion(object,vector): extrudes the given object
in the direction given by the vector. The original object
gets hidden."""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
newobj = FreeCAD.ActiveDocument.addObject("Part::Extrusion","Extrusion")
newobj.Base = obj
newobj.Dir = vector
newobj.Solid = solid
if gui:
obj.ViewObject.Visibility = False
formatObject(newobj,obj)
select(newobj)
return newobj
def joinWires(wires, joinAttempts = 0):
"""joinWires(objects): merges a set of wires where possible, if any of those
wires have a coincident start and end point"""
if joinAttempts > len(wires):
return
joinAttempts += 1
for wire1Index, wire1 in enumerate(wires):
for wire2Index, wire2 in enumerate(wires):
if wire2Index <= wire1Index:
continue
if joinTwoWires(wire1, wire2):
wires.pop(wire2Index)
break
joinWires(wires, joinAttempts)
def joinTwoWires(wire1, wire2):
"""joinTwoWires(object, object): joins two wires if they share a common
point as a start or an end.
BUG: it occasionally fails to join lines even if the lines
visually share a point.
This is a rounding error in the comparison of the shared point;
a small difference will result in the points being considered different
and thus the lines not joining.
Test properly using `DraftVecUtils.equals` because then it will consider
the precision set in the Draft preferences.
"""
wire1AbsPoints = [wire1.Placement.multVec(point) for point in wire1.Points]
wire2AbsPoints = [wire2.Placement.multVec(point) for point in wire2.Points]
if (wire1AbsPoints[0] == wire2AbsPoints[-1] and wire1AbsPoints[-1] == wire2AbsPoints[0]) \
or (wire1AbsPoints[0] == wire2AbsPoints[0] and wire1AbsPoints[-1] == wire2AbsPoints[-1]):
wire2AbsPoints.pop()
wire1.Closed = True
elif wire1AbsPoints[0] == wire2AbsPoints[0]:
wire1AbsPoints = list(reversed(wire1AbsPoints))
elif wire1AbsPoints[0] == wire2AbsPoints[-1]:
wire1AbsPoints = list(reversed(wire1AbsPoints))
wire2AbsPoints = list(reversed(wire2AbsPoints))
elif wire1AbsPoints[-1] == wire2AbsPoints[-1]:
wire2AbsPoints = list(reversed(wire2AbsPoints))
elif wire1AbsPoints[-1] == wire2AbsPoints[0]:
pass
else:
return False
wire2AbsPoints.pop(0)
wire1.Points = [wire1.Placement.inverse().multVec(point) for point in wire1AbsPoints] + [wire1.Placement.inverse().multVec(point) for point in wire2AbsPoints]
FreeCAD.ActiveDocument.removeObject(wire2.Name)
return True
def split(wire, newPoint, edgeIndex):
if getType(wire) != "Wire":
return
elif wire.Closed:
splitClosedWire(wire, edgeIndex)
else:
splitOpenWire(wire, newPoint, edgeIndex)
def splitClosedWire(wire, edgeIndex):
wire.Closed = False
if edgeIndex == len(wire.Points):
makeWire([wire.Placement.multVec(wire.Points[0]),
wire.Placement.multVec(wire.Points[-1])], placement=wire.Placement)
else:
makeWire([wire.Placement.multVec(wire.Points[edgeIndex-1]),
wire.Placement.multVec(wire.Points[edgeIndex])], placement=wire.Placement)
wire.Points = list(reversed(wire.Points[0:edgeIndex])) + list(reversed(wire.Points[edgeIndex:]))
def splitOpenWire(wire, newPoint, edgeIndex):
wire1Points = []
wire2Points = []
for index, point in enumerate(wire.Points):
if index == edgeIndex:
wire1Points.append(wire.Placement.inverse().multVec(newPoint))
wire2Points.append(newPoint)
wire2Points.append(wire.Placement.multVec(point))
elif index < edgeIndex:
wire1Points.append(point)
elif index > edgeIndex:
wire2Points.append(wire.Placement.multVec(point))
wire.Points = wire1Points
makeWire(wire2Points, placement=wire.Placement)
def fuse(object1,object2):
"""fuse(oject1,object2): returns an object made from
the union of the 2 given objects. If the objects are
coplanar, a special Draft Wire is used, otherwise we use
a standard Part fuse."""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
import DraftGeomUtils, Part
# testing if we have holes:
holes = False
fshape = object1.Shape.fuse(object2.Shape)
fshape = fshape.removeSplitter()
for f in fshape.Faces:
if len(f.Wires) > 1:
holes = True
if DraftGeomUtils.isCoplanar(object1.Shape.fuse(object2.Shape).Faces) and not holes:
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython","Fusion")
_Wire(obj)
if gui:
_ViewProviderWire(obj.ViewObject)
obj.Base = object1
obj.Tool = object2
elif holes:
# temporary hack, since Part::Fuse objects don't remove splitters
obj = FreeCAD.ActiveDocument.addObject("Part::Feature","Fusion")
obj.Shape = fshape
else:
obj = FreeCAD.ActiveDocument.addObject("Part::Fuse","Fusion")
obj.Base = object1
obj.Tool = object2
if gui:
object1.ViewObject.Visibility = False
object2.ViewObject.Visibility = False
formatObject(obj,object1)
select(obj)
return obj
def cut(object1,object2):
"""cut(oject1,object2): returns a cut object made from
the difference of the 2 given objects."""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
obj = FreeCAD.ActiveDocument.addObject("Part::Cut","Cut")
obj.Base = object1
obj.Tool = object2
object1.ViewObject.Visibility = False
object2.ViewObject.Visibility = False
formatObject(obj,object1)
select(obj)
return obj
def moveVertex(object, vertex_index, vector):
points = object.Points
points[vertex_index] = points[vertex_index].add(vector)
object.Points = points
def moveEdge(object, edge_index, vector):
moveVertex(object, edge_index, vector)
if isClosedEdge(edge_index, object):
moveVertex(object, 0, vector)
else:
moveVertex(object, edge_index+1, vector)
def copyMovedEdges(arguments):
copied_edges = []
for argument in arguments:
copied_edges.append(copyMovedEdge(argument[0], argument[1], argument[2]))
joinWires(copied_edges)
def copyMovedEdge(object, edge_index, vector):
vertex1 = object.Placement.multVec(object.Points[edge_index]).add(vector)
if isClosedEdge(edge_index, object):
vertex2 = object.Placement.multVec(object.Points[0]).add(vector)
else:
vertex2 = object.Placement.multVec(object.Points[edge_index+1]).add(vector)
return makeLine(vertex1, vertex2)
def copyRotatedEdges(arguments):
copied_edges = []
for argument in arguments:
copied_edges.append(copyRotatedEdge(argument[0], argument[1],
argument[2], argument[3], argument[4]))
joinWires(copied_edges)
def copyRotatedEdge(object, edge_index, angle, center, axis):
vertex1 = rotateVectorFromCenter(
object.Placement.multVec(object.Points[edge_index]),
angle, axis, center)
if isClosedEdge(edge_index, object):
vertex2 = rotateVectorFromCenter(
object.Placement.multVec(object.Points[0]),
angle, axis, center)
else:
vertex2 = rotateVectorFromCenter(
object.Placement.multVec(object.Points[edge_index+1]),
angle, axis, center)
return makeLine(vertex1, vertex2)
def isClosedEdge(edge_index, object):
return edge_index + 1 >= len(object.Points)
def move(objectslist,vector,copy=False):
"""move(objects,vector,[copy]): Moves the objects contained
in objects (that can be an object or a list of objects)
in the direction and distance indicated by the given
vector. If copy is True, the actual objects are not moved, but copies
are created instead. The objects (or their copies) are returned."""
typecheck([(vector,Vector), (copy,bool)], "move")
if not isinstance(objectslist,list): objectslist = [objectslist]
objectslist.extend(getMovableChildren(objectslist))
newobjlist = []
newgroups = {}
objectslist = filterObjectsForModifiers(objectslist, copy)
for obj in objectslist:
newobj = None
# real_vector have been introduced to take into account
# the possibility that object is inside an App::Part
if hasattr(obj, "getGlobalPlacement"):
v_minus_global = obj.getGlobalPlacement().inverse().Rotation.multVec(vector)
real_vector = obj.Placement.Rotation.multVec(v_minus_global)
else:
real_vector = vector
if getType(obj) == "Point":
v = Vector(obj.X,obj.Y,obj.Z)
v = v.add(real_vector)
if copy:
newobj = makeCopy(obj)
else:
newobj = obj
newobj.X = v.x
newobj.Y = v.y
newobj.Z = v.z
elif obj.isDerivedFrom("App::DocumentObjectGroup"):
pass
elif hasattr(obj,'Shape'):
if copy:
newobj = makeCopy(obj)
else:
newobj = obj
pla = newobj.Placement
pla.move(real_vector)
elif getType(obj) == "Annotation":
if copy:
newobj = FreeCAD.ActiveDocument.addObject("App::Annotation",getRealName(obj.Name))
newobj.LabelText = obj.LabelText
if gui:
formatObject(newobj,obj)
else:
newobj = obj
newobj.Position = obj.Position.add(real_vector)
elif getType(obj) == "DraftText":
if copy:
newobj = FreeCAD.ActiveDocument.addObject("App::FeaturePython",getRealName(obj.Name))
DraftText(newobj)
if gui:
ViewProviderDraftText(newobj.ViewObject)
formatObject(newobj,obj)
newobj.Text = obj.Text
newobj.Placement = obj.Placement
if gui:
formatObject(newobj,obj)
else:
newobj = obj
newobj.Placement.Base = obj.Placement.Base.add(real_vector)
elif getType(obj) in ["Dimension","LinearDimension"]:
if copy:
newobj = FreeCAD.ActiveDocument.addObject("App::FeaturePython",getRealName(obj.Name))
_Dimension(newobj)
if gui:
_ViewProviderDimension(newobj.ViewObject)
formatObject(newobj,obj)
else:
newobj = obj
newobj.Start = obj.Start.add(real_vector)
newobj.End = obj.End.add(real_vector)
newobj.Dimline = obj.Dimline.add(real_vector)
else:
if copy and obj.isDerivedFrom("Mesh::Feature"):
print("Mesh copy not supported at the moment") # TODO
newobj = obj
if "Placement" in obj.PropertiesList:
pla = obj.Placement
pla.move(real_vector)
if newobj is not None:
newobjlist.append(newobj)
if copy:
for p in obj.InList:
if p.isDerivedFrom("App::DocumentObjectGroup") and (p in objectslist):
g = newgroups.setdefault(p.Name,FreeCAD.ActiveDocument.addObject(p.TypeId,p.Name))
g.addObject(newobj)
break
if getType(p) == "Layer":
p.Proxy.addObject(p,newobj)
if copy and getParam("selectBaseObjects",False):
select(objectslist)
else:
select(newobjlist)
if len(newobjlist) == 1: return newobjlist[0]
return newobjlist
def array(objectslist,arg1,arg2,arg3,arg4=None,arg5=None,arg6=None):
"""array(objectslist,xvector,yvector,xnum,ynum) for rectangular array,
array(objectslist,xvector,yvector,zvector,xnum,ynum,znum) for rectangular array,
or array(objectslist,center,totalangle,totalnum) for polar array: Creates an array
of the objects contained in list (that can be an object or a list of objects)
with, in case of rectangular array, xnum of iterations in the x direction
at xvector distance between iterations, and same for y and z directions with yvector
and ynum and zvector and znum. In case of polar array, center is a vector, totalangle
is the angle to cover (in degrees) and totalnum is the number of objects, including
the original.
This function creates an array of independent objects. Use makeArray() to create a
parametric array object."""
def rectArray(objectslist,xvector,yvector,xnum,ynum):
typecheck([(xvector,Vector), (yvector,Vector), (xnum,int), (ynum,int)], "rectArray")
if not isinstance(objectslist,list): objectslist = [objectslist]
for xcount in range(xnum):
currentxvector=Vector(xvector).multiply(xcount)
if not xcount==0:
move(objectslist,currentxvector,True)
for ycount in range(ynum):
currentxvector=FreeCAD.Base.Vector(currentxvector)
currentyvector=currentxvector.add(Vector(yvector).multiply(ycount))
if not ycount==0:
move(objectslist,currentyvector,True)
def rectArray2(objectslist,xvector,yvector,zvector,xnum,ynum,znum):
typecheck([(xvector,Vector), (yvector,Vector), (zvector,Vector),(xnum,int), (ynum,int),(znum,int)], "rectArray2")
if not isinstance(objectslist,list): objectslist = [objectslist]
for xcount in range(xnum):
currentxvector=Vector(xvector).multiply(xcount)
if not xcount==0:
move(objectslist,currentxvector,True)
for ycount in range(ynum):
currentxvector=FreeCAD.Base.Vector(currentxvector)
currentyvector=currentxvector.add(Vector(yvector).multiply(ycount))
if not ycount==0:
move(objectslist,currentyvector,True)
for zcount in range(znum):
currentzvector=currentyvector.add(Vector(zvector).multiply(zcount))
if not zcount==0:
move(objectslist,currentzvector,True)
def polarArray(objectslist,center,angle,num):
typecheck([(center,Vector), (num,int)], "polarArray")
if not isinstance(objectslist,list): objectslist = [objectslist]
fraction = float(angle)/num
for i in range(num):
currangle = fraction + (i*fraction)
rotate(objectslist,currangle,center,copy=True)
if arg6:
rectArray2(objectslist,arg1,arg2,arg3,arg4,arg5,arg6)
elif arg4:
rectArray(objectslist,arg1,arg2,arg3,arg4)
else:
polarArray(objectslist,arg1,arg2,arg3)
def filterObjectsForModifiers(objects, isCopied=False):
filteredObjects = []
for object in objects:
if hasattr(object, "MoveBase") and object.MoveBase and object.Base:
parents = []
for parent in object.Base.InList:
if parent.isDerivedFrom("Part::Feature"):
parents.append(parent.Name)
if len(parents) > 1:
warningMessage = translate("draft","%s shares a base with %d other objects. Please check if you want to modify this.") % (object.Name,len(parents) - 1)
FreeCAD.Console.PrintError(warningMessage)
if FreeCAD.GuiUp:
FreeCADGui.getMainWindow().showMessage(warningMessage, 0)
filteredObjects.append(object.Base)
elif hasattr(object,"Placement") and object.getEditorMode("Placement") == ["ReadOnly"] and not isCopied:
FreeCAD.Console.PrintError(translate("Draft","%s cannot be modified because its placement is readonly.") % obj.Name)
continue
else:
filteredObjects.append(object)
return filteredObjects
def rotateVertex(object, vertex_index, angle, center, axis):
points = object.Points
points[vertex_index] = object.Placement.inverse().multVec(
rotateVectorFromCenter(
object.Placement.multVec(points[vertex_index]),
angle, axis, center))
object.Points = points