-
Notifications
You must be signed in to change notification settings - Fork 14
/
oDraft.py
6851 lines (6342 loc) · 291 KB
/
oDraft.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 <[email protected]>, Ken Cline <[email protected]> *
#* *
#* 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 *
#* *
#***************************************************************************
#from __future__ import division
__title__="FreeCAD Draft Workbench"
__author__ = "Yorik van Havre, Werner Mayer, Martin Burbaum, Ken Cline, Dmitry Chigrin, Daniel Falck"
__url__ = "http://www.freecadweb.org"
## \addtogroup DRAFT
# \brief Create and manipulate basic 2D objects
#
# This module offers a range of 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
# FreeCAD interface, and corresponding python functions, that can perform the same
# operation programmatically.
#
# @{
'''The Draft module offers a range of tools to create and manipulate basic 2D objects'''
import FreeCAD, math, sys, os, DraftVecUtils, Draft_rc, WorkingPlane
from FreeCAD import Vector
if FreeCAD.GuiUp:
import FreeCADGui
from PySide import QtCore
from PySide.QtCore import QT_TRANSLATE_NOOP
gui = True
#from DraftGui import translate
else:
def QT_TRANSLATE_NOOP(ctxt,txt):
return txt
#print("FreeCAD Gui not present. Draft module will have some features disabled.")
gui = False
def translate(ctx,txt):
return txt
arrowtypes = ["Dot","Circle","Arrow","Tick","Tick-2"]
def msg(text=None,mode=None):
"prints the given message on the FreeCAD status bar"
if not text: FreeCAD.Console.PrintMessage("")
else:
if mode == 'warning':
FreeCAD.Console.PrintWarning(text)
elif mode == 'error':
FreeCAD.Console.PrintError(text)
else:
FreeCAD.Console.PrintMessage(text)
#---------------------------------------------------------------------------
# General functions
#---------------------------------------------------------------------------
def stringencodecoin(ustr):
"""stringencodecoin(str): Encodes a unicode object to be used as a string in coin"""
try:
from pivy import coin
coin4 = coin.COIN_MAJOR_VERSION >= 4
except (ImportError, AttributeError):
coin4 = False
if coin4:
return ustr.encode('utf-8')
else:
return ustr.encode('latin1')
def typecheck (args_and_types, name="?"):
"typecheck([arg1,type),(arg2,type),...]): checks arguments types"
for v,t in args_and_types:
if not isinstance (v,t):
w = "typecheck[" + str(name) + "]: "
w += str(v) + " is not " + str(t) + "\n"
FreeCAD.Console.PrintWarning(w)
raise TypeError("Draft." + str(name))
def getParamType(param):
if param in ["dimsymbol","dimPrecision","dimorientation","precision","defaultWP",
"snapRange","gridEvery","linewidth","UiMode","modconstrain","modsnap",
"maxSnapEdges","modalt","HatchPatternResolution","snapStyle",
"dimstyle","gridSize"]:
return "int"
elif param in ["constructiongroupname","textfont","patternFile","template",
"snapModes","FontFile","ClonePrefix","labeltype"]:
return "string"
elif param in ["textheight","tolerance","gridSpacing","arrowsize","extlines","dimspacing"]:
return "float"
elif param in ["selectBaseObjects","alwaysSnap","grid","fillmode","saveonexit","maxSnap",
"SvgLinesBlack","dxfStdSize","showSnapBar","hideSnapBar","alwaysShowGrid",
"renderPolylineWidth","showPlaneTracker","UsePartPrimitives","DiscretizeEllipses",
"showUnit"]:
return "bool"
elif param in ["color","constructioncolor","snapcolor"]:
return "unsigned"
else:
return None
def getParam(param,default=None):
"getParam(parameterName): returns a Draft parameter value from the current config"
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")
t = getParamType(param)
#print("getting param ",param, " of type ",t, " default: ",str(default))
if t == "int":
if default == None:
default = 0
return p.GetInt(param,default)
elif t == "string":
if default == None:
default = ""
return p.GetString(param,default)
elif t == "float":
if default == None:
default = 0
return p.GetFloat(param,default)
elif t == "bool":
if default == None:
default = False
return p.GetBool(param,default)
elif t == "unsigned":
if default == None:
default = 0
return p.GetUnsigned(param,default)
else:
return None
def setParam(param,value):
"setParam(parameterName,value): sets a Draft parameter with the given value"
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")
t = getParamType(param)
if t == "int": p.SetInt(param,value)
elif t == "string": p.SetString(param,value)
elif t == "float": p.SetFloat(param,value)
elif t == "bool": p.SetBool(param,value)
elif t == "unsigned": p.SetUnsigned(param,value)
def precision():
"precision(): returns the precision value from Draft user settings"
return getParam("precision",6)
def tolerance():
"tolerance(): returns the tolerance value from Draft user settings"
return getParam("tolerance",0.05)
def epsilon():
''' epsilon(): returns a small number based on Draft.tolerance() for use in
floating point comparisons. Use with caution. '''
return (1.0/(10.0**tolerance()))
def getRealName(name):
"getRealName(string): strips the trailing numbers from a string name"
for i in range(1,len(name)):
if not name[-i] in '1234567890':
return name[:len(name)-(i-1)]
return name
def getType(obj):
"getType(object): returns the Draft type of the given object"
import Part
if not obj:
return None
if isinstance(obj,Part.Shape):
return "Shape"
if "Proxy" in obj.PropertiesList:
if hasattr(obj.Proxy,"Type"):
return obj.Proxy.Type
if obj.isDerivedFrom("Sketcher::SketchObject"):
return "Sketch"
if (obj.TypeId == "Part::Line"):
return "Part::Line"
if obj.isDerivedFrom("Part::Feature"):
return "Part"
if (obj.TypeId == "App::Annotation"):
return "Annotation"
if obj.isDerivedFrom("Mesh::Feature"):
return "Mesh"
if obj.isDerivedFrom("Points::Feature"):
return "Points"
if (obj.TypeId == "App::DocumentObjectGroup"):
return "Group"
return "Unknown"
def getObjectsOfType(objectslist,typ):
"""getObjectsOfType(objectslist,typ): returns a list of objects of type "typ" found
in the given object list"""
objs = []
for o in objectslist:
if getType(o) == typ:
objs.append(o)
return objs
def get3DView():
"get3DView(): returns the current view if it is 3D, or the first 3D view found, or None"
if FreeCAD.GuiUp:
import FreeCADGui
v = FreeCADGui.ActiveDocument.ActiveView
if str(type(v)) == "<type 'View3DInventorPy'>":
return v
v = FreeCADGui.ActiveDocument.mdiViewsOfType("Gui::View3DInventor")
if v:
return v[0]
return None
def isClone(obj,objtype,recursive=False):
"""isClone(obj,objtype,[recursive]): returns True if the given object is
a clone of an object of the given type. If recursive is True, also check if
the clone is a clone of clone (of clone...) of the given type."""
if isinstance(objtype,list):
return any([isClone(obj,t,recursive) for t in objtype])
if getType(obj) == "Clone":
if len(obj.Objects) == 1:
if getType(obj.Objects[0]) == objtype:
return True
elif recursive and (getType(obj.Objects[0]) == "Clone"):
return isClone(obj.Objects[0],objtype,recursive)
elif hasattr(obj,"CloneOf"):
if obj.CloneOf:
return True
return False
def getGroupNames():
"returns a list of existing groups in the document"
glist = []
doc = FreeCAD.ActiveDocument
for obj in doc.Objects:
if obj.isDerivedFrom("App::DocumentObjectGroup") or (getType(obj) in ["Floor","Building","Site"]):
glist.append(obj.Name)
return glist
def ungroup(obj):
"removes the current object from any group it belongs to"
for g in getGroupNames():
grp = FreeCAD.ActiveDocument.getObject(g)
if obj in grp.Group:
g = grp.Group
g.remove(obj)
grp.Group = g
def autogroup(obj):
"adds a given object to the autogroup, if applicable"
if FreeCAD.GuiUp:
if hasattr(FreeCADGui,"draftToolBar"):
if hasattr(FreeCADGui.draftToolBar,"autogroup") and (not FreeCADGui.draftToolBar.isConstructionMode()):
if FreeCADGui.draftToolBar.autogroup != None:
g = FreeCAD.ActiveDocument.getObject(FreeCADGui.draftToolBar.autogroup)
if g:
found = False
for o in g.Group:
if o.Name == obj.Name:
found = True
if not found:
gr = g.Group
gr.append(obj)
g.Group = gr
def dimSymbol(symbol=None,invert=False):
"returns the current dim symbol from the preferences as a pivy SoMarkerSet"
if symbol == None:
symbol = getParam("dimsymbol",0)
from pivy import coin
if symbol == 0:
return coin.SoSphere()
elif symbol == 1:
marker = coin.SoMarkerSet()
marker.markerIndex = coin.SoMarkerSet.CIRCLE_LINE_9_9
return marker
elif symbol == 2:
marker = coin.SoSeparator()
t = coin.SoTransform()
t.translation.setValue((0,-2,0))
t.center.setValue((0,2,0))
if invert:
t.rotation.setValue(coin.SbVec3f((0,0,1)),-math.pi/2)
else:
t.rotation.setValue(coin.SbVec3f((0,0,1)),math.pi/2)
c = coin.SoCone()
c.height.setValue(4)
marker.addChild(t)
marker.addChild(c)
return marker
elif symbol == 3:
marker = coin.SoSeparator()
c = coin.SoCoordinate3()
c.point.setValues([(-1,-2,0),(0,2,0),(1,2,0),(0,-2,0)])
f = coin.SoFaceSet()
marker.addChild(c)
marker.addChild(f)
return marker
elif symbol == 4:
marker = coin.SoSeparator()
v = coin.SoVertexProperty()
v.vertex.set1Value(0, -1.5,-1.5,0)
v.vertex.set1Value(1, 1.5,1.5,0)
l = coin.SoLineSet()
l.vertexProperty = v
marker.addChild(l)
return marker
else:
print("Draft.dimsymbol: Not implemented")
return coin.SoSphere()
def shapify(obj):
'''shapify(object): transforms a parametric shape object into
non-parametric and returns the new object'''
if not (obj.isDerivedFrom("Part::Feature")): return None
if not "Shape" in obj.PropertiesList: return None
shape = obj.Shape
if len(shape.Faces) == 1:
name = "Face"
elif len(shape.Solids) == 1:
name = "Solid"
elif len(shape.Solids) > 1:
name = "Compound"
elif len(shape.Faces) > 1:
name = "Shell"
elif len(shape.Wires) == 1:
name = "Wire"
elif len(shape.Edges) == 1:
import DraftGeomUtils
if DraftGeomUtils.geomType(shape.Edges[0]) == "Line":
name = "Line"
else:
name = "Circle"
else:
name = getRealName(obj.Name)
FreeCAD.ActiveDocument.removeObject(obj.Name)
newobj = FreeCAD.ActiveDocument.addObject("Part::Feature",name)
newobj.Shape = shape
FreeCAD.ActiveDocument.recompute()
return newobj
def getGroupContents(objectslist,walls=False,addgroups=False,spaces=False):
'''getGroupContents(objectlist,[walls,addgroups]): if any object of the given list
is a group, its content is appended to the list, which is returned. If walls is True,
walls and structures are also scanned for included windows or rebars. If addgroups
is true, the group itself is also included in the list.'''
def getWindows(obj):
l = []
if getType(obj) in ["Wall","Structure"]:
for o in obj.OutList:
l.extend(getWindows(o))
elif (getType(obj) in ["Window","Rebar"]) or isClone(obj,["Window","Rebar"]):
l.append(obj)
return l
newlist = []
if not isinstance(objectslist,list):
objectslist = [objectslist]
for obj in objectslist:
if obj:
if obj.isDerivedFrom("App::DocumentObjectGroup") or ((getType(obj) in ["Space","Site"]) and hasattr(obj,"Group")):
if getType(obj) == "Site":
if obj.Shape:
newlist.append(obj)
if obj.isDerivedFrom("Drawing::FeaturePage"):
# skip if the group is a page
newlist.append(obj)
else:
if addgroups or (spaces and (getType(obj) == "Space")):
newlist.append(obj)
newlist.extend(getGroupContents(obj.Group,walls,addgroups))
else:
#print("adding ",obj.Name)
newlist.append(obj)
if walls:
newlist.extend(getWindows(obj))
# cleaning possible duplicates
cleanlist = []
for obj in newlist:
if not obj in cleanlist:
cleanlist.append(obj)
return cleanlist
def removeHidden(objectslist):
"""removeHidden(objectslist): removes hidden objects from the list"""
newlist = objectslist[:]
for o in objectslist:
if o.ViewObject:
if not o.ViewObject.isVisible():
newlist.remove(o)
return newlist
def printShape(shape):
"""prints detailed information of a shape"""
print("solids: ", len(shape.Solids))
print("faces: ", len(shape.Faces))
print("wires: ", len(shape.Wires))
print("edges: ", len(shape.Edges))
print("verts: ", len(shape.Vertexes))
if shape.Faces:
for f in range(len(shape.Faces)):
print("face ",f,":")
for v in shape.Faces[f].Vertexes:
print(" ",v.Point)
elif shape.Wires:
for w in range(len(shape.Wires)):
print("wire ",w,":")
for v in shape.Wires[w].Vertexes:
print(" ",v.Point)
else:
for v in shape.Vertexes:
print(" ",v.Point)
def compareObjects(obj1,obj2):
"Prints the differences between 2 objects"
if obj1.TypeId != obj2.TypeId:
print(obj1.Name + " and " + obj2.Name + " are of different types")
elif getType(obj1) != getType(obj2):
print(obj1.Name + " and " + obj2.Name + " are of different types")
else:
for p in obj1.PropertiesList:
if p in obj2.PropertiesList:
if p in ["Shape","Label"]:
pass
elif p == "Placement":
delta = str((obj1.Placement.Base.sub(obj2.Placement.Base)).Length)
print("Objects have different placements. Distance between the 2: " + delta + " units")
else:
if getattr(obj1,p) != getattr(obj2,p):
print("Property " + p + " has a different value")
else:
print("Property " + p + " doesn't exist in one of the objects")
def formatObject(target,origin=None):
'''
formatObject(targetObject,[originObject]): This function applies
to the given target object the current properties
set on the toolbar (line color and line width),
or copies the properties of another object if given as origin.
It also places the object in construction group if needed.
'''
if not target:
return
obrep = target.ViewObject
if not obrep:
return
ui = None
if gui:
if hasattr(FreeCADGui,"draftToolBar"):
ui = FreeCADGui.draftToolBar
if ui:
doc = FreeCAD.ActiveDocument
if ui.isConstructionMode():
col = fcol = ui.getDefaultColor("constr")
gname = getParam("constructiongroupname","Construction")
grp = doc.getObject(gname)
if not grp:
grp = doc.addObject("App::DocumentObjectGroup",gname)
grp.addObject(target)
if hasattr(obrep,"Transparency"):
obrep.Transparency = 80
else:
col = ui.getDefaultColor("line")
fcol = ui.getDefaultColor("face")
col = (float(col[0]),float(col[1]),float(col[2]),0.0)
fcol = (float(fcol[0]),float(fcol[1]),float(fcol[2]),0.0)
lw = ui.linewidth
fs = ui.fontsize
if not origin or not hasattr(origin,'ViewObject'):
if "FontSize" in obrep.PropertiesList: obrep.FontSize = fs
if "TextColor" in obrep.PropertiesList: obrep.TextColor = col
if "LineWidth" in obrep.PropertiesList: obrep.LineWidth = lw
if "PointColor" in obrep.PropertiesList: obrep.PointColor = col
if "LineColor" in obrep.PropertiesList: obrep.LineColor = col
if "ShapeColor" in obrep.PropertiesList: obrep.ShapeColor = fcol
else:
matchrep = origin.ViewObject
for p in matchrep.PropertiesList:
if not p in ["DisplayMode","BoundingBox","Proxy","RootNode","Visibility"]:
if p in obrep.PropertiesList:
if not obrep.getEditorMode(p):
if hasattr(getattr(matchrep,p),"Value"):
val = getattr(matchrep,p).Value
else:
val = getattr(matchrep,p)
setattr(obrep,p,val)
if matchrep.DisplayMode in obrep.listDisplayModes():
obrep.DisplayMode = matchrep.DisplayMode
if hasattr(matchrep,"DiffuseColor") and hasattr(obrep,"DiffuseColor"):
if matchrep.DiffuseColor:
FreeCAD.ActiveDocument.recompute()
obrep.DiffuseColor = matchrep.DiffuseColor
def getSelection():
"getSelection(): returns the current FreeCAD selection"
if gui:
return FreeCADGui.Selection.getSelection()
return None
def getSelectionEx():
"getSelectionEx(): returns the current FreeCAD selection (with subobjects)"
if gui:
return FreeCADGui.Selection.getSelectionEx()
return None
def select(objs=None):
"select(object): deselects everything and selects only the passed object or list"
if gui:
FreeCADGui.Selection.clearSelection()
if objs:
if not isinstance(objs,list):
objs = [objs]
for obj in objs:
if obj:
FreeCADGui.Selection.addSelection(obj)
def loadSvgPatterns():
"loads the default Draft SVG patterns and custom patters if available"
import importSVG
from PySide import QtCore
FreeCAD.svgpatterns = {}
# getting default patterns
patfiles = QtCore.QDir(":/patterns").entryList()
for fn in patfiles:
fn = ":/patterns/"+str(fn)
f = QtCore.QFile(fn)
f.open(QtCore.QIODevice.ReadOnly)
p = importSVG.getContents(str(f.readAll()),'pattern',True)
if p:
for k in p:
p[k] = [p[k],fn]
FreeCAD.svgpatterns.update(p)
# looking for user patterns
altpat = getParam("patternFile","")
if os.path.isdir(altpat):
for f in os.listdir(altpat):
if f[-4:].upper() == ".SVG":
p = importSVG.getContents(altpat+os.sep+f,'pattern')
if p:
for k in p:
p[k] = [p[k],altpat+os.sep+f]
FreeCAD.svgpatterns.update(p)
def svgpatterns():
"""svgpatterns(): returns a dictionary with installed SVG patterns"""
if hasattr(FreeCAD,"svgpatterns"):
return FreeCAD.svgpatterns
else:
loadSvgPatterns()
if hasattr(FreeCAD,"svgpatterns"):
return FreeCAD.svgpatterns
return {}
def loadTexture(filename,size=None):
"""loadTexture(filename,[size]): returns a SoSFImage from a file. If size
is defined (an int or a tuple), and provided the input image is a png file,
it will be scaled to match the given size."""
if gui:
from pivy import coin
from PySide import QtGui,QtSvg
try:
p = QtGui.QImage(filename)
# buggy - TODO: allow to use resolutions
#if size and (".svg" in filename.lower()):
# # this is a pattern, not a texture
# if isinstance(size,int):
# size = (size,size)
# svgr = QtSvg.QSvgRenderer(filename)
# p = QtGui.QImage(size[0],size[1],QtGui.QImage.Format_ARGB32)
# pa = QtGui.QPainter()
# pa.begin(p)
# svgr.render(pa)
# pa.end()
#else:
# p = QtGui.QImage(filename)
size = coin.SbVec2s(p.width(), p.height())
buffersize = p.byteCount()
numcomponents = int (float(buffersize) / ( size[0] * size[1] ))
img = coin.SoSFImage()
width = size[0]
height = size[1]
bytes = ""
for y in range(height):
#line = width*numcomponents*(height-(y));
for x in range(width):
rgb = p.pixel(x,y)
if numcomponents == 1:
bytes = bytes + chr(QtGui.qGray( rgb ))
elif numcomponents == 2:
bytes = bytes + chr(QtGui.qGray( rgb ))
bytes = bytes + chr(QtGui.qAlpha( rgb ))
elif numcomponents == 3:
bytes = bytes + chr(QtGui.qRed( rgb ))
bytes = bytes + chr(QtGui.qGreen( rgb ))
bytes = bytes + chr(QtGui.qBlue( rgb ))
elif numcomponents == 4:
bytes = bytes + chr(QtGui.qRed( rgb ))
bytes = bytes + chr(QtGui.qGreen( rgb ))
bytes = bytes + chr(QtGui.qBlue( rgb ))
bytes = bytes + chr(QtGui.qAlpha( rgb ))
#line += numcomponents
img.setValue(size, numcomponents, bytes)
except:
print("Draft: unable to load texture")
return None
else:
return img
return None
def getMovableChildren(objectslist,recursive=True):
'''getMovableChildren(objectslist,[recursive]): extends the given list of objects
with all child objects that have a "MoveWithHost" property set to True. If
recursive is True, all descendents are considered, otherwise only direct children.'''
added = []
if not isinstance(objectslist,list):
objectslist = [objectslist]
for obj in objectslist:
if not (getType(obj) in ["Clone","SectionPlane","Facebinder"]):
# objects that should never move their children
children = obj.OutList
if hasattr(obj,"Proxy"):
if obj.Proxy:
if hasattr(obj.Proxy,"getSiblings") and not(getType(obj) in ["Window"]):
#children.extend(obj.Proxy.getSiblings(obj))
pass
for child in children:
if hasattr(child,"MoveWithHost"):
if child.MoveWithHost:
if hasattr(obj,"CloneOf"):
if obj.CloneOf:
if obj.CloneOf.Name != child.Name:
added.append(child)
else:
added.append(child)
else:
added.append(child)
if recursive:
added.extend(getMovableChildren(children))
return added
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'''
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)
if len(edge.Vertexes) > 1:
ref = placement.multVec(FreeCAD.Vector(1,0,0))
v1 = (edge.Vertexes[0].Point).sub(edge.Curve.Center)
v2 = (edge.Vertexes[-1].Point).sub(edge.Curve.Center)
a1 = -math.degrees(DraftVecUtils.angle(v1,ref))
a2 = -math.degrees(DraftVecUtils.angle(v2,ref))
obj.FirstAngle = a1
obj.LastAngle = a2
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)
FreeCAD.ActiveDocument.recompute()
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 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)
FreeCAD.ActiveDocument.recompute()
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".
'''
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 = []
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"))
obj.ViewObject.Override = "R $dim"
obj.Diameter = False
elif p3 == "diameter":
#l.append((p1,"Diameter"))
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)
FreeCAD.ActiveDocument.recompute()
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.
'''
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)
FreeCAD.ActiveDocument.recompute()
return obj
def makeWire(pointslist,closed=False,placement=None,face=None,support=None):
'''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.'''
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")
if len(pointslist) == 2: fname = "Line"
else: fname = "DWire"
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)
FreeCAD.ActiveDocument.recompute()
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 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)
FreeCAD.ActiveDocument.recompute()
return obj
def makeLine(p1,p2):
'''makeLine(p1,p2): Creates a line between p1 and p2.'''
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.'''
from DraftTools import msg
if not isinstance(pointslist,list):
nlist = []
for v in pointslist.Vertexes:
nlist.append(v.Point)
pointslist = nlist
if len(pointslist) < 2:
msg(translate("draft","Draft.makeBSpline: not enough points\n"), 'error')
return
if (pointslist[0] == pointslist[-1]):
if len(pointslist) > 2:
closed = True
pointslist.pop()
msg(translate("draft","Draft.makeBSpline: Equal endpoints forced Closed\n"), 'warning')
else: # len == 2 and first == last GIGO
msg(translate("draft","Draft.makeBSpline: Invalid pointslist\n"), 'error')
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)
FreeCAD.ActiveDocument.recompute()
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 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)
FreeCAD.ActiveDocument.recompute()
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.'''
typecheck([(point,Vector)], "makeText")
if not isinstance(stringslist,list): stringslist = [stringslist]
obj=FreeCAD.ActiveDocument.addObject("App::Annotation","Text")
obj.LabelText=stringslist
obj.Position=point
if FreeCAD.GuiUp:
if not screen:
obj.ViewObject.DisplayMode="World"
h = getParam("textheight",0.20)
if screen:
h = h*10
obj.ViewObject.FontSize = h
obj.ViewObject.FontName = getParam("textfont","")