-
Notifications
You must be signed in to change notification settings - Fork 2
/
Base.py
1962 lines (1652 loc) · 68.8 KB
/
Base.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=gbk
#***************************************************************************
#* *
#* Copyright (c) 2009, 2010 *
#* Xiaolong Cheng <[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 *
#* *
#***************************************************************************
import FreeCAD, FreeCADGui, Part, math, sys, os, Image, Drawing, WorkingPlane
from FreeCAD import Vector
#from draftlibs import fcvec, fcgeo
import fcvec, fcgeo
from pivy import coin
from PyQt4 import QtGui , QtCore
import PartGui
import silver_rc
#---------------------------------------------------------------------------
# General functions
#---------------------------------------------------------------------------
__currentProjectPath__ = None
__workbenchPath__ = None
__radius4boltEndpoint__ = 0.01
__radius4Points__ = 1
__windowInfo__ = [] # xmin , xmax , ymin , ymax
DDAStages = ['PreDL','DL','DC','DF','DG']
__currentStage__ = None
StepForStage = ['FirstStep' , 'ShapesAvailable' , 'SpecialStep']
__currentStep__ = None
__ifGraphLatest__ = False
# brush colors come from Mr. Shi's code
__brushColors__ = [( 0.0 , 0.0 , 0.0 , 1.0 ) ,( 0.0 , 0.4 , 0.4 , 1.0 ) ,( 0.0 , 0.4 , 0.0 , 1.0 )
,( 0.0 , 0.6 , 0.0 , 1.0 ) ,( 0.0 , 0.8 , 0.0 , 1.0 ) ,( 0.0 , 1.0 , 0.0 , 1.0 )
,( 0.0 , 1.0 , 0.2 , 1.0 ) ,( 0.0 , 0.6 , 0.6 , 1.0 ) ,( 0.0 , 0.4 , 0.8 , 1.0 )
,( 0.0 , 0.4 , 0.8 , 1.0 ) ,( 0.0 , 0.2 , 1.0 , 1.0 ) ,(1.0 , 1.0 , 1.0 , 1.0)]
# pen colors come from Mr. Shi's code
__penColors__ = [( 0.0 , 0.0 , 0.0 , 1.0 ) ,( 0.0 , 0.0 , 0.0 , 1.0 ) ,( 0.0 , 1.0 , 0.0 , 1.0 )
,( 0.0 , 0.0 , 1.0 , 1.0 ) ,( 1.0 , 0.0 , 0.0 , 1.0 ) ,( 1.0 , 0.0 , 1.0 , 1.0 ) ]
__shapeBeModifying__ = [None , None , None] # docName , objName , subElement
__clearShapeModifyingNodes__ = False
FreeCADGui.updateLocale()
def translate(context, text):
"convenience function for Qt translator"
return str(QtGui.QApplication.translate(context, text, None, QtGui.QApplication.UnicodeUTF8).toUtf8())
def _translate(context, text):
'''翻译QString时用,指定字符串的解码方式,不然显示中文会有乱码 Silver'''
return str(QtGui.QApplication.translate(context, text, None, QtGui.QApplication.UnicodeUTF8).toUtf8()).decode('UTF-8')
def ifGraphLatest():
return __ifGraphLatest__
def sleepQT(seconds):
t=QtCore.QTimer()
e=QtCore.QEventLoop()
QtCore.QObject.connect(t,QtCore.SIGNAL("timeout()"),e,QtCore.SLOT("quit()"))
t.setSingleShot(True)
t.start(seconds*1000) # make a pause of 20 s
e.exec_() # stops here until the timeout() signal is emitted
def getRealTypeAndIndex(objName):
name = objName
for i in range(1 , len(name)):
if not name[-i] in '1234567890':
if i==1:
break
else:
No = int(name[len(name)-i+1:])
return name[:len(name)-i+1] , No
return name , 0
def setGraphLatest():
'''
graph is latest
'''
__ifGraphLatest__ = True
def getDatabaser4CurrentStage():
import DDADatabase
if __currentStage__=='PreDL':
return DDADatabase.dl_database
elif __currentStage__ == 'DL':
return DDADatabase.dc_inputDatabase
elif __currentStage__== 'DC' or __currentStage__== 'DF':
return DDADatabase.df_inputDatabase
return None
def changeStage(stage):
'''
there are 4 stages for DDA : 'DL','DC','DF','DG'
:param id: stage index
'''
assert stage in DDAStages
global __currentStage__
__currentStage__ = stage
print '##############\n#change to tage : ' , __currentStage__ , '\n############'
def changeStep4Stage(step):
'''
there are 3 steps for one stage : 'FirstStep' , 'ShapesAvailable' , 'SpecialStep'
:param id: stage index
'''
assert step in StepForStage
global __currentStage__ , __currentStep__
__currentStep__ = step
print '##############\n#change to step \'' , step , '\' in stage : ' , __currentStage__ , '\n############'
def setGraphRevised():
'''
graph has been revised
'''
__ifGraphLatest__ = False
def showErrorMessageBox( title , text):
box = QtGui.QMessageBox( QtGui.QMessageBox.Critical , title , text ) # 3个参数分别为图标,title,和text
box.exec_()
def showWaringMessageBox( title , text):
box = QtGui.QMessageBox( QtGui.QMessageBox.Warning , title , text , QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel )
ret = box.exec_()
return ret
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 tolerance():
"tolerance(): returns the tolerance value from Draft user settings"
return 0.01
def getParam(param , index = 0):
'''
all the parameters are from Draft.getParam
:param param: parameter name
:param index: if param is color , index is colorIndex
'''
if param == "snapRange" :
return 4
elif param == "gridSpacing":
return 1
elif param == "gridEvery":
return 10
elif param == "UiMode":
return 0
elif param == "linewidth":
return 2
elif param == "textheight":
return 10
elif param == "constructioncolor":
return 746455039
elif param == "color":
return 255
elif param == "snapcolor":
return 255
elif param == "modconstrain":
return 0
elif param == "modsnap":
return 1
elif param == "modalt":
return 2
elif param == "BorderLineColor":
return ( 0.0 , 0.0 , 0.0 )
elif param == "BoundaryLineColor":
return ( 0.0 , 0.0 , 0.0 )
elif param == "BlockColor":
return __brushColors__[index]
elif param == "BlockBoundaryLineColor":
return __penColors__[index]
elif param == "JointLineColor":
return __penColors__[index]
elif param == "TunnelLineColor":
return __penColors__[index]
elif param == "AdditionalLineColor":
return ( 0.0 , 0.0 , 0.0 )
elif param == "MaterialLineColor":
return ( 0.0 , 0.0 , 1.0)
elif param == "TmpBoltElementColor":
return ( 0.0 , 1.0 , 0.0)
elif param == "BoltElementColor":
return ( 0.0 , 1.0 , 0.0)
elif param == "FixedPointColor":
# p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/DDA")
# print 'fixed point color :' , p.GetUnsigned('fixedpointcolor')
return ( 1.0 , 0.0 , 0.0)
elif param == "LoadingPointColor":
# p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/DDA")
# print 'loading point color :' , p.GetUnsigned('loadingpointcolor')
return ( 1.0 , 0.0 , 1.0)
elif param == "MeasuredPointColor":
return ( 0.0 , 1.0 , 1.0)
elif param == "HolePointColor":
return ( 0.8 , 0.8 , 0.0)
# else :
# FreeCAD.Console.PrintError('type \'%s\' not found\n'% param)
def getType(obj):
"getType(object): returns the Draft type of the given object"
if "Proxy" in obj.PropertiesList:
if hasattr(obj.Proxy, "Type"):
return obj.Proxy.Type
if obj.isDerivedFrom("Part::Feature"):
return "Part"
if (obj.Type == "App::Annotation"):
return "Annotation"
if obj.isDerivedFrom("Mesh::Feature"):
return "Mesh"
return "Unknown"
def dimSymbol():
"returns the current dim symbol from the preferences as a pivy SoMarkerSet"
s = getParam("dimsymbol")
marker = coin.SoMarkerSet()
if s == 0: marker.markerIndex = coin.SoMarkerSet.CIRCLE_FILLED_5_5
elif s == 1: marker.markerIndex = coin.SoMarkerSet.CIRCLE_FILLED_7_7
elif s == 2: marker.markerIndex = coin.SoMarkerSet.CIRCLE_FILLED_9_9
elif s == 3: marker.markerIndex = coin.SoMarkerSet.CIRCLE_LINE_5_5
elif s == 4: marker.markerIndex = coin.SoMarkerSet.CIRCLE_LINE_7_7
elif s == 5: marker.markerIndex = coin.SoMarkerSet.CIRCLE_LINE_9_9
elif s == 6: marker.markerIndex = coin.SoMarkerSet.SLASH_5_5
elif s == 7: marker.markerIndex = coin.SoMarkerSet.SLASH_7_7
elif s == 8: marker.markerIndex = coin.SoMarkerSet.SLASH_9_9
elif s == 9: marker.markerIndex = coin.SoMarkerSet.BACKSLASH_5_5
elif s == 10: marker.markerIndex = coin.SoMarkerSet.BACKSLASH_7_7
elif s == 11: marker.markerIndex = coin.SoMarkerSet.BACKSLASH_9_9
return marker
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.
'''
pass
def getSelection():
"getSelection(): returns the current FreeCAD selection"
return FreeCADGui.Selection.getSelection()
def select(objs):
"select(object): deselects everything and selects only the passed object or list"
FreeCADGui.Selection.clearSelection()
if not isinstance(objs, list):
objs = [objs]
for obj in objs:
FreeCADGui.Selection.addSelection(obj)
def recomputeDocument():
'''
recompute FreeCAD.ActiveDocument
'''
FreeCAD.ActiveDocument.recompute()
def makeWire(pointslist, closed=False, placement=None, face=True, support=None , fname = 'Line' , colorIndex = 0):
'''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 isinstance(pointslist, list):
nlist = []
for v in pointslist.Vertexes:
nlist.append(v.Point)
if fcgeo.isReallyClosed(pointslist):
nlist.append(pointslist.Vertexes[0].Point)
pointslist = nlist
if placement: typecheck([(placement, FreeCAD.Placement)], "makeWire")
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython", fname)
_Wire(obj)
_ViewProviderWire(obj.ViewObject)
obj.Points = pointslist
obj.Closed = closed
if closed:
if pointslist[0] != pointslist[-1]:
pointslist.append(pointslist[0])
obj.Support = support
obj.ViewObject.LineColor = getParam(fname+'Color' , colorIndex)
if not face: obj.ViewObject.DisplayMode = "Wireframe"
if placement: obj.Placement = placement
formatObject(obj)
select(obj)
FreeCAD.ActiveDocument.recompute()
setGraphRevised()
return obj
def addShapeMover(docName , objName , subName , point):
assert isinstance(docName , str) and isinstance(objName , str) and isinstance(subName , str)
removeShapeMover()
import Part
# create only one for the node. Create node every time will occur bugs
# for that FreeCAD updates graphs only when script done, this will occure bugs
# if user click objects one by one. For this situation, FreeCAD will create
# 'ABC', 'ABC001' ... at end of script before I delete the first 'ABC'
# I will try to fix the bug later by adding node actually
obj = FreeCAD.ActiveDocument.getObject("ShapeMover")
if not obj:
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","ShapeMover")
_ShapeModifier(obj)
_ViewProviderDDA(obj.ViewObject)
obj.RelatedDocumentName = docName
obj.RelatedObjectName = objName
obj.RelatedSubElement = subName
shape = Part.Vertex(point)
obj.Shape = shape
obj.ViewObject.PointSize = 10
obj.ViewObject.Visibility = True
print '\tShapeMover added'
def removeShapeMover():
hideShapeMover()
# objName = None
# for obj in FreeCAD.ActiveDocument.Objects:
# shapeType , idx = getRealTypeAndIndex(obj.Label)
# if shapeType=='ShapeMover':
# objName = obj.Label
# break
# if objName:
# from drawGui import todo
# todo.delay(FreeCAD.ActiveDocument.removeObject, objName)
# print '\tShapeMover remove ' , objName
def hideShapeMover():
tmp = FreeCAD.ActiveDocument.getObject('ShapeMover')
if tmp:
tmp.ViewObject.Visibility = False
def addShapeModifier(docName , objName , subName , point1 , point2):
assert isinstance(docName , str) and isinstance(objName , str) and isinstance(subName , str)
removeShapeModifier()
import Part
# create only one for the node. Create node every time will occur bugs
# for that FreeCAD updates graphs only when script done, this will occure bugs
# if user click objects one by one. For this situation, FreeCAD will create
# 'ABC', 'ABC001' ... at end of script before I delete the first 'ABC'
# I will try to fix the bug later by adding node actually
obj = FreeCAD.ActiveDocument.getObject("ShapeModifier")
if not obj:
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","ShapeModifier")
_ShapeModifier(obj)
_ViewProviderDDA(obj.ViewObject)
obj.Points = [point1 , point2]
obj.ViewObject.PointSize = 10
obj.ViewObject.Visibility = True
print '\tShapeModifier added'
def removeShapeModifier():
hideShapeModifier()
# objName = None
# for obj in FreeCAD.ActiveDocument.Objects:
# shapeType , idx = getRealTypeAndIndex(obj.Label)
# if shapeType=='ShapeModifier':
# objName = obj.Label
# break
# if objName:
# from drawGui import todo
# todo.delay(FreeCAD.ActiveDocument.removeObject, objName)
# print '\tShapeModifier remove ' , objName
def hideShapeModifier():
tmp = FreeCAD.ActiveDocument.getObject('ShapeModifier')
if tmp:
tmp.ViewObject.Visibility = False
def checkIfAnyObjectsExisting():
return len(FreeCAD.ActiveDocument.Objects)>0
#def __confirmViewProvider4Lines(fname , viewObject):
# if fname=='AdditionalLine':
# _ViewProviderAdditionalLines(viewObject)
# elif fname == 'MaterialLine':
# _ViewProviderMaterialLine(viewObject)
# elif fname == 'BoltElement':
# _ViewProviderBoltElement(viewObject)
# elif fname == 'TmpBoltElement':
# _ViewProviderBoltElement(viewObject)
# elif fname == 'JointLine':
# _ViewProviderJointLines(viewObject)
## elif fname == 'BoundaryLine':
## _ViewProviderBoundaryLines(viewObject)
# else:
# raise Exception('unkown shapes')
def addLines2Document(shapeType , ifStore2Database=False , args=None, closed=False , ifTriggerRedraw=True):
obj = FreeCAD.ActiveDocument.getObject(shapeType)
if not obj:
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", shapeType)
_Lines(obj)
_ViewProviderDDALines(obj.ViewObject)
if ifStore2Database:
database = getDatabaser4CurrentStage()
database.add(shapeType=shapeType, idxes=[0], args=args, ifRecord=True)
if ifTriggerRedraw:
obj.ViewObject.RedrawTrigger = True
return obj
def addPolyLine2Document(shapeType , ifStore2Database=False , pointsList=None, materialNo=1 , closed=False , ifTriggerRedraw=True):
obj = FreeCAD.ActiveDocument.getObject(shapeType)
if not obj:
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", shapeType)
_Lines(obj)
_ViewProviderDDAPolyLines(obj.ViewObject)
if closed:
if pointsList[0] != pointsList[-1]:
pointsList.append(pointsList[0])
if ifStore2Database: # polyLines only lives in DL part
database = getDatabaser4CurrentStage()
from loadDataTools import DDAPolyLine
database.add(shapeType, [0] ,[DDAPolyLine(pointsList,materialNo)] , ifRecord = True)
if ifTriggerRedraw:
obj.ViewObject.RedrawTrigger = True
return obj
def addCircles2Document(shapeType , ifStore2Database=False , pts=None , ifRecord=False):
obj = FreeCAD.ActiveDocument.getObject(shapeType)
if not obj:
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", shapeType)
_Lines(obj)
_ViewProviderDDAPoint(obj.ViewObject)
if ifStore2Database:
from loadDataTools import DDAPoint
for p in pts:
assert isinstance(p , DDAPoint)
database = getDatabaser4CurrentStage()
assert database
database.add(shapeType, [0] , pts,ifRecord)
obj.ViewObject.RedrawTrigger = True
return obj
def makeCircle(center , radius, placement=None, face=False, support=None, fname = 'Circle'):
'''makeCircle(radius,[placement,face,startangle,endangle]): 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 placement: typecheck([(placement, FreeCAD.Placement)], "makeCircle")
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython", fname)
_Circle(obj)
_ViewProviderDDAPoint(obj.ViewObject)
obj.Radius = radius
obj.ViewObject.Center = center
obj.ViewObject.BlockNo = -1
if not face: obj.ViewObject.DisplayMode = "Wireframe"
color = getParam(fname+'Color')
# if color:
obj.ViewObject.LineColor = color
# else:
# FreeCAD.Console.PrintError('in DDA.makeCircle. color not found.\n')
# obj.ViewObject.LineColor =( 0.0 , 0.0 , 0.0 , 1.0 )
if placement:
print '**********placement is not None ************\n'
else:
print '**********placement is None ************\n'
obj.Placement = placement
formatObject(obj)
select(obj)
FreeCAD.ActiveDocument.recompute()
setGraphRevised()
return obj
def addCircle2Document(center , radius, placement=None, face=False, support=None, fname = 'Circle'):
# if placement: typecheck([(placement, FreeCAD.Placement)], "addCircle2Document")
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", fname)
_Circle(obj)
_ViewProviderDDAPoint(obj.ViewObject)
obj.Radius = radius
obj.ViewObject.Center = center
# if not face: obj.ViewObject.DisplayMode = "Wireframe"
# color = getParam(fname+'Color')
# obj.ViewObject.LineColor = color
#
# formatObject(obj)
# select(obj)
# setGraphRevised()
return obj
def addPolygon2Document(points , placement=None , support=None , fname = 'Polygon' , materialIndex = 0 , ifColorGradual = False):
if not isinstance(points, list):
nlist = []
for v in points.Vertexes:
nlist.append(v.Point)
if fcgeo.isReallyClosed(points):
nlist.append(points.Vertexes[0].Point)
points = nlist
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython", fname)
_Polygon(obj)
_ViewProviderPolygon(obj.ViewObject)
obj.Points = points
# obj.ViewObject.ShapeColor = getParam(fname+'Color' , colorIndex)
# obj.ViewObject.FaceColor = getParam(fname+'Color' , colorIndex)
obj.ViewObject.Material = 1
obj.ViewObject.DisplayMode = "Polygon"
formatObject(obj)
select(obj)
setGraphRevised()
return obj
def refreshShape4Type(shapeType):
obj = FreeCAD.ActiveDocument.getObject(shapeType)
if obj:
obj.ViewObject.RedrawTrigger = True
def refreshAllShapes():
from DDADatabase import __allShapeTypes__
for shapeType in __allShapeTypes__:
refreshShape4Type(shapeType)
def updateTmpBoltElements():
'''
tmp function for compromise.
setting a array of points to coin, coin didn't update if first n points is the same.
use _ViewProviderDDALines.updateGeometry() and 'TunnelBoltsSelectionTool' for detail problem
'''
import DDADatabase
import Part
bolts = DDADatabase.tmpBoltElements
lines = []
for bolt in bolts:
lines.append(Part.makeLine(bolt.startPoint , bolt.endPoint))
shape = Part.Compound(lines)
obj = FreeCAD.ActiveDocument.getObject('TmpBoltElement')
if not obj:
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", 'TmpBoltElement')
_Lines(obj)
obj.ViewObject.Proxy = 0
obj.Shape = shape
FreeCADGui.ActiveDocument.getObject("TmpBoltElement").LineColor = (1.0,0.0,0.0)
def refreshPolygons():
obj = FreeCAD.ActiveDocument.getObject('Block')
if not obj:
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", 'Block')
_Polygons(obj)
_ViewProviderPolygons(obj.ViewObject)
obj.Points = [] # trigger redraw
obj.ViewObject.DisplayMode = "Shaded"
obj.ViewObject.RedrawTrigger = True # trigger update colors
return obj
def refreshBlockBoundaryLines():
obj = FreeCAD.ActiveDocument.getObject('BlockBoundaryLines')
if not obj:
obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython", 'BlockBoundaryLines')
_BlockBoundaryLines(obj)
_ViewProviderBlockBoundaryLines(obj.ViewObject)
obj.Points = [] # trigger redraw
obj.ViewObject.RedrawTrigger = True # trigger update colors
##################################################
##
## there is a list contains points of all polygons
##
##################################################
#
#__polygons__ = []
#__blocksMaterials__ = []
#
#
#def initPolygonSets():
# __polygons__ = []
#
#def addPolygons2Document(points , placement=None , support=None , fname = 'Polygon'):
# __polygons__.append(points)
#
#
#
#def polygonsAddedDone():
# obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", 'Block')
# _Polygons(obj)
# obj.Points = []
#
# import Part
# faces = []
# for pts in __polygons__:
# edges = []
# for i in range(len(pts)-1):
# edges.append(Part.makeLine(pts[i] , pts[(i+1)]))
#
# wire = Part.Wire(edges)
# faces.append(Part.Face(wire))
## print 'one face done'
# obj.Shape = Part.Compound(faces)
#
#
# colors = []
## __blocksMaterials__ = [1]*len(__polygons__)
# for i in range(len(__polygons__)):
# colors.append(__brushColors__[__blocksMaterials__[i]])
#
# _ViewProviderPolygons(obj.ViewObject)
# obj.ViewObject.DisplayMode = "Shaded"
# obj.ViewObject.Material = 1
#
## _ViewProviderPolygons(obj.ViewObject)
## obj.ViewObject.Proxy = 0
## formatObject(obj)
## select(obj)
## setGraphRevised()
# return obj
#
#
#---------------------------------------------------------------------------
# Python Features definitions
#---------------------------------------------------------------------------
class _ViewProviderDDA:
"A generic View Provider for Draft objects"
def __init__(self, obj):
obj.Proxy = self
self.appPart = obj.Object # obj.Object.ViewObject is obj
self.owner = obj # obj is ViewObject
obj.setEditorMode('Deviation' , 2)
obj.setEditorMode('BoundingBox' , 2)
obj.setEditorMode('ControlPoints' , 2)
obj.setEditorMode('DrawStyle' , 2)
obj.setEditorMode('DisplayMode' , 2)
obj.setEditorMode('Lighting' , 2)
obj.setEditorMode('LineWidth' , 2)
obj.setEditorMode('PointColor' , 2)
obj.setEditorMode('PointSize' , 2)
obj.setEditorMode('Selectable' , 2)
obj.setEditorMode('ShapeColor' , 2)
obj.setEditorMode('Transparency' , 2)
obj.setEditorMode('Visibility' , 2)
obj.setEditorMode('LineColor' , 2)
obj.addProperty("App::PropertyBool", "IfShowAssist", "Base", "if show StartPoint and EndPoint")
obj.setEditorMode('IfShowAssist' , 2)
obj.addProperty("App::PropertyBool", "RedrawTrigger", "Base", "if show StartPoint and EndPoint")
obj.setEditorMode('RedrawTrigger' , 2)
def attach(self, obj):
self.Object = obj.Object
return
def updateData(self, fp, prop):
return
def getDisplayModes(self, obj):
modes = []
return modes
def setDisplayMode(self, mode):
return mode
def onChanged(self, vp, prop):
return
def __getstate__(self):
return None
def __setstate__(self, state):
return None
# def setEdit(self, vp, mode):
# FreeCADGui.runCommand("Draft_Edit")
# return True
#
# def unsetEdit(self, vp, mode):
# if FreeCAD.activeDraftCommand:
# FreeCAD.activeDraftCommand.finish()
# return
# def getIcon(self):
# return(":/icons/Draft_Draft.svg")
class _ShapeModifier:
'''
shape modifier
'''
def __init__(self, obj):
obj.addProperty("App::PropertyString", "RelatedDocumentName", "Base",
"document name")
obj.addProperty("App::PropertyString", "RelatedObjectName", "Base",
"object name and No.")
obj.addProperty("App::PropertyString", "RelatedSubElement", "Base",
"sub element name and No.")
obj.addProperty("App::PropertyVectorList", "Points", "Base",
"Vertexes of the polygon")
obj.Proxy = self
self.owner = obj
def execute(self, fp):
self.createGeometry(fp)
def onChanged(self, fp, prop):
if prop in ["Points"]:
self.createGeometry(fp)
def createGeometry(self, fp):
pts = self.owner.Points
if len(pts)==2:
p1 = Part.Vertex(pts[0])
p2 = Part.Vertex(pts[1])
fp.Shape = Part.Compound([p1,p2])
class _Wire:
"The Wire object"
def __init__(self, obj):
obj.addProperty("App::PropertyVectorList", "Points", "Base",
"The vertices of the wire")
obj.addProperty("App::PropertyBool", "Closed", "Base",
"If the wire is closed or not")
obj.addProperty("App::PropertyLink", "Base", "Base",
"The base object is the wire is formed from 2 objects")
obj.addProperty("App::PropertyLink", "Tool", "Base",
"The tool object is the wire is formed from 2 objects")
obj.addProperty("App::PropertyVector","Start","Base",
"The start point of this line")
obj.addProperty("App::PropertyVector","End","Base",
"The end point of this line")
obj.addProperty("App::PropertyDistance","FilletRadius","Base","Radius to use to fillet the corners")
obj.Proxy = self
obj.Closed = False
self.Type = "Wire"
def execute(self, fp):
self.createGeometry(fp)
def onChanged(self, fp, prop):
if prop in ["Points", "Closed", "Base", "Tool"]:
self.createGeometry(fp)
def createGeometry(self, fp):
plm = fp.Placement
if fp.Base and (not fp.Tool): # make face
FreeCAD.Console.PrintError("Checking , In DDA.py 's makeWire use fp.Base\n")
if fp.Base.isDerivedFrom("Sketcher::SketchObject"):
shape = fp.Base.Shape.copy()
if fp.Base.Shape.isClosed():
shape = Part.Face(shape)
fp.Shape = shape
p = []
for v in shape.Vertexes: p.append(v.Point)
if fp.Points != p: fp.Points = p
elif fp.Base and fp.Tool: # concatenate 2 shapes : fp.Tool and fp.Base
if ('Shape' in fp.Base.PropertiesList) and ('Shape' in fp.Tool.PropertiesList):
sh1 = fp.Base.Shape.copy()
sh2 = fp.Tool.Shape.copy()
shape = sh1.fuse(sh2)
if fcgeo.isCoplanar(shape.Faces):
shape = fcgeo.concatenate(shape)
fp.Shape = shape
p = []
for v in shape.Vertexes: p.append(v.Point)
if fp.Points != p: fp.Points = p
elif fp.Points:
if fp.Points[0] == fp.Points[-1]:
if not fp.Closed: fp.Closed = True
fp.Points.pop()
if fp.Closed and (len(fp.Points) > 2):
shape = Part.makePolygon(fp.Points + [fp.Points[0]])
shape = Part.Face(shape)
else:
edges = []
pts = fp.Points[1:]
lp = fp.Points[0]
for p in pts:
edges.append(Part.Line(lp, p).toShape())
lp = p
shape = Part.Wire(edges)
fp.Shape = shape
fp.Placement = plm
class _Lines:
'''
data class for _ViewProviderLines ,
'''
def __init__(self , obj):
# obj.addProperty("App::PropertyVectorList", "Points", "Base", "Vertexes of the polygon")
obj.Proxy = self
self.Type = "Lines"
def onChanged(self, fp, prop):
"Do something when a property has changed"
if prop in ["Points"]:
self.createGeometry(fp)
def execute(self, fp):
"Do something when doing a recomputation, this method is mandatory"
pass
def createGeometry(self, fp):
pass
class _BlockBoundaryLines:
'''
data class for _ViewProviderLines ,
'''
def __init__(self , obj):
obj.addProperty("App::PropertyVectorList", "Points", "Base", "Vertexes of the polygon")
obj.Proxy = self
self.Type = "Lines"
def onChanged(self, fp, prop):
"Do something when a property has changed"
if prop in ["Points"]:
self.createGeometry(fp)
def execute(self, fp):
"Do something when doing a recomputation, this method is mandatory"
pass
def createGeometry(self, fp):
pass
class _Polygons:
def __init__(self , obj):
obj.addProperty("App::PropertyVectorList", "Points", "Base", "Vertexes of the polygon")
obj.Proxy = self
self.Type = "Polygon"
def onChanged(self, fp, prop):
"Do something when a property has changed"
if prop in ["Points"]:
self.createGeometry(fp)
def execute(self, fp):
"Do something when doing a recomputation, this method is mandatory"
FreeCAD.Console.PrintMessage("Recompute Python Box feature\n")
self.createGeometry(fp)
def createGeometry(self, fp):
import Part
from DDADatabase import df_inputDatabase
blocks = df_inputDatabase.blocks
faces = []
for block in blocks:
pts = [(p[1],p[2],-1) for p in block.vertices]
if pts[0]!=pts[-1]:
pts.append(pts[0])
edges = []
for i in range(len(pts)-1):
edges.append(Part.makeLine(pts[i] , pts[(i+1)]))
try:
wire = Part.Wire(edges)
faces.append(Part.Face(wire))
except:
raise
# print 'one face done'
fp.Shape = Part.Compound(faces)
class _Circle:
"The Circle object"
def __init__(self, obj):
obj.Proxy = self
self.owner = obj
obj.addProperty("App::PropertyDistance","Radius","Base",
"Radius of the circle")
def execute(self, fp):
self.createGeometry(fp)
def onChanged(self, fp, prop):
if prop in ["Radius"]:
self.createGeometry(fp)
def createGeometry(self,fp):
return
import Part
c = self.owner.ViewObject.Center
shape = Part.makeCircle(fp.Radius,self.owner.ViewObject.Center,Vector(0,0,1))
# center = Part.Vertex(self.owner.ViewObject.Center)
tmp = Vector(c[0] , c[1] , c[2])
p1 = Vector(tmp[0]-self.owner.Radius/2 , tmp[1] , tmp[2])
p2 = Vector(tmp[0]+self.owner.Radius/2 , tmp[1] , tmp[2])
p3 = Vector(tmp[0] , tmp[1]-self.owner.Radius/2 , tmp[2])
p4 = Vector(tmp[0] , tmp[1]+self.owner.Radius/2 , tmp[2])
line1 = Part.makeLine(p1 , p2)
line2 = Part.makeLine(p3 , p4)
# print self.owner.ViewObject.Center
# self.owner.ViewObject.PointSize = 100
fp.Shape = Part.Compound([shape,line1 , line2])
# fp.Shape = center
class _ViewProviderDDAPoint(_ViewProviderDDA):
def __init__(self, obj ):
obj.Proxy = self
self.owner = obj # this viewObject
obj.addProperty("App::PropertyVector", "Center", "Base", "material of the additional lines")
_ViewProviderDDA.__init__(self, obj)
def onChanged(self, vp, prop):
if prop == "RedrawTrigger":
self.updateGeometry()
def updateGeometry(self):
label = self.appPart.Label
# confirm color
color = getParam(label+'Color')
assert color
self.color.rgb.setValue(color[0],color[1],color[2])
# get centers
import DDADatabase
database = getDatabaser4CurrentStage()
assert database
if label=='FixedPoint':
points = database.fixedPoints
elif label=='MeasuredPoint':
points = database.measuredPoints
elif label=='LoadingPoint':
points = database.loadingPoints
elif label=='HolePoint':
points = database.holePoints
pts = [ p for p in points if p.visible]
self.updateCircels(pts)
def updateCircels(self, points):
import math
rad = math.pi/180.0