/
Draft.py
6729 lines (6132 loc) · 285 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
def makeCircle(radius, placement=None, face=None, startangle=None, endangle=None, support=None):
"""makeCircle(radius,[placement,face,startangle,endangle])
or makeCircle(edge,[face]):
Creates a circle object with given radius. If placement is given, it is
used. If face is False, the circle is shown as a
wireframe, otherwise as a face. If startangle AND endangle are given
(in degrees), they are used and the object appears as an arc. If an edge
is passed, its Curve must be a Part.Circle"""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
import Part, DraftGeomUtils
if placement: typecheck([(placement,FreeCAD.Placement)], "makeCircle")
if startangle != endangle:
n = "Arc"
else:
n = "Circle"
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython",n)
_Circle(obj)
if face != None:
obj.MakeFace = face
if isinstance(radius,Part.Edge):
edge = radius
if DraftGeomUtils.geomType(edge) == "Circle":
obj.Radius = edge.Curve.Radius
placement = FreeCAD.Placement(edge.Placement)
delta = edge.Curve.Center.sub(placement.Base)
placement.move(delta)
# Rotation of the edge
rotOk = FreeCAD.Rotation(edge.Curve.XAxis, edge.Curve.YAxis, edge.Curve.Axis, "ZXY")
placement.Rotation = rotOk
if len(edge.Vertexes) > 1:
v0 = edge.Curve.XAxis
v1 = (edge.Vertexes[0].Point).sub(edge.Curve.Center)
v2 = (edge.Vertexes[-1].Point).sub(edge.Curve.Center)
# Angle between edge.Curve.XAxis and the vector from center to start of arc
a0 = math.degrees(FreeCAD.Vector.getAngle(v0, v1))
# Angle between edge.Curve.XAxis and the vector from center to end of arc
a1 = math.degrees(FreeCAD.Vector.getAngle(v0, v2))
obj.FirstAngle = a0
obj.LastAngle = a1
else:
obj.Radius = radius
if (startangle != None) and (endangle != None):
if startangle == -0: startangle = 0
obj.FirstAngle = startangle
obj.LastAngle = endangle
obj.Support = support
if placement: obj.Placement = placement
if gui:
_ViewProviderDraft(obj.ViewObject)
formatObject(obj)
select(obj)
return obj
def makeRectangle(length, height, placement=None, face=None, support=None):
"""makeRectangle(length,width,[placement],[face]): Creates a Rectangle
object with length in X direction and height in Y direction.
If a placement is given, it is used. If face is False, the
rectangle is shown as a wireframe, otherwise as a face."""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
if placement: typecheck([(placement,FreeCAD.Placement)], "makeRectangle")
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython","Rectangle")
_Rectangle(obj)
obj.Length = length
obj.Height = height
obj.Support = support
if face != None:
obj.MakeFace = face
if placement: obj.Placement = placement
if gui:
_ViewProviderRectangle(obj.ViewObject)
formatObject(obj)
select(obj)
return obj
def makeDimension(p1,p2,p3=None,p4=None):
"""makeDimension(p1,p2,[p3]) or makeDimension(object,i1,i2,p3)
or makeDimension(objlist,indices,p3): Creates a Dimension object with
the dimension line passign through p3.The current line width and color
will be used. There are multiple ways to create a dimension, depending on
the arguments you pass to it:
- (p1,p2,p3): creates a standard dimension from p1 to p2
- (object,i1,i2,p3): creates a linked dimension to the given object,
measuring the distance between its vertices indexed i1 and i2
- (object,i1,mode,p3): creates a linked dimension
to the given object, i1 is the index of the (curved) edge to measure,
and mode is either "radius" or "diameter".
"""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython","Dimension")
_Dimension(obj)
if gui:
_ViewProviderDimension(obj.ViewObject)
if isinstance(p1,Vector) and isinstance(p2,Vector):
obj.Start = p1
obj.End = p2
if not p3:
p3 = p2.sub(p1)
p3.multiply(0.5)
p3 = p1.add(p3)
elif isinstance(p2,int) and isinstance(p3,int):
l = []
idx = (p2,p3)
l.append((p1,"Vertex"+str(p2+1)))
l.append((p1,"Vertex"+str(p3+1)))
obj.LinkedGeometry = l
obj.Support = p1
p3 = p4
if not p3:
v1 = obj.Base.Shape.Vertexes[idx[0]].Point
v2 = obj.Base.Shape.Vertexes[idx[1]].Point
p3 = v2.sub(v1)
p3.multiply(0.5)
p3 = v1.add(p3)
elif isinstance(p3,str):
l = []
l.append((p1,"Edge"+str(p2+1)))
if p3 == "radius":
#l.append((p1,"Center"))
if FreeCAD.GuiUp:
obj.ViewObject.Override = "R $dim"
obj.Diameter = False
elif p3 == "diameter":
#l.append((p1,"Diameter"))
if FreeCAD.GuiUp:
obj.ViewObject.Override = "Ø $dim"
obj.Diameter = True
obj.LinkedGeometry = l
obj.Support = p1
p3 = p4
if not p3:
p3 = p1.Shape.Edges[p2].Curve.Center.add(Vector(1,0,0))
obj.Dimline = p3
if hasattr(FreeCAD,"DraftWorkingPlane"):
normal = FreeCAD.DraftWorkingPlane.axis
else:
normal = FreeCAD.Vector(0,0,1)
if gui:
# invert the normal if we are viewing it from the back
vnorm = get3DView().getViewDirection()
if vnorm.getAngle(normal) < math.pi/2:
normal = normal.negative()
obj.Normal = normal
if gui:
formatObject(obj)
select(obj)
return obj
def makeAngularDimension(center,angles,p3,normal=None):
"""makeAngularDimension(center,angle1,angle2,p3,[normal]): creates an angular Dimension
from the given center, with the given list of angles, passing through p3.
"""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython","Dimension")
_AngularDimension(obj)
obj.Center = center
for a in range(len(angles)):
if angles[a] > 2*math.pi:
angles[a] = angles[a]-(2*math.pi)
obj.FirstAngle = math.degrees(angles[1])
obj.LastAngle = math.degrees(angles[0])
obj.Dimline = p3
if not normal:
if hasattr(FreeCAD,"DraftWorkingPlane"):
normal = FreeCAD.DraftWorkingPlane.axis
else:
normal = Vector(0,0,1)
if gui:
# invert the normal if we are viewing it from the back
vnorm = get3DView().getViewDirection()
if vnorm.getAngle(normal) < math.pi/2:
normal = normal.negative()
obj.Normal = normal
if gui:
_ViewProviderAngularDimension(obj.ViewObject)
formatObject(obj)
select(obj)
return obj
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 makePolygon(nfaces,radius=1,inscribed=True,placement=None,face=None,support=None):
"""makePolgon(nfaces,[radius],[inscribed],[placement],[face]): Creates a
polygon object with the given number of faces and the radius.
if inscribed is False, the polygon is circumscribed around a circle
with the given radius, otherwise it is inscribed. If face is True,
the resulting shape is displayed as a face, otherwise as a wireframe.
"""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
if nfaces < 3: return None
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython","Polygon")
_Polygon(obj)
obj.FacesNumber = nfaces
obj.Radius = radius
if face != None:
obj.MakeFace = face
if inscribed:
obj.DrawMode = "inscribed"
else:
obj.DrawMode = "circumscribed"
obj.Support = support
if placement: obj.Placement = placement
if gui:
_ViewProviderDraft(obj.ViewObject)
formatObject(obj)
select(obj)
return obj
def makeLine(p1,p2=None):
"""makeLine(p1,p2): Creates a line between p1 and p2.
makeLine(LineSegment): Creates a line from a Part.LineSegment
makeLine(Shape): Creates a line from first vertex to last vertex of the given shape"""
if not p2:
if hasattr(p1,"StartPoint") and hasattr(p1,"EndPoint"):
p2 = p1.EndPoint
p1 = p1.StartPoint
elif hasattr(p1,"Vertexes"):
p2 = p1.Vertexes[-1].Point
p1 = p1.Vertexes[0].Point
else:
FreeCAD.Console.PrintError("Unable to create a line from the given data\n")
return
obj = makeWire([p1,p2])
return obj
def makeBSpline(pointslist,closed=False,placement=None,face=None,support=None):
"""makeBSpline(pointslist,[closed],[placement]): Creates a B-Spline 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
if not isinstance(pointslist,list):
nlist = []
for v in pointslist.Vertexes:
nlist.append(v.Point)
pointslist = nlist
if len(pointslist) < 2:
FreeCAD.Console.PrintError(translate("draft","Draft.makeBSpline: not enough points")+"\n")
return
if (pointslist[0] == pointslist[-1]):
if len(pointslist) > 2:
closed = True
pointslist.pop()
FreeCAD.Console.PrintWarning(translate("draft","Draft.makeBSpline: Equal endpoints forced Closed")+"\n")
else: # len == 2 and first == last GIGO
FreeCAD.Console.PrintError(translate("draft","Draft.makeBSpline: Invalid pointslist")+"\n")
return
# should have sensible parms from here on
if placement: typecheck([(placement,FreeCAD.Placement)], "makeBSpline")
if len(pointslist) == 2: fname = "Line"
else: fname = "BSpline"
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython",fname)
_BSpline(obj)
obj.Closed = closed
obj.Points = pointslist
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 makeBezCurve(pointslist,closed=False,placement=None,face=None,support=None,degree=None):
"""makeBezCurve(pointslist,[closed],[placement]): Creates a Bezier Curve object
from the given list of vectors. Instead of a pointslist, you can also pass a Part Wire."""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
if not isinstance(pointslist,list):
nlist = []
for v in pointslist.Vertexes:
nlist.append(v.Point)
pointslist = nlist
if placement: typecheck([(placement,FreeCAD.Placement)], "makeBezCurve")
if len(pointslist) == 2: fname = "Line"
else: fname = "BezCurve"
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython",fname)
_BezCurve(obj)
obj.Points = pointslist
if degree:
obj.Degree = degree
else:
import Part
obj.Degree = min((len(pointslist)-(1 * (not closed))),
Part.BezierCurve().MaxDegree)
obj.Closed = closed
obj.Support = support
if face != None:
obj.MakeFace = face
obj.Proxy.resetcontinuity(obj)
if placement: obj.Placement = placement
if gui:
_ViewProviderWire(obj.ViewObject)
# if not face: obj.ViewObject.DisplayMode = "Wireframe"
# obj.ViewObject.DisplayMode = "Wireframe"
formatObject(obj)
select(obj)
return obj
def makeText(stringslist,point=Vector(0,0,0),screen=False):
"""makeText(strings,[point],[screen]): Creates a Text object at the given point,
containing the strings given in the strings list, one string by line (strings
can also be one single string). The current color and text height and font
specified in preferences are used.
If screen is True, the text always faces the view direction."""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
typecheck([(point,Vector)], "makeText")
if not isinstance(stringslist,list): stringslist = [stringslist]
obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython","Text")
DraftText(obj)
obj.Text = stringslist
obj.Placement.Base = point
if FreeCAD.GuiUp:
ViewProviderDraftText(obj.ViewObject)
if screen:
obj.ViewObject.DisplayMode = "3D text"
h = getParam("textheight",0.20)
if screen:
h = h*10
obj.ViewObject.FontSize = h
obj.ViewObject.FontName = getParam("textfont","")
obj.ViewObject.LineSpacing = 1
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) == "Dimension") 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"""
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):