-
Notifications
You must be signed in to change notification settings - Fork 2
/
DDATools.py
1412 lines (1219 loc) · 57.4 KB
/
DDATools.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 *
#* *
#***************************************************************************
#****************************************
#Modified by Silver <[email protected]>
#2013-11-27
#****************************************
import FreeCAD
FreeCAD.Console.PrintMessage( 'DDATools moudle begin\n')
__title__ = "FreeCAD DDA Workbench GUI Tools"
__author__ = "Cheng Xiaolong"
FreeCAD.Console.PrintMessage ('Importing DDATools moudle\n')
#---------------------------------------------------------------------------
# Generic stuff
#---------------------------------------------------------------------------
import os, FreeCAD, FreeCADGui, Part, WorkingPlane, math, re
from pivy import coin
from FreeCAD import Vector
#from draftlibs import fcvec, fcgeo
import fcvec, fcgeo
from functools import partial
import Base
from drawGui import todo , QtCore, QtGui
from TrackerTools import *
FreeCAD.Console.PrintMessage ('base moudles import done\n')
def translate(context, text):
"convenience function for Qt translator"
return QtGui.QApplication.translate(context, text, None, QtGui.QApplication.UnicodeUTF8).toUtf8()
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)
# last snapped objects, for quick intersection calculation
lastObj = [0, 0]
# set modifier keys
MODS = ["shift", "ctrl", "alt"]
MODCONSTRAIN = MODS[Base.getParam("modconstrain")]
MODSNAP = MODS[Base.getParam("modsnap")]
MODALT = MODS[Base.getParam("modalt")]
def getSupport(args):
"returns the supporting object and sets the working plane"
snapped = FreeCADGui.ActiveDocument.ActiveView.getObjectInfo((args["Position"][0], args["Position"][1]))
if not snapped: return None
obj = None
plane.save()
try:
obj = FreeCAD.ActiveDocument.getObject(snapped['Object'])
shape = obj.Shape
component = getattr(shape, snapped["Component"])
if plane.alignToFace(component, 0) \
or plane.alignToCurve(component, 0): # 这一句要研究下,‘0’是什么意思,度数吗?
self.display(plane.axis)
except:
FreeCAD.Console.PrintWarning("function 'getSupport' get Exceptions\n")
return obj
def hasMod(args, mod):
"checks if args has a specific modifier"
if mod == "shift":
return args["ShiftDown"]
elif mod == "ctrl":
return args["CtrlDown"]
elif mod == "alt":
return args["AltDown"]
def setMod(args, mod, state):
"sets a specific modifier state in args"
if mod == "shift":
args["ShiftDown"] = state
elif mod == "ctrl":
args["CtrlDown"] = state
elif mod == "alt":
args["AltDown"] = state
def snapPoint(target, point, cursor, ctrl=False):
'''
Snap function used by the Draft tools
Currently has two modes: passive and active. Pressing CTRL while
clicking puts you in active mode:
- In passive mode (an open circle appears), your point is
snapped to the nearest point on any underlying geometry.
- In active mode (ctrl pressed, a filled circle appears), your point
can currently be snapped to the following points:
- Nodes and midpoints of all Part shapes
- Nodes and midpoints of lines/wires
- Centers and quadrant points of circles
- Endpoints of arcs
- Intersection between line, wires segments, arcs and circles
- When constrained (SHIFT pressed), Intersections between
constraining axis and lines/wires
'''
def getConstrainedPoint(edge, last, constrain):
"check for constrained snappoint"
p1 = edge.Vertexes[0].Point
p2 = edge.Vertexes[-1].Point
ar = []
if (constrain == 0):
if ((last.y > p1.y) and (last.y < p2.y) or (last.y > p2.y) and (last.y < p1.y)):
pc = (last.y - p1.y) / (p2.y - p1.y) # 按比例计算,如为线段,下行中的cp计算结果应该就在edge上
cp = (Vector(p1.x + pc * (p2.x - p1.x), p1.y + pc * (p2.y - p1.y), p1.z + pc * (p2.z - p1.z)))
ar.append([cp, 1, cp]) # constrainpoint
if (constrain == 1):
if ((last.x > p1.x) and (last.x < p2.x) or (last.x > p2.x) and (last.x < p1.x)):
pc = (last.x - p1.x) / (p2.x - p1.x)
cp = (Vector(p1.x + pc * (p2.x - p1.x), p1.y + pc * (p2.y - p1.y), p1.z + pc * (p2.z - p1.z)))
ar.append([cp, 1, cp]) # constrainpoint
return ar
def getPassivePoint(info):
"returns a passive snap point"
cur = Vector(info['x'], info['y'], info['z'])
return [cur, 2, cur]
def getScreenDist(dist, cursor):
"returns a 3D distance from a screen pixels distance"
p1 = FreeCADGui.ActiveDocument.ActiveView.getPoint(cursor)
p2 = FreeCADGui.ActiveDocument.ActiveView.getPoint((cursor[0] + dist, cursor[1]))
return (p2.sub(p1)).Length # 好像计算结果是屏幕上两个点的x方向距离,为什么 ,后面在计算snapRadius时用到,用来计算半径
def getGridSnap(target, point):
"returns a grid snap point if available"
if target.grid:
return target.grid.getClosestNode(point)
return None
def getPerpendicular(edge, last):
"returns a point on an edge, perpendicular to the given point"
dv = last.sub(edge.Vertexes[0].Point)
nv = fcvec.project(dv, fcgeo.vec(edge))
np = (edge.Vertexes[0].Point).add(nv) # 将edge作直线看,np是线外点到些直线的垂点
return np
# checking if alwaySnap setting is on
extractrl = False
if Base.getParam("alwaysSnap"):
extractrl = ctrl
ctrl = True
# setting Radius , the raius is for snapping , not radius of circle
radius = getScreenDist(Base.getParam("snapRange"), cursor)
# checking if parallel to one of the edges of the last objects
target.snap.off()
target.extsnap.off()
if (len(target.node) > 0):
for o in [lastObj[1], lastObj[0]]: # 前文中申明,last snapped objects , 用来快速求交
if o:
ob = target.doc.getObject(o)
if ob:
edges = ob.Shape.Edges
if len(edges) < 10:
for e in edges:
if isinstance(e.Curve, Part.Line):
last = target.node[len(target.node) - 1]
de = Part.Line(last, last.add(fcgeo.vec(e))).toShape()
np = getPerpendicular(e, point) # point为函数参数,计算point到e的垂点
if (np.sub(point)).Length < radius: # snap 成功
target.snap.coords.point.setValue((np.x, np.y, np.z))
target.snap.setMarker("circle")
target.snap.on() # target.snap和target.extsnap区别
target.extsnap.p1(e.Vertexes[0].Point)
target.extsnap.p2(np)
target.extsnap.on()
point = np
else:
last = target.node[len(target.node) - 1]
de = Part.Line(last, last.add(fcgeo.vec(e))).toShape()
np = getPerpendicular(de, point)
if (np.sub(point)).Length < radius: # 取edge首尾端点所成线段算距离,为何有效
target.snap.coords.point.setValue((np.x, np.y, np.z))
target.snap.setMarker("circle")
target.snap.on()
point = np
# check if we snapped to something
snapped = target.view.getObjectInfo((cursor[0], cursor[1]))
if (snapped == None):
# nothing has been snapped, check fro grid snap
gpt = getGridSnap(target, point) # 选取最近点
if gpt:
if radius != 0:
dv = point.sub(gpt)
if dv.Length <= radius:
target.snap.coords.point.setValue((gpt.x, gpt.y, gpt.z))
target.snap.setMarker("point")
target.snap.on()
return gpt
return point
else:
# we have something to snap
obj = target.doc.getObject(snapped['Object'])
if hasattr(obj.ViewObject, "Selectable"):
if not obj.ViewObject.Selectable:
return point
if not ctrl:
# are we in passive snap?
snapArray = [getPassivePoint(snapped)]
else:
snapArray = []
comp = snapped['Component'] # 'Component'保存什么?
if obj.isDerivedFrom("Part::Feature"):
if "Edge" in comp:
# get the stored objects to calculate intersections
intedges = []
if lastObj[0]:
lo = target.doc.getObject(lastObj[0])
if lo:
if lo.isDerivedFrom("Part::Feature"):
intedges = lo.Shape.Edges
nr = int(comp[4:]) - 1 # 这计算的是什么?
edge = obj.Shape.Edges[nr]
for v in edge.Vertexes:
snapArray.append([v.Point, 0, v.Point]) # 点和数放在一起,中间这一位什么意思?
if isinstance(edge.Curve, Part.Line):
# the edge is a line
midpoint = fcgeo.findMidpoint(edge)
snapArray.append([midpoint, 1, midpoint]) # 点和数放在一起,中间这一位什么意思?
if (len(target.node) > 0):
last = target.node[len(target.node) - 1] # target.node 中保存的是点
snapArray.extend(getConstrainedPoint(edge, last, target.constrain))
np = getPerpendicular(edge, last)
snapArray.append([np, 1, np])
elif isinstance (edge.Curve, Part.Circle):
# the edge is an arc
rad = edge.Curve.Radius
pos = edge.Curve.Center
for i in [0, 30, 45, 60, 90, 120, 135, 150, 180, 210, 225, 240, 270, 300, 315, 330]:
ang = math.radians(i)
cur = Vector(math.sin(ang) * rad + pos.x, math.cos(ang) * rad + pos.y, pos.z)
snapArray.append([cur, 1, cur])
for i in [15, 37.5, 52.5, 75, 105, 127.5, 142.5, 165, 195, 217.5, 232.5, 255, 285, 307.5, 322.5, 345]:
ang = math.radians(i)
cur = Vector(math.sin(ang) * rad + pos.x, math.cos(ang) * rad + pos.y, pos.z)
snapArray.append([cur, 0, pos]) # 点和数放在一起,中间这一位什么意思?保存东西还可以不一样
for e in intedges:
# get the intersection points
pt = fcgeo.findIntersection(e, edge)
if pt:
for p in pt:
snapArray.append([p, 3, p])
elif "Vertex" in comp:
# directly snapped to a vertex
p = Vector(snapped['x'], snapped['y'], snapped['z'])
snapArray.append([p, 0, p])
elif comp == '':
# workaround for the new view provider
p = Vector(snapped['x'], snapped['y'], snapped['z'])
snapArray.append([p, 2, p])
else:
snapArray = [getPassivePoint(snapped)]
elif Base.getType(obj) == "Dimension":
for pt in [obj.Start, obj.End, obj.Dimline]:
snapArray.append([pt, 0, pt])
elif Base.getType(obj) == "Mesh":
for v in obj.Mesh.Points:
snapArray.append([v.Vector, 0, v.Vector])
if not lastObj[0]: # 为什么
lastObj[0] = obj.Name
lastObj[1] = obj.Name
if (lastObj[1] != obj.Name):
lastObj[0] = lastObj[1]
lastObj[1] = obj.Name
# calculating shortest distance
shortest = 1000000000000000000
spt = Vector(snapped['x'], snapped['y'], snapped['z'])
newpoint = [Vector(0, 0, 0), 0, Vector(0, 0, 0)]
for pt in snapArray:
if pt[0] == None: FreeCAD.Console.PrintMessage ("snapPoint: debug 'i[0]' is 'None'")
di = pt[0].sub(spt)
if di.Length < shortest:
shortest = di.Length
newpoint = pt
if radius != 0:
dv = point.sub(newpoint[2])
if (not extractrl) and (dv.Length > radius):
newpoint = getPassivePoint(snapped)
target.snap.coords.point.setValue((newpoint[2].x, newpoint[2].y, newpoint[2].z))
if (newpoint[1] == 1):
target.snap.setMarker("square")
elif (newpoint[1] == 0):
target.snap.setMarker("point")
elif (newpoint[1] == 3):
target.snap.setMarker("square")
else:
target.snap.setMarker("circle")
target.snap.on()
return newpoint[2]
def getPoint(target, args, mobile=False, sym=False, workingplane=True):
'''
Function used by the Draft Tools.
returns a constrained 3d point and its original point.
if mobile=True, the constraining occurs from the location of
mouse cursor when Shift is pressed, otherwise from last entered
point. If sym=True, x and y values stay always equal. If workingplane=False,
the point wont be projected on the Working Plane.
'''
ui = FreeCADGui.DDAToolbar
view = FreeCADGui.ActiveDocument.ActiveView
point = view.getPoint(args["Position"][0], args["Position"][1])
point = snapPoint(target, point, args["Position"], hasMod(args, MODSNAP))
if (not plane.weak) and workingplane:
# working plane was explicitely selected - project onto it
viewDirection = view.getViewDirection()
if FreeCADGui.ActiveDocument.ActiveView.getCameraType() == "Perspective":
camera = FreeCADGui.ActiveDocument.ActiveView.getCameraNode()
p = camera.getField("position").getValue()
# view is from camera to point:
viewDirection = point.sub(Vector(p[0], p[1], p[2]))
# if we are not snapping to anything, project along view axis,
# otherwise perpendicularly
if view.getObjectInfo((args["Position"][0], args["Position"][1])):
pass
# point = plane.projectPoint(point)
else:
point = plane.projectPoint(point, viewDirection)
ctrlPoint = Vector(point.x, point.y, point.z)
if (hasMod(args, MODCONSTRAIN)): # constraining
if mobile and (target.constrain == None):
target.node.append(point) # target.node中保存的是点,竟然这样添加
point = constrainPoint(target, point, mobile=mobile, sym=sym)
else:
target.constrain = None
ui.xValue.setEnabled(True)
ui.yValue.setEnabled(True)
# ui.zValue.setEnabled(True)
if target.node:
if target.featureName == "Rectangle":
ui.displayPoint(point, target.node[0], plane=plane)
else:
ui.displayPoint(point, target.node[-1], plane=plane)
else: ui.displayPoint(point, plane=plane)
return point, ctrlPoint
def getSupport(args):
"returns the supporting object and sets the working plane"
snapped = FreeCADGui.ActiveDocument.ActiveView.getObjectInfo((args["Position"][0], args["Position"][1]))
if not snapped: return None
obj = None
plane.save()
try:
obj = FreeCAD.ActiveDocument.getObject(snapped['Object'])
shape = obj.Shape
component = getattr(shape, snapped["Component"])
if plane.alignToFace(component, 0) \
or plane.alignToCurve(component, 0): # 这一句要研究下,‘0’是什么意思,度数吗?
self.display(plane.axis)
except:
pass
return obj
#---------------------------------------------------------------------------
# Geometry constructors
#---------------------------------------------------------------------------
class Creator(object):
"A generic DDA Shape Creator used by creation tools such as line or arc"
def __init__(self,shapeType = 'xxx'):
# self.commitList = []
self.shapeType = shapeType
def Activated(self, name="None"):
FreeCAD.Console.PrintMessage( 'Creator activing\n')
if FreeCAD.activeDDACommand:
FreeCAD.activeDDACommand.finish()
self.ui = None
self.call = None
self.doc = None
self.support = None
# self.commitList = []
self.doc = FreeCAD.ActiveDocument
self.view = FreeCADGui.ActiveDocument.ActiveView
self.featureName = name
# debug message
print self.shapeType , ' in Creator'
# import Base
# Base.__lastShapeName__=self.shapeType
#
if not self.doc:
FreeCAD.Console.PrintMessage( 'FreeCAD.ActiveDocument get failed\n')
self.finish()
else:
FreeCAD.activeDDACommand = self # FreeCAD.activeDDACommand 在不同的时间会接收不同的命令
# self.ui = FreeCADGui.DDADockWidget
FreeCAD.Console.PrintMessage('setting mouse cursor in Creator\n')
# self.ui.cross(True)
# self.ui.sourceCmd = self
FreeCAD.Console.PrintMessage('self.ui works fine\n')
# self.ui.setTitle(name)
# self.ui.show()
rot = self.view.getCameraNode().getField("orientation").getValue() # camera 的朝向,一个matrix
upv = Vector(rot.multVec(coin.SbVec3f(0, 1, 0)).getValue()) # camera 的朝上方向
plane.setup(fcvec.neg(self.view.getViewDirection()), Vector(0, 0, 0), upv)
self.node = []
self.pos = []
self.constrain = None
self.obj = None
self.snap = snapTracker()
self.extsnap = lineTracker(dotted=True)
self.planetrack = PlaneTracker()
# 源代码中使用Draft.getParam(...)作判断来确定是否使用gridTracker()
self.grid = gridTracker()
import Base
Base.enableSelectionObserver(False)
import DDAToolbars
FreeCADGui.DDAToolBar = DDAToolbars.lineToolbar
FreeCADGui.DDAToolBar.on()
self.ui = FreeCADGui.DDAToolBar
self.ui.sourceCmd = self
def IsActive(self):
if FreeCADGui.ActiveDocument:
return True
else:
return False
def finish(self):
self.snap.finalize()
self.extsnap.finalize()
self.node = []
self.planetrack.finalize()
if self.grid: self.grid.finalize()
if self.support: plane.restore()
FreeCAD.activeDDACommand = None
if self.ui:
FreeCAD.Console.PrintMessage('closing UI\n')
self.ui.offUi()
self.ui.cross(False)
self.ui.sourceCmd = None
# msg("")
if self.call:
self.view.removeEventCallback("SoEvent", self.call)
self.call = None
# if self.commitList:
# todo.delayCommit(self.commitList)
# self.commitList = []
import Base
Base.enableSelectionObserver(True)
# def commit(self, name, func):
# "stores partial actions to be committed to the FreeCAD document"
# self.commitList.append((name, func))
class Line(Creator):
"The Line FreeCAD command definition"
def __init__(self, wiremode=False , shapeType = 'xxx' , mustColse=False):
self.isWire = wiremode
self.shapeType = shapeType
self.mustColse = mustColse
self.ifPolyLine = True
if shapeType == 'MaterialLine':
self.ifPolyLine = False
def GetResources(self):
return {
#'Pixmap' : 'Draft_Line',
#'Accel' : "L,I",
'MenuText': "Line",
'ToolTip': "Creates a 2-point line. CTRL to snap, SHIFT to constrain"}
def Activated(self, name="Line"):
FreeCAD.Console.PrintMessage( 'Line activing\n')
Creator.Activated(self, name)
if self.doc:
self.obj = None
self.linetrack = lineTracker()
self.constraintrack = lineTracker(dotted=True)
self.obj = self.doc.getObject('Line')
if not self.obj:
self.obj = self.doc.addObject("Part::Feature", 'Line') # 新建一个用于显示的object
# self.obj.ViewObject.Selectable = False
#Draft.formatObject(self.obj)
#if not Draft.getParam("UiMode"): self.makeDumbTask()
self.call = self.view.addEventCallback("SoEvent", self.action)
msg( translate('line',"Pick first point:\n"))
# import DDAToolbars
# FreeCADGui.DDAToolBar = DDAToolbars.lineToolbar
# FreeCADGui.DDAToolBar.on()
# self.ui = FreeCADGui.DDAToolBar
# self.ui.sourceCmd = self
def finish(self, closed=False, ifSave=True , materialNo=1):
"terminates the operation and closes the poly if asked"
#if not Draft.getParam("UiMode"):
FreeCAD.Console.PrintMessage( 'finishing\n')
FreeCADGui.Control.closeDialog()
if self.obj:
self.obj.Shape = Part.Shape([])
self.obj.ViewObject.Visibility = False
# old = self.obj.Name
# todo.delay(self.doc.removeObject, old)
self.obj = None # 可能到些都是辅助图元,下面if里的内容才是真正的最终图元 ,self.commit(...)里的内容才是真正的图元
tmpObj = None
# if self.shapeType == 'BoundaryLine' and len(self.node) > 2:
# Base.addLines2Document(self.node , True , face=False, support=self.support , fname = self.shapeType)
# elif(len(self.node) > 1):
# tmpObj = Base.addLines2Document(self.node , True , face=False, support=self.support , fname = self.shapeType)
from loadDataTools import DDALine
if ifSave:
import Base
if self.shapeType!= 'MaterialLine':
tmpObj = Base.addPolyLine2Document(self.shapeType, ifStore2Database = True , pointsList=self.node , materialNo=materialNo , closed=closed)
if self.ui:
self.linetrack.finalize()
self.constraintrack.finalize()
Creator.finish(self)
return tmpObj
def action(self, arg):
"scene event handler"
if arg["Type"] == "SoKeyboardEvent":
FreeCAD.Console.PrintMessage('keyboardEvent')
if arg["Key"] == "ESCAPE":
FreeCAD.Console.PrintError('Escape pressed, finising\n')
self.finish(closed = self.mustColse)
elif arg["Type"] == "SoLocation2Event": # mouse movement detection
point, ctrlPoint = getPoint(self, arg)
#FreeCAD.Console.PrintMessage('setting mouse cursor in Line action\n')
self.ui.cross(True)
self.linetrack.p2(point)
# Draw constraint tracker line.
# if hasMod(arg, MODCONSTRAIN):
# self.constraintrack.p1(point)
# self.constraintrack.p2(ctrlPoint)
# self.constraintrack.on()
# else:
# self.constraintrack.off()
elif arg["Type"] == "SoMouseButtonEvent":
if (arg["State"] == "DOWN") and (arg["Button"] == "BUTTON1"):
if (arg["Position"] == self.pos):
FreeCAD.Console.PrintError('same point, finising\n')
self.finish(closed=self.mustColse, cont=True)
else:
if not self.node: self.support = getSupport(arg)
point, ctrlPoint = getPoint(self, arg)
self.pos = arg["Position"]
self.node.append(point)
self.linetrack.p1(point)
self.drawSegment(point)
if len(self.node)==2 and not self.ifPolyLine: # currently, materialLine need this
self.finish(closed = self.mustColse)
# if (not self.isWire and len(self.node) == 2):
# FreeCAD.Console.PrintError('not Wire and len(node)==2, finising\n')
# self.finish(closed=False, cont=True)
# if (len(self.node) > 2):
# # DNC: allows to close the curve
# # by placing ends close to each other
# # with tol = Draft tolerance
# # old code has been to insensitive
# # if fcvec.equals(point,self.node[0]):
# if ((point - self.node[0]).Length < Base.tolerance()):
# self.undolast()
# FreeCAD.Console.PrintError('< tolerance, finising\n')
# self.finish(closed=True, cont=True)
# msg( "Wire has been closed\n")
def drawSegment(self, point):
"draws a new segment"
if (len(self.node) == 1):
self.linetrack.on()
msg(translate("draft", "Pick next point:\n"))
self.planetrack.set(self.node[0])
elif (len(self.node) == 2):
last = self.node[len(self.node) - 2] # 参数中的point是最新的点,取倒数第二个点和point绘线
newseg = Part.Line(last, point).toShape()
self.obj.Shape = newseg
self.obj.ViewObject.Visibility = True
if self.isWire:
msg(translate("draft", "Pick next point, or (F)inish or (C)lose:\n"))
else:
currentshape = self.obj.Shape
last = self.node[len(self.node) - 2]
newseg = Part.Line(last, point).toShape()
if not currentshape:
newshape = newseg
else :
newshape = currentshape.fuse(newseg)
self.obj.Shape = newshape
msg(translate("draft", "Pick next point, or (F)inish or (C)lose:\n"))
# def wipe(self):
# "removes all previous segments and starts from last point"
# if len(self.node) > 1:
# FreeCAD.Console.PrintMessage ("nullifying")
# # self.obj.Shape.nullify() - for some reason this fails
# self.obj.ViewObject.Visibility = False
# self.node = [self.node[-1]] # 清空了除最后一个点外保存的所有点
# FreeCAD.Console.PrintMessage ("setting trackers")
# self.linetrack.p1(self.node[0])
# self.planetrack.set(self.node[0])
# msg(translate("draft", "Pick next point:\n"))
# FreeCAD.Console.PrintMessage ("done\n")
def numericInput(self, numx, numy, numz):
"this function gets called by the toolbar when valid x, y, and z have been entered there"
point = Vector(numx, numy, numz)
self.node.append(point)
self.linetrack.p1(point)
self.drawSegment(point)
# if (not self.isWire and len(self.node) == 2):
# self.finish(False, cont=True)
#self.ui.setNextFocus()
class Rectangle(Creator):
"the DDA_Rectangle FreeCAD command definition"
def GetResources(self):
return {
#'Pixmap' : 'Draft_Rectangle',
# 'Accel' : "R, E",
'MenuText': "Rectangle",
'ToolTip': "Creates a 2-point rectangle. CTRL to snap"}
def Activated(self):
Creator.Activated(self, "Rectangle")
if self.ui:
self.refpoint = None
self.ui.pointUi()
#self.ui.extUi()
self.call = self.view.addEventCallback("SoEvent", self.action)
self.rect = rectangleTracker()
msg( "Pick first point:\n")
def finish(self, closed=False, cont=False):
"terminates the operation and closes the poly if asked"
Creator.finish(self)
if self.ui:
self.rect.off()
self.rect.finalize()
if cont and self.ui:
if self.ui.continueMode:
self.Activated()
def createObject(self):
"creates the final object in the current doc"
p1 = self.node[0]
p3 = self.node[-1]
diagonal = p3.sub(p1) # diagonal 对角线
p2 = p1.add(fcvec.project(diagonal, plane.v)) # 添加plane.v方向的偏移量
p4 = p1.add(fcvec.project(diagonal, plane.u))
length = p4.sub(p1).Length
if abs(fcvec.angle(p4.sub(p1), plane.u, plane.axis)) > 1: length = -length
height = p2.sub(p1).Length
if abs(fcvec.angle(p2.sub(p1), plane.v, plane.axis)) > 1: height = -height
p = plane.getRotation()
p.move(p1)
# try:
self.commit("Create Rectangle",
partial(Base.makeRectangle, length, height,
p, False, support=self.support))
# except:
# print "Draft: error delaying commit"
self.finish(cont=True)
def action(self, arg):
"scene event handler"
if arg["Type"] == "SoKeyboardEvent":
if arg["Key"] == "ESCAPE":
self.finish()
elif arg["Type"] == "SoLocation2Event": # mouse movement detection
point, ctrlPoint = getPoint(self, arg, mobile=True)
self.rect.update(point)
self.ui.cross(True)
elif arg["Type"] == "SoMouseButtonEvent":
if (arg["State"] == "DOWN") and (arg["Button"] == "BUTTON1"):
if (arg["Position"] == self.pos):
self.finish()
else:
if not self.node: self.support = getSupport(arg)
point, ctrlPoint = getPoint(self, arg)
self.appendPoint(point)
def numericInput(self, numx, numy, numz):
"this function gets called by the toolbar when valid x, y, and z have been entered there"
point = Vector(numx, numy, numz)
self.appendPoint(point)
def appendPoint(self, point):
self.node.append(point)
if (len(self.node) > 1):
FreeCAD.Console.PrintMessage('DDA_Rectangle create object\n')
self.rect.update(point)
self.createObject()
else:
msg("Pick opposite point:\n")
# self.ui.setRelative()
self.rect.setorigin(point)
self.rect.on()
self.planetrack.set(point)
class Circle(Creator):
"the Draft_Arc FreeCAD command definition"
def __init__(self , shapeType = 'xxx'):
self.closedCircle = True
self.featureName = "Circle"
self.shapeType = shapeType
self.center = None
def GetResources(self):
return {
'MenuText': "Circle",
'ToolTip': "Creates a circle"}
def Activated(self):
Creator.Activated(self, self.featureName)
if self.ui:
self.step = 0
self.center = None
self.rad = None
self.call = self.view.addEventCallback("SoEvent", self.action)
msg(QtGui.QApplication.translate('Circle',"Pick center point:\n"))
def finish(self, closed=True, cont=False):
"finishes the arc"
Creator.finish(self)
tmpObj = None
if self.center :
import Base
print 'Circle ending'
view=FreeCADGui.ActiveDocument.ActiveView
obj = view.getObjectInfo(view.getCursorPos())
objName , objIdx = Base.getRealTypeAndIndex(obj['Object'])
assert objName == 'Block'
subName , subIdx = Base.getRealTypeAndIndex(obj['Component'])
tmpObj = self.drawCircle(subIdx)
# from loadDataTools import DDAPoint
# Base.addCircles2Document(self.shapeType, ifStore2Database=True \
# , pts=[DDAPoint(self.center[0],self.center[1])], ifRecord = True)
#
print 'DDAPoint with center (%f , %f) is drawn'%(self.center[0],self.center[1])
# FreeCADGui.runCommand('DDA_DCChangesConfirm')
return tmpObj
def drawCircle(self , blockNo):
from loadDataTools import DDAPoint
import Base
point = DDAPoint(self.center[0],self.center[1])
point.blockNo = blockNo
return Base.addCircles2Document(self.shapeType, ifStore2Database=True \
, pts= [point], ifRecord = True)
def action(self, arg):
"scene event handler"
if arg["Type"] == "SoKeyboardEvent":
if arg["Key"] == "ESCAPE":
self.finish()
elif arg["Type"] == "SoLocation2Event":
point, ctrlPoint = getPoint(self, arg)
# this is to make sure radius is what you see on screen
self.ui.cross(True)
elif arg["Type"] == "SoMouseButtonEvent":
if (arg["State"] == "DOWN") and (arg["Button"] == "BUTTON1"):
point, ctrlPoint = getPoint(self, arg)
self.center = FreeCAD.Vector(point[0],point[1],0)
import Base
self.rad = Base.__radius4Points__
self.finish()
#
# def drawArc(self):
# "actually draws the FreeCAD object"
# print '**********draw Circle*************\n'
# p = plane.getRotation()
# p.move(self.center)
# tmpObj = None
## tmpObj = Base.makeCircle( self.center , self.rad, p , face=False, support=self.support , fname = self.shapeType)
# if self.closedCircle:
# tmpObj = Base.makeCircle( self.center , self.rad, p , face=False, support=self.support , fname = self.shapeType)
# else:
# print "Draft: error delaying commit"
# return tmpObj
def numericInput(self, numx, numy, numz):
"this function gets called by the toolbar when valid x, y, and z have been entered there"
self.center = Vector(numx, numy, numz)
self.node = [self.center]
self.arctrack.setCenter(self.center)
self.arctrack.on()
self.ui.radiusUi()
self.ui.setNextFocus()
msg("Pick radius:\n")
class DataTable(QtCore.QObject):
'''
for jointSets , tunnels , format the table manipulations
'''
dataInvalidSignal = QtCore.pyqtSignal( int )
saveDataSignal = QtCore.pyqtSignal()
def __init__(self , row , column , headers , firstColumnDropDown = False , lastColumnNoEdit = True , columnWidth = None , VHeaders = None):
super(DataTable, self).__init__()
self.__dataValid = False
self.__firstColumnDropDown = firstColumnDropDown
self.__lastColumnNoEdit = lastColumnNoEdit
self.__normalColorBrush = QtGui.QBrush(QtGui.QColor(255,255,255))
self.__errorColorBrush = QtGui.QBrush(QtGui.QColor(255,160,30))
self.table = QtGui.QTableWidget(0 , column)
self.table.setHorizontalHeaderLabels(headers)
# print 'row : %d , column : %d'%(row,column)
for i in range(row):
self.addRow()
if VHeaders:
self.table.setVerticalHeaderLabels(VHeaders)
self.__columnWidth = columnWidth
if columnWidth != None :
# print 'set column width to ' , columnWidth
for i in range(column):
self.table.setColumnWidth( i , columnWidth)
self.table.cellChanged.connect(self.checkCell)
self.table.cellClicked.connect(self.handleClick)
def getColumnStartIndex(self):
if self.__firstColumnDropDown :
return 1
return 0
def getColumnEndIndex(self):
if self.__lastColumnNoEdit :
return self.table.columnCount()-1
return self.table.columnCount()
def addDelButton4Row(self, row):
'add the del button for the row'
newItem = QtGui.QTableWidgetItem("Del")
newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
self.table.setItem(row, self.table.columnCount()-1, newItem)
def addComboBox4Row(self, row , column):
'add the del button for the row'
newItem = QtGui.QComboBox()
newItem.addItems(['1' , '2' , '3' , '4'])
self.table.setCellWidget(row, column, newItem)
def addBlankItem4Cell(self, row , column):
'add the del button for the row'
newItem = QtGui.QTableWidgetItem()
self.table.setItem(row, column, newItem)
newItem.setBackground(self.__errorColorBrush)
def deleteRow(self , row):
if self.table.rowCount()==0:
FreeCAD.Console.PrintError('deleting row that doesnot exist\n')
return
print '****** DataTable deleting row : ' , self.table.currentRow() , ' ***********'
dataList = []
self.saveData(dataList)
self.table.setRowCount(self.table.rowCount()-1)
del dataList[row]
self.refreshData(dataList)
def saveData(self , dataList):
num = self.table.columnCount()
if self.__lastColumnNoEdit:
num = num-1
for i in range( self.table.rowCount()):
array = range(num)
start = 0
if self.__firstColumnDropDown:
start = 1
array[0] = str(self.table.cellWidget(i,0).currentText())
for j in range(start , num):
array[j] = self.table.item(i,j).text()
# print 'new tuple : ' , array
dataList.append(array)
def handleClick(self , row , column):
if self.__lastColumnNoEdit == True and column == self.table.columnCount()-1 :
self.deleteRow(row)
def checkCell ( self, row , column):
# print 'checking cell : (%d , %d)'%(row , column)
if self.__firstColumnDropDown == True and column==0 :
return
if self.__lastColumnNoEdit == True and column == self.table.columnCount()-1 :
return
try:
num = float(self.table.item(row , column).text())
except:
self.__dataValid = False
self.table.item(row , column).setBackground(self.__errorColorBrush)
self.dataInvalidSignal.emit(0) # data in table is invalid
else :
self.table.item(row , column).setBackground(self.__normalColorBrush)
valid = self.checkTable()
self.dataInvalidSignal.emit(valid) # data in table is invalid
def writeData2Table(self , data):
for i in range(len(data)):
print data[i]
start = self.getColumnStartIndex()
end = self.getColumnEndIndex()
if (len(data)!=self.table.rowCount()) or (len(data[0])!=end - start) : # 行数 或者 列数不相等
# print 'data table column count and row count unvalid ( %d , %d ) <-->(%d , %d)'\
# %( len(data) , len(data[0]) , self.table.rowCount() , end-start )
raise
for i in range(self.table.rowCount()):
for j in range(start , end):
self.table.item(i,j).setText(str(data[i][j]))
def checkTable( self ):
# print '******** begining check table *********'
valid = True
for i in range(self.table.rowCount()):
start = 0
if self.__firstColumnDropDown :
start = 1
end = self.table.columnCount()
if self.__lastColumnNoEdit :
end = end-1