forked from juanvanyo/FreeCAD-GDT
-
Notifications
You must be signed in to change notification settings - Fork 3
/
GDT.py
2366 lines (2024 loc) · 99.6 KB
/
GDT.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) 2016 Juan Vanyo Cerda <juavacer@inf.upv.es> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#***************************************************************************
__title__="FreeCAD GDT Workbench"
__author__ = "Juan Vanyo Cerda <juavacer@inf.upv.es>"
__url__ = "http://www.freecadweb.org"
# Description of tool
import numpy
import FreeCAD as App
import FreeCAD, math, sys, os, DraftVecUtils, Draft_rc
from math import pi
from FreeCAD import Vector
import traceback
import Draft
import Part
from pivy import coin
import FreeCADGui, WorkingPlane
translate = FreeCAD.Qt.translate
if FreeCAD.GuiUp:
gui = True
else:
FreeCAD.Console.PrintMessage("FreeCAD Gui not present. GDT module will have some features disabled.")
gui = True
try:
import PySide
from PySide import QtCore,QtGui,QtSvg
except ImportError:
FreeCAD.Console.PrintMessage("Error: Python-pyside package must be installed on your system to use the Geometric Dimensioning & Tolerancing module.")
__dir__ = os.path.dirname(__file__)
iconPath = os.path.join( __dir__, 'Resources', 'icons' )
path_dd_resources = os.path.join( os.path.dirname(__file__), 'Resources', 'dd_resources.rcc')
resourcesLoaded = QtCore.QResource.registerResource(path_dd_resources)
assert resourcesLoaded
checkBoxState = True
auxDictionaryDS=[]
for i in range(1,100):
auxDictionaryDS.append('DS'+str(i))
dictionaryAnnotation=[]
for i in range(1,100):
dictionaryAnnotation.append('Annotation'+str(i))
#---------------------------------------------------------------------------
# Param functions
#---------------------------------------------------------------------------
def getParamType(param):
if param in ["lineWidth"]:
return "int"
elif param in ["textFamily"]:
return "string"
elif param in ["textSize","tolerancetextSize","lineScale"]:
return "float"
elif param in ["alwaysShowGrid","showUnit", "changeColor"]:
return "bool"
elif param in ["textColor","lineColor"]:
return "unsigned"
else:
return None
def getParam(param,default=None):
"getParam(parameterName): returns a GDT parameter value from the current config"
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/GDT")
t = getParamType(param)
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 = 1
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 GDT parameter with the given value"
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/GDT")
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)
#---------------------------------------------------------------------------
# General functions
#---------------------------------------------------------------------------
# Modif 5@xes for test
"""
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 string_encode(ustr):
"""string_encode(str): Encodes a unicode object to be used as a string in coin"""
# return ustr.encode('utf-8')
# return ustr.encode('latin1')
return ustr
def stringplusminus():
# else ' +- '
return ' ± '
def getType(objt):
"getType(object): returns the GDT type of the given object"
if not objt:
return None
if "Proxy" in objt.PropertiesList:
if hasattr(objt.Proxy,"Type"):
return objt.Proxy.Type
return "Unknown"
def getObjectsOfType(typeList):
"getObjectsOfType(string): returns a list of objects of the given type"
listObjectsOfType = []
objs = FreeCAD.ActiveDocument.Objects
if not isinstance(typeList,list):
typeList = [typeList]
for obj in objs:
for typ in typeList:
if typ == getType(obj):
listObjectsOfType.append(obj)
return listObjectsOfType
def getAllAnnotationPlaneObjects():
"getAllAnnotationPlaneObjects(): returns a list of annotation plane objects"
return getObjectsOfType("AnnotationPlane")
def getAllDatumFeatureObjects():
"getAllDatumFeatureObjects(): returns a list of datum feature objects"
return getObjectsOfType("DatumFeature")
def getAllDatumSystemObjects():
"getAllDatumSystemObjects(): returns a list of datum system objects"
return getObjectsOfType("DatumSystem")
def getAllGeometricToleranceObjects():
"getAllGeometricToleranceObjects(): returns a list of geometric tolerance objects"
return getObjectsOfType("GeometricTolerance")
def getAllGDTObjects():
"getAllGDTObjects(): returns a list of GDT objects"
return getObjectsOfType(["AnnotationPlane","DatumFeature","DatumSystem","GeometricTolerance"])
def getAllAnnotationObjects():
"getAllAnnotationObjects(): returns a list of annotation objects"
return getObjectsOfType("Annotation")
def getRGB(param):
color = QtGui.QColor(getParam(param,16753920)>>8)
r = float(color.red()/255.0)
g = float(color.green()/255.0)
b = float(color.blue()/255.0)
col = (r,g,b,0.0)
return col
def getRGBText():
return getRGB("textColor")
def getTextFamily():
return getParam("textFamily","")
# Modif 5@xes
def getTextSize():
return getParam("textSize",1.8)
def getToleranceTextSize():
return getParam("tolerancetextSize",1.0)
def getLineWidth():
return getParam("lineWidth",2)
def getRGBLine():
return getRGB("lineColor")
def hideGrid():
if hasattr(FreeCADGui,"Snapper") and getParam("alwaysShowGrid") == False:
if FreeCADGui.Snapper.grid:
if FreeCADGui.Snapper.grid.Visible:
FreeCADGui.Snapper.grid.off()
FreeCADGui.Snapper.forceGridOff=True
def showGrid():
if hasattr(FreeCADGui,"Snapper"):
if FreeCADGui.Snapper.grid:
if FreeCADGui.Snapper.grid.Visible == False:
FreeCADGui.Snapper.grid.reset()
FreeCADGui.Snapper.grid.on()
FreeCADGui.Snapper.forceGridOff=False
else:
FreeCADGui.Snapper.show()
# Just to know if we have a selection
def getSelection():
"getSelection(): returns the current FreeCAD selection"
if gui:
return FreeCADGui.Selection.getSelection()
return None
# Possibility to modify FreeCADGui.Selection.getSelectionEx("",0)
# https://forum.freecad.org/viewtopic.php?p=668442#p668442
def getSelectionEx():
"getSelectionEx(): returns the current FreeCAD selection (with subobjects)"
if gui:
return FreeCADGui.Selection.getSelectionEx("",0)
return None
def select(objt):
"select(object): deselects everything and selects only the working faces of the passed object"
if gui:
FreeCADGui.Selection.clearSelection()
for i in range(len(objt.faces)):
FreeCADGui.Selection.addSelection(objt.faces[i][0],objt.faces[i][1])
def setColor(type):
paracol = getParam("changeColor",True)
if paracol == True :
a = FreeCADGui.Selection.getSelectionEx() # selection SubElementNames
aa = FreeCADGui.Selection.getSelection() # selection object
try:
cols = colors = []
cols = FreeCAD.ActiveDocument.getObject(aa[0].Name).ViewObject.DiffuseColor
if len(cols) == 1:
for i in aa[0].Shape.Faces:
colors += [(cols[0])]
else:
colors = cols
for i in range(len(aa)):
fce = int(a[0].SubElementNames[i][4:])-1
if type == "PF" :
colors[fce] = (float(1),float(0),float(0),float(0))
elif type == "DF" :
colors[fce] = (float(0),float(0),float(1),float(0))
elif type == "GT" :
colors[fce] = (float(1),float(1),float(0),float(0))
else :
colors[fce] = (float(0),float(1),float(0),float(0))
aa[i].ViewObject.DiffuseColor = colors
except Exception:
print ("Select one face")
def makeContainerOfData():
""
faces = []
for i in range(len(FreeCADGui.Selection.getSelectionEx("",0))):
for j in range(len(FreeCADGui.Selection.getSelectionEx("",1)[i].SubElementNames)):
faces.append((FreeCADGui.Selection.getSelectionEx("",0)[i].Object, FreeCADGui.Selection.getSelectionEx("",1)[i].SubElementNames[j]))
faces.sort()
container = ContainerOfData(faces)
return container
def getAnnotationObj(obj):
List = getAllAnnotationObjects()
for l in List:
if l.faces == obj.faces:
return l
return None
def getAnnotationWithDF(obj):
List = getAllAnnotationObjects()
for l in List:
if l.DF == obj:
return l
return None
def getAnnotationWithGT(obj):
List = getAllAnnotationObjects()
for l in List:
for gt in l.GT:
if gt == obj:
return l
return None
#-----------------------------------
# Geometric creation for the entities
#-----------------------------------
# Points definition for the geometry
def getPointsToPlot(obj):
points = []
segments = []
if obj.GT != [] or obj.DF != None:
X = FreeCAD.Vector(1.0,0.0,0.0)
Y = FreeCAD.Vector(0.0,1.0,0.0)
#AP Annotation Plane
Direction = X if abs(X.dot(obj.AP.Direction)) < 0.8 else Y
Vertical = obj.AP.Direction.cross(Direction).normalize()
Horizontal = Vertical.cross(obj.AP.Direction).normalize()
point = obj.selectedPoint
d = point.distanceToPlane(obj.p1, obj.Direction)
# IF circumference
if obj.circumferenceBool:
P3 = point + obj.Direction * (-d)
d2 = (P3 - obj.p1) * Vertical
P2 = obj.p1 + Vertical * (d2*3/4)
else:
P2 = obj.p1 + obj.Direction * (d*3/4)
P3 = point
# Crate the points for the Attach Line
points = [obj.p1, P2, P3]
segments = [0,1,2]
existGT = True
# Draw Geometric Tolerance
if obj.GT != []:
points, segments = getPointsToPlotGT(obj, points, segments, Vertical, Horizontal)
else:
existGT = False
# Draw Datum Feature
if obj.DF != None:
points, segments = getPointsToPlotDF(obj, existGT, points, segments, Vertical, Horizontal)
segments += []
return points, segments
# Draw Geometric Tolerance
def getPointsToPlotGT(obj, points, segments, Vertical, Horizontal):
newPoints = points
newSegments = segments
if obj.ViewObject.LineScale > 0:
sizeOfLine = obj.ViewObject.LineScale
else:
sizeOfLine = 1.0
for i in range(len(obj.GT)):
d = len(newPoints)
if points[2].x < points[0].x:
P0 = newPoints[-1] + Vertical * (sizeOfLine) if i == 0 else FreeCAD.Vector(newPoints[-2])
else:
P0 = newPoints[-1] + Vertical * (sizeOfLine) if i == 0 else FreeCAD.Vector(newPoints[-1])
P1 = P0 + Vertical * (-sizeOfLine*2)
P2 = P0 + Horizontal * (sizeOfLine*2)
P3 = P1 + Horizontal * (sizeOfLine*2)
# Length of the framework around the Tolerance Zone
lengthToleranceValue = len(string_encode(displayExternal(obj.GT[i].ToleranceValue, obj.ViewObject.Decimals, 'Length', obj.ViewObject.ShowUnit))) -2
# if obj.GT[i].FeatureControlFrameIcon != '' or obj.GT[i].FeatureControlFrameCode != '' :
# Add the space for the Control Ine and the diameter
if obj.GT[i].FeatureControlFrameIcon != '' :
lengthToleranceValue += 2
if obj.GT[i].Circumference :
lengthToleranceValue += 1
P4 = P2 + Horizontal * (sizeOfLine*lengthToleranceValue)
P5 = P3 + Horizontal * (sizeOfLine*lengthToleranceValue)
if obj.GT[i].DS == None or obj.GT[i].DS.Primary == None:
newPoints += [P0, P2, P3, P4, P5, P1]
newSegments += [-1, 0+d, 3+d, 4+d, 5+d, 0+d, -1, 1+d, 2+d]
if points[2].x < points[0].x:
displacement = newPoints[-3].x - newPoints[-6].x
for i in range(len(newPoints)-6, len(newPoints)):
newPoints[i].x-=displacement
else:
P6 = P4 + Horizontal * (sizeOfLine*2)
P7 = P5 + Horizontal * (sizeOfLine*2)
if obj.GT[i].DS.Secondary != None:
P8 = P6 + Horizontal * (sizeOfLine*2)
P9 = P7 + Horizontal * (sizeOfLine*2)
if obj.GT[i].DS.Tertiary != None:
P10 = P8 + Horizontal * (sizeOfLine*2)
P11 = P9 + Horizontal * (sizeOfLine*2)
newPoints += [P0, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P1]
newSegments += [-1, 0+d, 9+d, 10+d, 11+d, 0+d, -1, 1+d, 2+d, -1, 3+d, 4+d, -1, 5+d, 6+d, -1, 7+d, 8+d]
if points[2].x < points[0].x:
displacement = newPoints[-3].x - newPoints[-12].x
for i in range(len(newPoints)-12, len(newPoints)):
newPoints[i].x-=displacement
else:
newPoints += [P0, P2, P3, P4, P5, P6, P7, P8, P9, P1]
newSegments += [-1, 0+d, 7+d, 8+d, 9+d, 0+d, -1, 1+d, 2+d, -1, 3+d, 4+d, -1, 5+d, 6+d]
if points[2].x < points[0].x:
displacement = newPoints[-3].x - newPoints[-10].x
for i in range(len(newPoints)-10, len(newPoints)):
newPoints[i].x-=displacement
else:
newPoints += [P0, P2, P3, P4, P5, P6, P7, P1]
newSegments += [-1, 0+d, 5+d, 6+d, 7+d, 0+d, -1, 1+d, 2+d, -1, 3+d, 4+d]
if points[2].x < points[0].x:
displacement = newPoints[-3].x - newPoints[-8].x
for i in range(len(newPoints)-8, len(newPoints)):
newPoints[i].x-=displacement
return newPoints, newSegments
# Draw Datum Feature
def getPointsToPlotDF(obj, existGT, points, segments, Vertical, Horizontal):
newPoints = points
newSegments = segments
if obj.ViewObject.LineScale > 0:
sizeOfLine = obj.ViewObject.LineScale
else:
sizeOfLine = 1.0
'''
d = len(points)
# Remove the Square initialy created at the base of the Datum Reference
if not existGT:
P0 = points[-1] + Vertical * (sizeOfLine)
P1 = P0 + Horizontal * (sizeOfLine*2)
P2 = P1 + Vertical * (-sizeOfLine*2)
P3 = P2 + Horizontal * (-sizeOfLine*2)
newPoints += [P0, P1, P2, P3]
newSegments += [-1, 0+d, 1+d, 2+d, 3+d, 0+d]
if points[2].x < points[0].x:
displacement = newPoints[-2].x - newPoints[-1].x
for i in range(len(newPoints)-4, len(newPoints)):
newPoints[i].x-=displacement
'''
# Draw the Square arount the Datum + The bottom triangle
d=len(newPoints)
# newPoints[-1]should be end of attach line
h = math.sqrt(sizeOfLine*sizeOfLine+(sizeOfLine/2)*(sizeOfLine/2))
'''
PAux = newPoints[-1] + Horizontal * (sizeOfLine)
P0 = newPoints[-1] + Horizontal * (sizeOfLine/2)
'''
PAux = newPoints[-1] + Horizontal * (sizeOfLine) - Horizontal
P0 = newPoints[-1] + Horizontal * (sizeOfLine/2) - Horizontal
P1 = P0 + Horizontal * (sizeOfLine)
P2 = PAux + Vertical * (-h)
P3 = PAux + Vertical * (-sizeOfLine*3)
P4 = P3 + Horizontal * (sizeOfLine)
P5 = P4 + Vertical * (-sizeOfLine*2)
P6 = P5 + Horizontal * (-sizeOfLine*2)
P7 = P6 + Vertical * (sizeOfLine*2)
newPoints += [P0, P1, P2, P3, P4, P5, P6, P7]
if existGT:
displacement = newPoints[-8].x - newPoints[-7].x
print("displacement {}".format(displacement))
for i in range(len(newPoints)-8, len(newPoints)):
newPoints[i].x-=displacement
newSegments += [-1, 0+d, 1+d, 0+d, 2+d, -1, 1+d, 2+d, 3+d, 4+d, 5+d, 6+d, 7+d, 3+d]
return newPoints, newSegments
# Draw the Text for the Tolerance
def plotStrings(self, fp, points):
import DraftGeomUtils
if fp.ViewObject.LineScale > 0:
sizeOfLine = fp.ViewObject.LineScale
else:
sizeOfLine = 1.0
X = FreeCAD.Vector(1.0,0.0,0.0)
Y = FreeCAD.Vector(0.0,1.0,0.0)
#AP Annotation Plane
Direction = X if abs(X.dot(fp.AP.Direction)) < 0.8 else Y
Vertical = fp.AP.Direction.cross(Direction).normalize()
Horizontal = Vertical.cross(fp.AP.Direction).normalize()
index = 0
indexSYMB = 0
indexIcon = 0
displacement = 0
""" Define a Geometrix Tolerance """
if fp.GT != []:
for i in range(len(fp.GT)):
distance = 0
# posToleranceValue
v = (points[7+displacement] - points[5+displacement])
if v.x != 0:
distance = (v.x)/2
elif v.y != 0:
distance = (v.y)/2
else:
distance = (v.z)/2
# if fp.GT[i].FeatureControlFrameIcon != '' or fp.GT[i].FeatureControlFrameCode != '':
if fp.GT[i].FeatureControlFrameIcon != '' :
distance -= sizeOfLine
if fp.GT[i].Circumference:
distance += sizeOfLine
centerPoint = points[5+displacement] + Horizontal * (distance)
posToleranceValue = centerPoint + Vertical * (sizeOfLine/2)
# posCharacteristic
auxPoint = points[3+displacement] + Vertical * (-sizeOfLine*2)
self.points[indexSYMB].point.setValues([[auxPoint.x,auxPoint.y,auxPoint.z],[points[5+displacement].x,points[5+displacement].y,points[5+displacement].z],[points[4+displacement].x,points[4+displacement].y,points[4+displacement].z],[points[3+displacement].x,points[3+displacement].y,points[3+displacement].z]])
# print("Label {}".format(fp.GT[i].Characteristic))
# print("AP.Direction {}".format(fp.AP.Direction))
try:
#Unicode display
self.textSYMB[indexSYMB].string = u"{}".format(fp.GT[i].CharacteristicCode) # Characteristic Code
symbolPoint = auxPoint + Horizontal + Vertical * 0.5
self.textSYMBpos[indexSYMB].translation.setValue([symbolPoint.x,symbolPoint.y,symbolPoint.z])
self.textSYMB[indexSYMB].justification = coin.SoAsciiText.CENTER
except:
# Compatibility Old Version with SVG File
self.face[indexIcon].numVertices = 4
sZ = 1/(sizeOfLine*2)
dS = FreeCAD.Vector(Horizontal) * sZ
dT = FreeCAD.Vector(Vertical) * sZ
self.svgPos[indexIcon].directionS.setValue(dS.x, dS.y, dS.z)
self.svgPos[indexIcon].directionT.setValue(dT.x, dT.y, dT.z)
displacementH = ((Horizontal*auxPoint)%(sizeOfLine*2))/(sizeOfLine*2)
displacementV = ((Vertical*auxPoint)%(sizeOfLine*2))/(sizeOfLine*2)
self.textureTransform[indexIcon].translation.setValue(-displacementH,-displacementV)
filename = fp.GT[i].CharacteristicIcon
filename = filename.replace(':/dd/icons', iconPath)
self.svg[indexIcon].filename = str(filename)
indexIcon+=1
indexSYMB+=1
# posFeactureControlFrame
# if fp.GT[i].FeatureControlFrameIcon != '' or fp.GT[i].FeatureControlFrameCode != '' :
if fp.GT[i].FeatureControlFrameIcon != '' :
auxPoint1 = points[7+displacement] + Horizontal * (-sizeOfLine*2)
auxPoint2 = auxPoint1 + Vertical * (sizeOfLine*2)
self.points[indexSYMB].point.setValues([[auxPoint1.x,auxPoint1.y,auxPoint1.z],[points[7+displacement].x,points[7+displacement].y,points[7+displacement].z],[points[6+displacement].x,points[6+displacement].y,points[6+displacement].z],[auxPoint2.x,auxPoint2.y,auxPoint2.z]])
try:
FreeCAD.Console.PrintMessage("FrameCode {}\n".format(fp.GT[i].FeatureControlFrameCode))
self.textSYMB[indexSYMB].string = u"{}".format(fp.GT[i].FeatureControlFrameCode) #Diameter
symbolPoint = auxPoint1 + Horizontal + Vertical * 0.5
self.textSYMBpos[indexSYMB].translation.setValue([symbolPoint.x,symbolPoint.y,symbolPoint.z])
self.textSYMB[indexSYMB].justification = coin.SoAsciiText.CENTER
except:
# Compatibility Old Version
self.face[indexIcon].numVertices = 4
self.svgPos[indexIcon].directionS.setValue(dS.x, dS.y, dS.z)
self.svgPos[indexIcon].directionT.setValue(dT.x, dT.y, dT.z)
displacementH = ((Horizontal*auxPoint1)%(sizeOfLine*2))/(sizeOfLine*2)
displacementV = ((Vertical*auxPoint1)%(sizeOfLine*2))/(sizeOfLine*2)
self.textureTransform[indexIcon].translation.setValue(-displacementH,-displacementV)
filename = fp.GT[i].FeatureControlFrameIcon
filename = filename.replace(':/dd/icons', iconPath)
self.svg[indexIcon].filename = str(filename)
indexIcon+=1
indexSYMB+=1
# posDiameter
if fp.GT[i].Circumference:
auxPoint1 = points[5+displacement] + Horizontal * (sizeOfLine*2)
auxPoint2 = auxPoint1 + Vertical * (sizeOfLine*2)
self.points[indexSYMB].point.setValues([[points[5+displacement].x,points[5+displacement].y,points[5+displacement].z],[auxPoint1.x,auxPoint1.y,auxPoint1.z],[auxPoint2.x,auxPoint2.y,auxPoint2.z],[points[4+displacement].x,points[4+displacement].y,points[4+displacement].z]])
"""
self.face[indexIcon].numVertices = 4
self.svgPos[indexIcon].directionS.setValue(dS.x, dS.y, dS.z)
self.svgPos[indexIcon].directionT.setValue(dT.x, dT.y, dT.z)
displacementH = ((Horizontal*points[5+displacement])%(sizeOfLine*2))/(sizeOfLine*2)
displacementV = ((Vertical*points[5+displacement])%(sizeOfLine*2))/(sizeOfLine*2)
self.textureTransform[indexIcon].translation.setValue(-displacementH,-displacementV)
filename = os.path.join(iconPath , 'diameter.svg')
self.svg[indexIcon].filename = str(filename)
indexIcon+=1
"""
# self.textSYMB[indexSYMB].string = u"\u2300" #Diameter
self.textSYMB[indexSYMB].string = u"\u00D8" #Diameter
symbolPoint = points[5+displacement] + Horizontal + Vertical*0.5
self.textSYMBpos[indexSYMB].translation.setValue([symbolPoint.x,symbolPoint.y,symbolPoint.z])
self.textSYMB[indexSYMB].justification = coin.SoAsciiText.CENTER
indexSYMB+=1
self.textGT[index].string = string_encode(displayExternal(fp.GT[i].ToleranceValue, fp.ViewObject.Decimals, 'Length', fp.ViewObject.ShowUnit))
self.textGTpos[index].translation.setValue([posToleranceValue.x-(sizeOfLine*0.3), posToleranceValue.y, posToleranceValue.z])
self.textGT[index].justification = coin.SoAsciiText.CENTER
index+=1
displacement+=6
if fp.GT[i].DS != None and fp.GT[i].DS.Primary != None:
# if fp.GT[i].FeatureControlFrameIcon != '' or fp.GT[i].FeatureControlFrameCode != '' :
if fp.GT[i].FeatureControlFrameIcon != '' :
distance += (sizeOfLine*2)
if fp.GT[i].Circumference:
distance -= (sizeOfLine*2)
posPrimary = posToleranceValue + Horizontal * (distance+sizeOfLine)
self.textGT[index].string = str(fp.GT[i].DS.Primary.Label)
self.textGTpos[index].translation.setValue([posPrimary.x, posPrimary.y, posPrimary.z])
self.textGT[index].justification = coin.SoAsciiText.CENTER
index+=1
displacement+=2
if fp.GT[i].DS.Secondary != None:
posSecondary = posPrimary + Horizontal * (sizeOfLine*2)
self.textGT[index].string = str(fp.GT[i].DS.Secondary.Label)
self.textGTpos[index].translation.setValue([posSecondary.x, posSecondary.y, posSecondary.z])
self.textGT[index].justification = coin.SoAsciiText.CENTER
index+=1
displacement+=2
if fp.GT[i].DS.Tertiary != None:
posTertiary = posSecondary + Horizontal * (sizeOfLine*2)
self.textGT[index].string = str(fp.GT[i].DS.Tertiary.Label)
self.textGTpos[index].translation.setValue([posTertiary.x, posTertiary.y, posTertiary.z])
self.textGT[index].justification = coin.SoAsciiText.CENTER
index+=1
displacement+=2
if fp.circumferenceBool and True in [l.Circumference for l in fp.GT]:
# posDiameterTolerance
auxPoint1 = FreeCAD.Vector(points[4]) # Point Diameter
dec=len(str(displayExternal(fp.diameter, fp.ViewObject.Decimals, 'Length', fp.ViewObject.ShowUnit)))-2
auxPoint2 = auxPoint1 + Horizontal * (sizeOfLine*2) # Point Nominal
auxPoint3 = auxPoint2 + Horizontal * (sizeOfLine*dec) + Vertical * (sizeOfLine*3) # Point Upper Tol
auxPoint4 = auxPoint2 + Horizontal * (sizeOfLine*dec) + Vertical * sizeOfLine # Point Lower Tol
self.points[indexSYMB].point.setValues([[auxPoint1.x,auxPoint1.y,auxPoint1.z],[auxPoint2.x,auxPoint2.y,auxPoint2.z],[auxPoint3.x,auxPoint3.y,auxPoint3.z],[auxPoint4.x,auxPoint4.y,auxPoint4.z]])
"""
self.face[indexIcon].numVertices = 4
self.svgPos[indexIcon].directionS.setValue(dS.x, dS.y, dS.z)
self.svgPos[indexIcon].directionT.setValue(dT.x, dT.y, dT.z)
displacementH = ((Horizontal*auxPoint1)%(sizeOfLine*2))/(sizeOfLine*2)
displacementV = ((Vertical*auxPoint1)%(sizeOfLine*2))/(sizeOfLine*2)
self.textureTransform[indexIcon].translation.setValue(-displacementH,-displacementV)
filename = os.path.join(iconPath , 'diameter.svg')
self.svg[indexIcon].filename = str(filename)
indexIcon+=1
"""
self.textSYMB[indexSYMB].string = u"\u00D8" #Diameter
symbolPoint = auxPoint1 + Horizontal + Vertical * 0.5
self.textSYMBpos[indexSYMB].translation.setValue([symbolPoint.x,symbolPoint.y,symbolPoint.z])
self.textSYMB[indexSYMB].justification = coin.SoAsciiText.CENTER
indexSYMB+=1
posDiameterTolerance = auxPoint2 + Vertical * (sizeOfLine/2)
self.textGT[index].justification = coin.SoAsciiText.LEFT
self.textGTpos[index].translation.setValue([posDiameterTolerance.x, posDiameterTolerance.y, posDiameterTolerance.z])
if fp.toleranceSelectBool:
text = string_encode(displayExternal(fp.diameter, fp.ViewObject.Decimals, 'Length', fp.ViewObject.ShowUnit) + stringplusminus() + displayExternal(fp.toleranceDiameter, fp.ViewObject.Decimals, 'Length', fp.ViewObject.ShowUnit))
self.textGT[index].string = text
index+=1
else:
text = string_encode(displayExternal(fp.diameter, fp.ViewObject.Decimals, 'Length', fp.ViewObject.ShowUnit))
self.textGT[index].justification = coin.SoAsciiText.LEFT
self.textGT[index].string = text
index+=1
text = string_encode(displayExternal(fp.highLimit, fp.ViewObject.Decimals, 'Length', fp.ViewObject.ShowUnit))
self.textGT[index].string = text
self.textGT[index].justification = coin.SoAsciiText.LEFT
self.textGTpos[index].translation.setValue([auxPoint3.x, auxPoint3.y, auxPoint3.z])
index+=1
text = string_encode(displayExternal(fp.lowLimit, fp.ViewObject.Decimals, 'Length', fp.ViewObject.ShowUnit))
self.textGT[index].string = text
self.textGT[index].justification = coin.SoAsciiText.LEFT
self.textGTpos[index].translation.setValue([auxPoint4.x, auxPoint4.y, auxPoint4.z])
index+=1
for i in range(index):
try:
#AP Annotation Plane
DirectionAux = FreeCAD.Vector(fp.AP.Direction)
DirectionAux.x = abs(DirectionAux.x)
DirectionAux.y = abs(DirectionAux.y)
DirectionAux.z = abs(DirectionAux.z)
rotation=(DraftGeomUtils.getRotation(DirectionAux)).Q
self.textGTpos[i].rotation.setValue(rotation)
except:
pass
for i in range(indexSYMB):
try:
#AP Annotation Plane
DirectionAux = FreeCAD.Vector(fp.AP.Direction)
DirectionAux.x = abs(DirectionAux.x)
DirectionAux.y = abs(DirectionAux.y)
DirectionAux.z = abs(DirectionAux.z)
rotation=(DraftGeomUtils.getRotation(DirectionAux)).Q
self.textSYMBpos[i].rotation.setValue(rotation)
except:
pass
for i in range(index,len(self.textGT)):
if str(self.textGT[i].string) != "":
self.textGT[i].string = ""
else:
break
for i in range(indexSYMB,len(self.textSYMB)):
self.textSYMB[i].string = ""
if str(self.face[i].numVertices) != 0:
self.face[i].numVertices = 0
for i in range(indexIcon,len(self.svg)):
self.svg[i].filename = ""
else:
for i in range(len(self.textGT)):
if str(self.textGT[i].string) != "" or str(self.svg[i].filename) != "":
self.textGT[i].string = ""
self.textSYMB[i].string = ""
self.face[i].numVertices = 0
self.svg[i].filename = ""
else:
break
"""
Define a Datum Feature
"""
if fp.DF != None:
# print("Datum Feature Label {}".format(str(fp.DF.Label)))
self.textDF.string = str(fp.DF.Label)
distance = 0
v = (points[-3] - points[-2])
if v.x != 0:
distance = (v.x)/2
elif v.y != 0:
distance = (v.y)/2
else:
distance = (v.z)/2
"""
print("Datum Feature Label {}".format(str(fp.DF.Label)))
print("Datum Feature Vertical {}".format(Vertical))
print("Datum Feature Horizontal {}".format(Horizontal))
"""
# Modif 5@xes https://github.com/5axes/FreeCAD-GDT/issues/21
# Must be tested on different Case
# Code not valid it's just a patch but if the plan is particular it doesn't work
# To be reviewed
Epsilon = 1E-10
vectCor = FreeCAD.Vector(0,distance/2,distance/2)
if Horizontal.y > Epsilon :
centerPoint = points[-2] + vectCor
else :
centerPoint = points[-2] + Horizontal * (distance)
if Vertical.z < -Epsilon :
centerPoint = centerPoint + Vertical * (sizeOfLine*1.5)
else :
centerPoint = centerPoint + Vertical * (sizeOfLine/2)
self.textDFpos.translation.setValue([centerPoint.x, centerPoint.y, centerPoint.z])
try:
#AP Annotation Plane
DirectionAux = FreeCAD.Vector(fp.AP.Direction)
DirectionAux.x = abs(DirectionAux.x)
DirectionAux.y = abs(DirectionAux.y)
DirectionAux.z = abs(DirectionAux.z)
rotation=(DraftGeomUtils.getRotation(DirectionAux)).Q
self.textDFpos.rotation.setValue(rotation)
except:
pass
else:
self.textDF.string = ""
"""
Write the 2x on the GT if 2 faces
"""
if fp.GT != [] or fp.DF != None:
if numpy.size(fp.faces[0][1]) > 1:
# posNumFaces
centerPoint = points[3] + Horizontal * (sizeOfLine)
posNumFaces = centerPoint + Vertical * (sizeOfLine/2)
# 2x
self.textGT[index].string = (str(numpy.size(fp.faces[0][1]))+'x')
self.textGTpos[index].translation.setValue([posNumFaces.x, posNumFaces.y, posNumFaces.z])
self.textGT[index].justification = coin.SoAsciiText.CENTER
try:
#AP Annotation Plane
DirectionAux = FreeCAD.Vector(fp.AP.Direction)
DirectionAux.x = abs(DirectionAux.x)
DirectionAux.y = abs(DirectionAux.y)
DirectionAux.z = abs(DirectionAux.z)
rotation=(DraftGeomUtils.getRotation(DirectionAux)).Q
self.textGTpos[index].rotation.setValue(rotation)
except:
pass
index+=1
#---------------------------------------------------------------------------
# UNITS handling
#---------------------------------------------------------------------------
def getDefaultUnit(dim):
'''return default Unit of Measure for a Dimension based on user preference
Units Schema'''
# only Length and Angle so far
from FreeCAD import Units
if dim == 'Length':
qty = FreeCAD.Units.Quantity(1.0,FreeCAD.Units.Length)
UOM = qty.getUserPreferred()[2]
elif dim == 'Angle':
qty = FreeCAD.Units.Quantity(1.0,FreeCAD.Units.Angle)
UOM = qty.getUserPreferred()[2]
else:
UOM = "xx"
return UOM
def makeFormatSpec(decimals=4,dim='Length'):
''' return a % format spec with specified decimals for a specified
dimension based on on user preference Units Schema'''
if dim == 'Length':
fmtSpec = "%." + str(decimals) + "f "+ getDefaultUnit('Length')
elif dim == 'Angle':
fmtSpec = "%." + str(decimals) + "f "+ getDefaultUnit('Angle')
else:
fmtSpec = "%." + str(decimals) + "f " + "??"
return fmtSpec
def displayExternal(internValue,decimals=4,dim='Length',showUnit=True):
'''return an internal value (ie mm) Length or Angle converted for display according
to Units Schema in use.'''
from FreeCAD import Units
if dim == 'Length':
qty = FreeCAD.Units.Quantity(internValue,FreeCAD.Units.Length)
pref = qty.getUserPreferred()
conversion = pref[1]
uom = pref[2] # can gibe uom Micron
# To suppress the Micron conversion
if uom == "µm" :
decimals = 3
conversion = 1.0
uom == "mm"
elif uom == 'thou':
decimals = 4
conversion = 25.4
uom == "in"
elif dim == 'Angle':
qty = FreeCAD.Units.Quantity(internValue,FreeCAD.Units.Angle)
pref=qty.getUserPreferred()
conversion = pref[1]
uom = pref[2]
else:
conversion = 1.0
uom = "??"
if not showUnit:
uom = ""
fmt = "{0:."+ str(decimals) + "f} "+ uom
displayExt = fmt.format(float(internValue) / float(conversion))
displayExt = displayExt.replace(".",QtCore.QLocale().decimalPoint())
return displayExt
#---------------------------------------------------------------------------
# Python Features definitions
#---------------------------------------------------------------------------
#-----------------------------------------------------------------------
# Base class for GDT objects
#-----------------------------------------------------------------------
class _GDTObject:
"The base class for GDT objects"
def __init__(self,obj,tp="Unknown"):
'''Add some custom properties to our GDT feature'''
obj.Proxy = self
self.Type = tp
obj.addProperty("App::PropertyString","Type","GDT","Type for icon")
obj.Type = "Unknown"
def __getstate__(self):
return self.Type
def __setstate__(self,state):
if state:
self.Type = state
def execute(self,obj):
'''Do something when doing a recomputation, this method is mandatory'''
pass
def onChanged(self, obj, prop):
'''Do something when a property has changed'''
pass
# Define the class for the main Folder
class _ViewProviderGDT:
"The base class for GDT Viewproviders"
def __init__(self, vobj):
'''Set this object to the proxy object of the actual view provider'''
vobj.Proxy = self
self.Object = vobj.Object
self.Type = vobj.Object.Type
def __getstate__(self):
return None
def __setstate__(self, state):
return None
def attach(self,vobj):
'''Setup the scene sub-graph of the view provider, this method is mandatory'''
self.Object = vobj.Object
if not hasattr(vobj.Object, "Type") :
FreeCAD.Console.PrintMessage("Update _GDTObject {}\n".format(vobj.Object))
vobj.Object.addProperty("App::PropertyString","Type","GDT","Type for icon")
vobj.Object.Type = "Unknown"
self.Type = vobj.Object.Type
return
def updateData(self, vobj, prop):
'''If a property of the handled feature has changed we have the chance to handle this here'''
# vobj is the handled feature, prop is the name of the property that has changed
return
def getDisplayModes(self, vobj):
'''Return a list of display modes.'''
modes=[]
return modes
def setDisplayMode(self, mode):
'''Map the display mode defined in attach with those defined in getDisplayModes.\
Since they have the same names nothing needs to be done. This method is optional'''
return mode
def onChanged(self, vobj, prop):