forked from oddtopus/dodo
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpCmd.py
More file actions
3121 lines (2772 loc) · 120 KB
/
pCmd.py
File metadata and controls
3121 lines (2772 loc) · 120 KB
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
# SPDX-License-Identifier: LGPL-3.0-or-later
__title__ = "pypeTools functions"
import FreeCAD
import FreeCADGui
import Part
import fCmd
import pFeatures
from DraftVecUtils import rounded
from quetzal_config import get_icon_path
from math import degrees
objToPaint = ["Pipe", "Elbow", "Reduct", "Flange", "Cap", "Tee"]
__author__ = "oddtopus"
__url__ = "github.com/oddtopus/dodo"
__license__ = "LGPL 3"
X = FreeCAD.Vector(1, 0, 0)
Y = FreeCAD.Vector(0, 1, 0)
Z = FreeCAD.Vector(0, 0, 1)
translate = FreeCAD.Qt.translate
QT_TRANSLATE_NOOP = FreeCAD.Qt.QT_TRANSLATE_NOOP
############### AUX FUNCTIONS ######################
def readTable(fileName="Pipe_SCH-STD.csv"):
"""
readTable(fileName)
Returns the list of dictionaries read from file in ./tablez
fileName: the file name without path; default="Pipe_SCH-STD.csv"
"""
from os.path import join, dirname, abspath
import csv
f = open(join(dirname(abspath(__file__)), "tablez", fileName), "r")
reader = csv.DictReader(f, delimiter=";")
table = []
for row in reader:
table.append(row)
f.close()
return table
def shapeReferenceAxis(obj=None, axObj=None):
# function to get the reference axis of the shape for rotateTheTubeAx()
# used in rotateTheTubeEdge() and pipeForms.rotateForm().getAxis()
"""
shapeReferenceAxis(obj, axObj)
Returns the direction of an axis axObj
according the original Shape orientation of the object obj
If arguments are None axObj is the normal to one circular edge selected
and obj is the object selected.
"""
if obj == None and axObj == None:
selex = FreeCADGui.Selection.getSelectionEx()
if len(selex) == 1 and len(selex[0].SubObjects) > 0:
sub = selex[0].SubObjects[0]
if sub.ShapeType == "Edge" and sub.curvatureAt(0) > 0:
axObj = sub.tangentAt(0).cross(sub.normalAt(0))
obj = selex[0].Object
X = obj.Placement.Rotation.multVec(FreeCAD.Vector(1, 0, 0)).dot(axObj)
Y = obj.Placement.Rotation.multVec(FreeCAD.Vector(0, 1, 0)).dot(axObj)
Z = obj.Placement.Rotation.multVec(FreeCAD.Vector(0, 0, 1)).dot(axObj)
axShapeRef = FreeCAD.Vector(X, Y, Z)
return axShapeRef
def isPipe(obj):
"True if obj is a tube"
return hasattr(obj, "PType") and obj.PType == "Pipe"
def isElbow(obj):
"True if obj is an elbow"
return hasattr(obj, "PType") and obj.PType == "Elbow"
def isTee(obj):
"True if obj is a Tee"
return hasattr(obj, "PType") and obj.PType == "Tee"
def moveToPyLi(obj, plName):
"""
Move obj to the group of pypeLine plName
"""
pl = FreeCAD.ActiveDocument.getObjectsByLabel(plName)[0]
group = FreeCAD.ActiveDocument.getObjectsByLabel(str(pl.Group))[0]
group.addObject(obj)
if hasattr(obj, "PType"):
if obj.PType in objToPaint:
obj.ViewObject.ShapeColor = pl.ViewObject.ShapeColor
elif obj.PType == "PypeBranch":
for e in [FreeCAD.ActiveDocument.getObject(name) for name in obj.Tubes + obj.Curves]:
e.ViewObject.ShapeColor = pl.ViewObject.ShapeColor
def portsPos(o):
"""
portsPos(o)
Returns the position of Ports of the pype-object o
"""
if hasattr(o, "Ports") and hasattr(o, "Placement"):
return [rounded(o.Placement.multVec(p)) for p in o.Ports]
def portsDir(o):
"""
portsDir(o)
Returns the orientation of Ports of the pype-object o
"""
dirs = list()
two_ways = ["Pipe", "Reduct", "Flange"]
if hasattr(o, "PType"):
# Use explicit PortDirections if available
if hasattr(o, "PortDirections") and o.PortDirections:
# Transform port directions from local to world coordinates
dirs = [
rounded(o.Placement.Rotation.multVec(d).normalize())
for d in o.PortDirections
]
#fallback for objects without explicit ports
elif o.PType in two_ways:
dirs = [
o.Placement.Rotation.multVec(p)
for p in [FreeCAD.Vector(0, 0, -1), FreeCAD.Vector(0, 0, 1)]
]
elif hasattr(o, "Ports") and hasattr(o, "Placement"):
dirs = list()
for p in o.Ports:
if p.Length:
dirs.append(rounded(o.Placement.Rotation.multVec(p).normalize()))
else:
dirs.append(
rounded(o.Placement.Rotation.multVec(FreeCAD.Vector(0, 0, -1)).normalize())
)
"""
if o.PType in two_ways:
dirs = [
o.Placement.Rotation.multVec(p)
for p in [FreeCAD.Vector(0, 0, -1), FreeCAD.Vector(0, 0, 1)]
]
elif hasattr(o, "Ports") and hasattr(o, "Placement"):
dirs = list()
for p in o.Ports:
if p.Length:
dirs.append(rounded(o.Placement.Rotation.multVec(p).normalize()))
else:
dirs.append(
rounded(o.Placement.Rotation.multVec(FreeCAD.Vector(0, 0, -1)).normalize())
)
"""
return dirs
################## COMMANDS ########################
def getSelectedPortDimensions():
"""
Determine the OD and thickness of the selected port.
Returns (OD, thk, PRating, PSize) or (None, None, None, None) if cannot determine.
For objects with multiple port sizes (Tee, Reduct), determines which port
is closest to the selected edge/vertex to get the correct dimensions.
This is a helper function for form auto-selection features.
"""
selex = FreeCADGui.Selection.getSelectionEx()
if not selex:
return None, None, None, None
for sx in selex:
obj = sx.Object
if not hasattr(obj, "PType"):
continue
# Get object properties
ptype = obj.PType
# For objects with uniform port sizes (Pipe, Elbow, Flange, Cap, Valve)
if ptype in ["Pipe", "Elbow", "Flange", "Cap", "Valve"]:
if hasattr(obj, "OD") and hasattr(obj, "thk") and hasattr(obj, "PRating") and hasattr(obj, "PSize"):
return float(obj.OD), float(obj.thk), obj.PRating, obj.PSize
# For Tee: has run and branch with potentially different sizes
elif ptype == "Tee":
if not (hasattr(obj, "Ports") and len(obj.Ports) >= 3):
continue
# Determine which port is selected based on proximity
selectedPort = None
if sx.SubObjects:
subObj = sx.SubObjects[0]
if hasattr(subObj, "CenterOfMass"):
selectionPoint = subObj.CenterOfMass
elif hasattr(subObj, "Point"):
selectionPoint = subObj.Point
else:
selectionPoint = None
if selectionPoint:
# Find closest port
minDist = float('inf')
for i, port in enumerate(obj.Ports):
portWorldPos = obj.Placement.multVec(port)
dist = (portWorldPos - selectionPoint).Length
if dist < minDist:
minDist = dist
selectedPort = i
# Port 2 is the branch, ports 0 and 1 are the run
if selectedPort == 2:
# Branch port
if hasattr(obj, "OD2") and hasattr(obj, "thk2"):
return float(obj.OD2), float(obj.thk2), obj.PRating if hasattr(obj, "PRating") else None, obj.PSize if hasattr(obj, "PSize") else None
else:
# Run port (0 or 1, or default if couldn't determine)
if hasattr(obj, "OD") and hasattr(obj, "thk"):
return float(obj.OD), float(obj.thk), obj.PRating if hasattr(obj, "PRating") else None, obj.PSize if hasattr(obj, "PSize") else None
# For Reduct: port 0 is larger end, port 1 is smaller end
elif ptype == "Reduct":
if not (hasattr(obj, "Ports") and len(obj.Ports) >= 2):
continue
# Determine which port is selected
selectedPort = None
if sx.SubObjects:
subObj = sx.SubObjects[0]
if hasattr(subObj, "CenterOfMass"):
selectionPoint = subObj.CenterOfMass
elif hasattr(subObj, "Point"):
selectionPoint = subObj.Point
else:
selectionPoint = None
if selectionPoint:
# Find closest port
minDist = float('inf')
for i, port in enumerate(obj.Ports):
portWorldPos = obj.Placement.multVec(port)
dist = (portWorldPos - selectionPoint).Length
if dist < minDist:
minDist = dist
selectedPort = i
# Port 0 is larger end (OD), port 1 is smaller end (OD2)
if selectedPort == 1:
# Smaller end
if hasattr(obj, "OD2") and hasattr(obj, "thk2"):
return float(obj.OD2), float(obj.thk2), obj.PRating if hasattr(obj, "PRating") else None, obj.PSize if hasattr(obj, "PSize") else None
else:
# Larger end (0 or default)
if hasattr(obj, "OD") and hasattr(obj, "thk"):
return float(obj.OD), float(obj.thk), obj.PRating if hasattr(obj, "PRating") else None, obj.PSize if hasattr(obj, "PSize") else None
return None, None, None, None
def autoSelectInPipeForm(form):
"""
Auto-select the size and rating in form lists based on selected object's port.
Args:
form: The form object (must have ratingList, sizeList, pipeDictList, PRating, fillSizes())
This is a helper function for form auto-selection features.
Works with any form that has the standard protoPypeForm structure.
"""
from FreeCAD import Units
pq = Units.parseQuantity
OD, thk, PRating, PSize = getSelectedPortDimensions()
if OD is None:
return # No valid selection, keep defaults
# Try to select matching rating first
if PRating and hasattr(form, 'ratingList'):
for i in range(form.ratingList.count()):
if form.ratingList.item(i).text() == PRating:
form.ratingList.setCurrentRow(i)
form.PRating = PRating
if hasattr(form, 'fillSizes'):
form.fillSizes()
break
# Try to find matching size by OD and thk
if not hasattr(form, 'pipeDictList') or not hasattr(form, 'sizeList'):
return
# If we have PSize from selection, try exact PSize match first
if PSize:
for i, pipeDict in enumerate(form.pipeDictList):
# For Tees: prefer equal run/branch sizes (e.g., "DN50xDN50" over "DN50xDN40")
# Check if PSize contains "x" (indicating Tee or Reduct with two sizes)
dictPSize = pipeDict.get("PSize", "")
if "x" in dictPSize:
# Split to get run and branch sizes
parts = dictPSize.split("x")
if len(parts) == 2:
runSize = parts[0]
branchSize = parts[1]
# Prefer straight tees: if detected PSize matches run, i.e. prefer DN50xDN50 over DN50xDN40. This won't find a match here for reducers, but it should find a match later by checking OD's
if runSize == branchSize and runSize == PSize:
form.sizeList.setCurrentRow(i)
if hasattr(form, 'fillOD2'):
form.fillOD2()
return # Found equal run/branch
# Also check for exact PSize match (including non-Tee items)
if dictPSize == PSize:
form.sizeList.setCurrentRow(i)
if hasattr(form, 'fillOD2'):
form.fillOD2()
return # Found exact PSize match
# Fallback: If no PSize match, try OD/thk matching with preference for equal OD/OD2
if OD is not None:
bestMatch = None
bestMatchScore = float('inf')
for i, pipeDict in enumerate(form.pipeDictList):
try:
dictOD = float(pq(pipeDict["OD"]))
dictThk = float(pq(pipeDict["thk"]))
# Check if this is a Tee/Reducer with OD2
hasOD2 = "OD2" in pipeDict
if hasOD2:
dictOD2 = float(pq(pipeDict["OD2"]))
# Prefer equal-size Tees: if OD matches and OD==OD2
if abs(dictOD - OD) < 0.1 and abs(dictOD - dictOD2) < 0.1:
# Straight tee
score = 0.0 # Perfect match score
else:
# Calculate normal match score
odDiff = abs(dictOD - OD)
thkDiff = abs(dictThk - thk)
score = odDiff * 10 + thkDiff
else:
# other fittings - calculate match score
odDiff = abs(dictOD - OD)
thkDiff = abs(dictThk - thk)
score = odDiff * 10 + thkDiff
if score < bestMatchScore:
bestMatchScore = score
bestMatch = i
except:
continue
# Select the best match if found
if bestMatch is not None and bestMatchScore < 5.0: # Reasonable tolerance
form.sizeList.setCurrentRow(bestMatch)
# Call form-specific update if it exists
if hasattr(form, 'fillOD2'):
form.fillOD2()
def getSelectionPortAttachment(selex=None):
"""
Inspects the current selection and, if the selected object has Ports,
returns the world position, outward direction, object, and port index of
the port closest to the selection point.
The selection point is determined as follows:
- Vertex selected -> vertex point
- Curved edge -> centerOfCurvatureAt(0)
- Straight edge -> CenterOfMass (midpoint)
Returns (pos, Z, obj, portIndex) if a ported object is found, or
(None, None, None, None) if no ported object is in the selection.
pos : FreeCAD.Vector - world-space port position
Z : FreeCAD.Vector - outward port direction in world space (from PortDirections)
obj : FreeCAD object - the stationary ported object
portIndex : int - index of the closest port
"""
if selex is None:
selex = FreeCADGui.Selection.getSelectionEx()
for sx in selex:
obj = sx.Object
if not (hasattr(obj, "Ports") and len(obj.Ports) > 0):
continue # object has no ports - skip
# Determine the raw selection point from the sub-shape
selPt = None
if sx.SubObjects:
sub = sx.SubObjects[0]
if sub.ShapeType == "Vertex":
selPt = sub.Point
elif sub.ShapeType == "Edge":
if sub.curvatureAt(0) != 0:
selPt = sub.centerOfCurvatureAt(0)
else:
selPt = sub.CenterOfMass # midpoint of straight edge
else:
selPt = sub.CenterOfMass
if selPt is None:
# No sub-object - use the object base as fallback
selPt = obj.Placement.Base
# Find the closest port (world coordinates)
closestPort = 0
minDist = float("inf")
for i, portVec in enumerate(obj.Ports):
worldPort = obj.Placement.multVec(portVec)
dist = (worldPort - selPt).Length
if dist < minDist:
minDist = dist
closestPort = i
# Port world position
pos = obj.Placement.multVec(obj.Ports[closestPort])
# Port outward direction in world space
if hasattr(obj, "PortDirections") and obj.PortDirections:
Z = obj.Placement.Rotation.multVec(obj.PortDirections[closestPort]).normalize()
else:
# Fallback: infer from port vector if PortDirections not set
pVec = obj.Ports[closestPort]
if pVec.Length > 0:
Z = obj.Placement.Rotation.multVec(pVec).normalize()
else:
Z = obj.Placement.Rotation.multVec(FreeCAD.Vector(0, 0, 1))
return pos, Z, obj, closestPort
return None, None, None, None
class ViewProvider:
def __init__(self, obj, icon_fn):
obj.Proxy = self
self._check_attr()
self.icon_fn = get_icon_path(icon_fn or "quetzal")
def _check_attr(self):
"""Check for missing attributes."""
if not hasattr(self, "icon_fn"):
setattr(self, "icon_fn", get_icon_path("quetzal"))
def getIcon(self):
"""Returns the path to the SVG icon."""
self._check_attr()
return self.icon_fn
def simpleSurfBend(path=None, profile=None):
"select the centerline and the O.D. and let it sweep"
curva = FreeCAD.activeDocument().addObject("Part::Feature", "Simple curve")
if path == None or profile == None:
curva.Shape = Part.makeSweepSurface(*fCmd.edges()[:2])
elif path.ShapeType == profile.ShapeType == "Edge":
curva.Shape = Part.makeSweepSurface(path, profile)
def getAttachmentPoints():
try:
#first, if a an object with ports is selected and edges, faces, or vertices are selected, insert the component at the closest port to the
#first selected object's first selected edge, face, or vertex. If none of those are present, the entire object is selected - insert
#the component at the highest number port. If nothing is selected, it will go to the execption and return None's, which will insert at the origin
selex = FreeCADGui.Selection.getSelectionEx()[0]
usablePorts = False
srcObj = None
srcPort = None
pos = None
Z = None
if hasattr(selex.Object, "Ports"):
if hasattr(selex.Object, "PType"):
if selex.Object.PType != "Any":
usablePorts = True
if usablePorts:
face = fCmd.faces([selex])
edge = fCmd.edges([selex])
v = fCmd.points([selex])
if len(face) + len(edge) + len(v) > 0:
pos, Z, srcObj, srcPort = getSelectionPortAttachment([selex])
else:
pos, Z, srcObj, srcPort = getSelectionPortAttachment([selex])
#overwrite port with highest number port
srcPort = len(selex.Object.Ports) - 1
else:
#insert at center of curvature for curved edges or faces, insert at vertex point for vertices
face = fCmd.faces([selex])
edge = fCmd.edges([selex])
v = fCmd.points([selex])
if face: # Face selected...
x = (face[0].ParameterRange[0] + face[0].ParameterRange[1]) / 2
y = (face[0].ParameterRange[2] + face[0].ParameterRange[3]) / 2
pos = face[0].valueAt(x, y)
Z = face[0].normalAt(x, y)
elif edge:
if edge[0].curvatureAt(0) == 0: # straight edge, no ports
pos =edge[0].valueAt(0)
Z =edge[0].tangentAt(0)
else: # curved edge, no ports
pos = edge[0].centerOfCurvatureAt(0)
Z = edge[0].tangentAt(0).cross(edge[0].normalAt(0))
#Note that this Z direction is a guess, it might need to be opposite. User can use Reverse button to reverse. Could try to add code to check direction against center of mass
elif v:
pos = v[0].Point
Z = None #use default orientation with vertex, since we don't know what direction is desired
return pos, Z, srcObj, srcPort
except:
#nothing selected, insert at origin
return None, None, None, None
def makePipe(rating,propList=[], pos=None, Z=None):
"""add a Pipe object
makePipe(rating,propList,pos,Z);
propList is one optional list with 4 elements:
DN (string): nominal diameter
OD (float): outside diameter
thk (float): shell thickness
H (float): length of pipe
Default is "DN50 (SCH-STD)"
rating pipe pressure capability
pos (vector): position of insertion; default = 0,0,0
Z (vector): orientation: default = 0,0,1
Remember: property PRating must be defined afterwards
"""
if pos == None:
pos = FreeCAD.Vector(0, 0, 0)
if Z == None:
Z = FreeCAD.Vector(0, 0, 1)
a = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Tube")
if len(propList) == 4:
pFeatures.Pipe(a,rating, *propList)
else:
pFeatures.Pipe(a,rating)
ViewProvider(a.ViewObject, "Quetzal_InsertPipe")
a.Placement.Base = pos
rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), Z)
a.Placement.Rotation = rot.multiply(a.Placement.Rotation)
a.Label = translate("Objects", "Tube")
return a
def doPipes(rating,propList=["DN50", 60.3, 3, 1000], pypeline=None):
"""
propList = [
DN (string): nominal diameter
OD (float): outside diameter
thk (float): shell thickness
H (float): length of pipe ]
pypeline = string
"""
FreeCAD.activeDocument().openTransaction(translate("Transaction", "Insert pipe"))
plist = list()
try:
#first, if a an object with ports is selected and edges, faces, or vertices are selected, insert the component at the closest port to the
#first selected object's first selected edge, face, or vertex. If none of those are present, the entire object is selected - insert
#the component at the highest number port.
selex = FreeCADGui.Selection.getSelectionEx()[0]
usablePorts = False
if hasattr(selex.Object, "Ports"):
if hasattr(selex.Object, "PType"):
if selex.Object.PType != "Any":
usablePorts = True
pos, Z, srcObj, srcPort = getAttachmentPoints()
if usablePorts:
pipe = makePipe(rating, propList, pos, Z)
plist.append(pipe)
FreeCAD.activeDocument().commitTransaction()
FreeCAD.activeDocument().recompute()
alignTwoPorts(pipe, 0, srcObj, srcPort)
else:
plist.append(makePipe(rating, propList, pos, Z))
except:
#nothing selected, insert at origin
plist.append(makePipe(rating,propList))
if pypeline:
for p in plist:
moveToPyLi(p, pypeline)
FreeCAD.activeDocument().commitTransaction()
FreeCAD.activeDocument().recompute()
return plist
def makeTerminalAdapter(rating,propList=[],pos=None,Z=None):
"""Add TerminalAdapter object
"""
if pos == None:
pos = FreeCAD.Vector(0, 0, 0)
if Z == None:
Z = FreeCAD.Vector(0, 0, 1)
a = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "TerminalAdapter")
pFeatures.TerminalAdapter(a,rating, *propList)
ViewProvider(a.ViewObject, "Quetzal_TerminalAdapter")
a.Placement.Base = pos
rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), -Z)
a.Placement.Rotation = rot.multiply(a.Placement.Rotation)
def makeElbow(propList=[], pos=None, Z=None, rating="SCH-STD"):
"""Adds an Elbow object
makeElbow(propList,pos,Z);
propList is one optional list with 5 elements:
DN (string): nominal diameter
OD (float): outside diameter
thk (float): shell thickness
BA (float): bend angle
BR (float): bend radius
Default is "DN50"
pos (vector): position of insertion; default = 0,0,0
Z (vector): orientation: default = 0,0,1
Remember: property PRating must be defined afterwards
"""
if pos == None:
pos = FreeCAD.Vector(0, 0, 0)
if Z == None:
Z = FreeCAD.Vector(0, 0, 1)
a = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Elbow")
if len(propList) == 5:
pFeatures.Elbow(a, rating, *propList)
else:
pFeatures.Elbow(a, rating)
ViewProvider(a.ViewObject, "Quetzal_InsertElbow")
# Rotate so port[0]'s local direction faces Z.
# SocketEll port[0] direction is (1,0,0) — local +X, not +Z — so the
# reference axis must be port[0]'s actual local direction, not (0,0,1).
port0_local_dir = a.PortDirections[0] if a.PortDirections else FreeCAD.Vector(0, 0, 1)
rot = FreeCAD.Rotation(port0_local_dir, Z)
a.Placement.Rotation = rot.multiply(a.Placement.Rotation)
# After rotation the object origin is still at (0,0,0). Translate so that
# port[0] — now in its rotated world position — lands exactly at pos.
port0_world = a.Placement.multVec(a.Ports[0])
a.Placement.Base = pos - port0_world
a.Label = translate("Objects", "Elbow")
return a
def makeElbowBetweenThings(thing1=None, thing2=None, propList=None):
"""
makeElbowBetweenThings(thing1, thing2, propList=None):
Place one elbow at the intersection of thing1 and thing2
Things can be any combination of intersecting beams, pipes or edges.
If nothing is passed as argument, the function attempts to take the
first two edges selected in the view.
propList is one optional list with 5 elements:
DN (string): nominal diameter
OD (float): outside diameter
thk (float): shell thickness
BA (float): bend angle - that will be recalculated! -
BR (float): bend radius
Default is "DN50 (SCH-STD)"
Remember: property PRating must be defined afterwards
"""
if not (thing1 and thing2):
thing1, thing2 = fCmd.edges()[:2]
P = fCmd.intersectionCLines(thing1, thing2)
directions = list()
try:
for thing in [thing1, thing2]:
if fCmd.beams([thing]):
directions.append(
rounded(
(fCmd.beamAx(thing).multiply(thing.Height / 2) + thing.Placement.Base) - P
)
)
elif hasattr(thing, "ShapeType") and thing.ShapeType == "Edge":
directions.append(rounded(thing.CenterOfMass - P))
except:
return None
ang = 180 - degrees(directions[0].getAngle(directions[1]))
if ang == 0 or ang == 180:
return None
if not propList:
propList = ["DN50", 60.3, 3.91, ang, 45.24]
else:
propList[3] = ang
elb = makeElbow(propList, P, directions[0].negative().cross(directions[1].negative()))
# mate the elbow ends with the pipes or edges
b = fCmd.bisect(directions[0], directions[1])
elbBisect = rounded(
fCmd.beamAx(elb, FreeCAD.Vector(1, 1, 0))
) # if not rounded, fail in plane xz
rot = FreeCAD.Rotation(elbBisect, b)
elb.Placement.Rotation = rot.multiply(elb.Placement.Rotation)
# trim the adjacent tubes
# FreeCAD.activeDocument().recompute() # may delete this row?
portA = elb.Placement.multVec(elb.Ports[0])
portB = elb.Placement.multVec(elb.Ports[1])
for tube in [t for t in [thing1, thing2] if fCmd.beams([t])]:
vectA = tube.Shape.Solids[0].CenterOfMass - portA
vectB = tube.Shape.Solids[0].CenterOfMass - portB
if fCmd.isParallel(vectA, fCmd.beamAx(tube)):
fCmd.extendTheBeam(tube, portA)
else:
fCmd.extendTheBeam(tube, portB)
return elb
def doElbow(rating="SCH-STD", propList=["DN50", 60.3, 3, 90, 45.225], pypeline=None):
"""
propList = [
DN (string): nominal diameter
OD (float): outside diameter
thk (float): shell thickness
BA (float): bend angle
BR (float): bend radius ]
pypeline = string
"""
elist = []
FreeCAD.activeDocument().openTransaction(translate("Transaction", "Insert elbow"))
selex = FreeCADGui.Selection.getSelectionEx()
if len(selex) == 0: # no selection -> insert one elbow at origin
elist.append(makeElbow(propList, rating=rating))
elif len(selex) == 1 and len(selex[0].SubObjects) == 1: # one selection -> ...
#first, if a an object with ports is selected and edges, faces, or vertices are selected, insert the component at the closest port to the
#first selected object's first selected edge, face, or vertex. If none of those are present, the entire object is selected - insert
#the component at the highest number port.
selex = FreeCADGui.Selection.getSelectionEx()[0]
usablePorts = False
if hasattr(selex.Object, "Ports"):
if hasattr(selex.Object, "PType"):
if selex.Object.PType != "Any":
usablePorts = True
pos, Z, srcObj, srcPort = getAttachmentPoints()
if usablePorts:
elb = makeElbow(propList, pos, Z, rating=rating)
elist.append(elb)
FreeCAD.activeDocument().commitTransaction()
FreeCAD.activeDocument().recompute()
alignTwoPorts(elb, 0, srcObj, srcPort)
else:
elist.append(makeElbow(propList, pos, Z, rating=rating))
else: # multiple selection -> insert one elbow at intersection of two edges or beams or pipes ##
things = []
for objEx in selex:
if (
len(fCmd.beams([objEx.Object])) == 1
): # if the object is a beam or pipe, append it to the "things"..
things.append(objEx.Object)
else: # ..else append its edges
for edge in fCmd.edges([objEx]):
things.append(edge)
if len(things) >= 2:
break
try: # create the feature
elb = elist.append(makeElbowBetweenThings(*things[:2], propList=propList))
except:
FreeCAD.Console.PrintError("Creation of elbow is failed\n")
if pypeline:
for e in elist:
moveToPyLi(e, pypeline)
FreeCAD.activeDocument().commitTransaction()
FreeCAD.activeDocument().recompute()
return elist
def makeFlange(propList=[], pos=None, Z=None, doOffset=None, rating="DIN-PN16"):
"""Adds a Flange object
makeFlange(propList,pos,Z);
propList is one optional list with 8 elements:
DN (string): nominal diameter
FlangeType (string): type of Flange
D (float): flange diameter
d (float): bore diameter
df (float): bolts holes distance
f (float): bolts holes diameter
t (float): flange thickness
n (int): nr. of bolts
trf (float): raised-face thickness - OPTIONAL -
drf (float): raised-face diameter - OPTIONAL -
twn (float): welding-neck thickness - OPTIONAL -
dwn (float): welding-neck diameter - OPTIONAL -
ODp (float): outside diameter of pipe for wn flanges - OPTIONAL -
Default is "DN50 (PN16)"
pos (vector): position of insertion; default = 0,0,0
Z (vector): orientation: default = 0,0,1
R Flange fillet radius
T1 Overall flange thickness
Y Socket depth
Remember: property PRating must be defined afterwards
"""
if pos == None:
pos = FreeCAD.Vector(0, 0, 0)
if Z == None:
Z = FreeCAD.Vector(0, 0, 1)
a = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Flange")
if len(propList) >= 8:
pFeatures.Flange(a, rating, *propList)
else:
pFeatures.Flange(a, rating)
ViewProvider(a.ViewObject, "Quetzal_InsertFlange")
a.Placement.Base = pos
rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), Z)
a.Placement.Rotation = rot.multiply(a.Placement.Rotation)
if not doOffset:
if a.FlangeType == "WN":
zpos = -a.T1 + a.trf
elif a.FlangeType == "SW":
zpos = -a.T1 + a.Y + a.trf
elif a.FlangeType == "LJ":
zpos = 0
else:
zpos = 0
a.Placement = a.Placement.multiply(
FreeCAD.Placement(FreeCAD.Vector(0, 0, zpos), FreeCAD.Rotation(1, 0, 0))
)
FreeCAD.ActiveDocument.recompute()
a.Label = translate("Objects", "Flange")
return a
def doFlanges(
rating="DIN-PN16",
propList=["DN50", "SO", 160, 60.3, 132, 14, 15, 4, 0, 0, 0, 0, 0, 0, 0],
pypeline=None,
doOffset=None,
attachFace=None #TODO add radio buttons to flange insertion form for whether to attach flange at face or neck
):
"""
propList = [
DN (string): nominal diameter
FlangeType (string): type of Flange
D (float): flange diameter
d (float): bore diameter
df (float): bolts holes distance
f (float): bolts holes diameter
t (float): flange thickness
n (int): nr. of bolts
trf (float): raised-face thickness - OPTIONAL -
drf (float): raised-face diameter - OPTIONAL -
twn (float): welding-neck thickness - OPTIONAL -
dwn (float): welding-neck diameter - OPTIONAL -
ODp (float): outside diameter of pipe for wn flanges - OPTIONAL -
R Flange fillet radius
T1 Overall flange thickness
Y Socket depth
pypeline = string
"""
flist = []
tubes = [t for t in fCmd.beams() if hasattr(t, "PSize")]
FreeCAD.activeDocument().openTransaction(translate("Transaction", "Insert flange"))
if attachFace:
connecting_port = 0
else:
connecting_port = 1
try:
#first, if a an object with ports is selected and edges, faces, or vertices are selected, insert the component at the closest port to the
#first selected object's first selected edge, face, or vertex. If none of those are present, the entire object is selected - insert
#the component at the highest number port.
selex = FreeCADGui.Selection.getSelectionEx()[0]
usablePorts = False
if hasattr(selex.Object, "Ports"):
if hasattr(selex.Object, "PType"):
if selex.Object.PType != "Any":
usablePorts = True
pos, Z, srcObj, srcPort = getAttachmentPoints()
if usablePorts:
flange = makeFlange(propList, pos, Z, doOffset, rating=rating)
flist.append(flange)
#if we need to remove pipe equivalent length
if doOffset:
#Correct offset for raised face flanges. If flat face flanges are added, presumably a.trf would be zero?
a=flist[-1]
if a.FlangeType == "WN":
zpos = -a.T1
elif a.FlangeType == "SW":
zpos = -a.T1 + a.Y
elif a.FlangeType == "LJ":
zpos = 0
else:
zpos = a.trf
pipe = fCmd.beams()[0]
#respos=a.Placement.multiply(FreeCAD.Placement(FreeCAD.Vector(0,0,-zpos), FreeCAD.Rotation(1, 0, 0)))
respos=a.Placement.multiply(FreeCAD.Placement(FreeCAD.Vector(0,0,zpos), FreeCAD.Rotation(1, 0, 0)))
fCmd.extendTheBeam(pipe,respos.Base)
FreeCAD.activeDocument().commitTransaction()
FreeCAD.activeDocument().recompute()
alignTwoPorts(flange, connecting_port, srcObj, srcPort)
else:
flist.append(makeFlange(propList, pos, Z, doOffset, rating=rating))
except:
#nothing selected, insert at origin
flist.append(makeFlange(propList))
###OLD METHOD
"""
if len(fCmd.edges()) == 0:
vs = [
v
for sx in FreeCADGui.Selection.getSelectionEx()
for so in sx.SubObjects
for v in so.Vertexes
]
if len(vs) == 0:
flist.append(makeFlange(propList))
else:
for v in vs:
flist.append(makeFlange(propList, v.Point))
elif tubes:
selex = FreeCADGui.Selection.getSelectionEx()
for sx in selex:
if isPipe(sx.Object) and fCmd.edges([sx]):
for edge in fCmd.edges([sx]):
if edge.curvatureAt(0) != 0:
flist.append(
makeFlange(
propList,
edge.centerOfCurvatureAt(0),
sx.Object.Shape.Solids[0].CenterOfMass
- edge.centerOfCurvatureAt(0),
doOffset
)
)
if doOffset:
a=flist.pop()
if a.FlangeType == "WN":
zpos = -a.T1 + a.trf
elif a.FlangeType == "SW":
zpos = -a.T1 + a.Y + a.trf
elif a.FlangeType == "LJ":
zpos = 0
else:
zpos = 0
pipe = fCmd.beams()[0]
respos=a.Placement.multiply(FreeCAD.Placement(FreeCAD.Vector(0,0,-zpos), FreeCAD.Rotation(1, 0, 0)))
fCmd.extendTheBeam(pipe,respos.Base)
else:
for edge in fCmd.edges():
if edge.curvatureAt(0) != 0:
flist.append(
makeFlange(
propList,
edge.centerOfCurvatureAt(0),
edge.tangentAt(0).cross(edge.normalAt(0)),
doOffset
)
)
"""
if pypeline:
for f in flist:
moveToPyLi(f, pypeline)
FreeCAD.activeDocument().commitTransaction()
FreeCAD.activeDocument().recompute()
return flist
def makeReduct(propList=[], pos=None, Z=None, conc=True, smallerEnd=False, rating="SCH-STD"):
"""Adds a Reduct object
makeReduct(propList=[], pos=None, Z=None, conc=True)
propList is one optional list with 6 elements:
PSize (string): nominal diameter
OD (float): major diameter
OD2 (float): minor diameter
thk (float): major thickness
thk2 (float): minor thickness
H (float): length of reduction
pos (vector): position of insertion; default = 0,0,0
Z (vector): orientation: default = 0,0,1
conc (bool): True for concentric or False for eccentric reduction
Remember: property PRating must be defined afterwards
"""
if pos == None:
pos = FreeCAD.Vector(0, 0, 0)
if Z == None:
Z = FreeCAD.Vector(0, 0, 1)
a = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Reduction")
propList.append(conc)
pFeatures.Reduct(a, rating, *propList)
ViewProvider(a.ViewObject, "Quetzal_InsertReduct")
a.Placement.Base = pos
rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), Z)
a.Placement.Rotation = rot.multiply(a.Placement.Rotation)
if smallerEnd:
initPos = a.Placement.Base