-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadFor3DPrinter.py
More file actions
1061 lines (945 loc) · 48 KB
/
Copy pathThreadFor3DPrinter.py
File metadata and controls
1061 lines (945 loc) · 48 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
import adsk.core, adsk.fusion
import json, math, traceback
_app = None
_ui = None
_handlers = []
CMD_ID = 'threadTool_v1'
PRIVACY_URL = 'https://github.com/HookyMaster/ThreadFor3DPrinter/blob/master/docs/PRIVACY.md'
MIN_FLANK_ANGLE_DEG = 5.0
MAX_FLANK_ANGLE_DEG = 45.0
PROFILE_TOLERANCE_CM = 1e-7
MIN_SHORT_EDGE_CM = 0.02 # 0.2 mm; avoids a degenerate/self-intersecting profile
# Recommended radial clearance (per side, mm) for 3D-printed mating threads.
# FDM prints typically need 0.2-0.4 mm per side to assemble without force;
# 0.3 mm is a common middle ground. Shown as a suggestion in the result dialog.
RECOMMENDED_CLEARANCE_MM = 0.3
# Maximum allowed deviation between the fitted helix spline and the true
# cylinder surface, expressed as a fraction of the tooth height H. The sweep
# guides the profile along the cylinder face; if the path strays further than
# roughly H from the surface the profile can no longer follow the guide and
# the kernel rejects the sweep (ASM_SWEEP_ILLEGAL_SURFACE). 0.5 gives a
# comfortable safety margin while keeping point counts low.
HELIX_DEVIATION_TOLERANCE_RATIO = 0.5
MIN_SAMPLES_PER_TURN = 16
MAX_SAMPLES_PER_TURN = 360
# Hard cap on the total number of spline points for one helix. When the
# adaptive per-turn sampling would exceed this for a long thread, the turn
# count is reduced instead of the sampling density, so the path always stays
# close to the cylinder surface.
MAX_HELIX_POINTS = 20000
def _profile_dimensions(L, H, angle_degrees):
"""Return axial flank inset, short edge, and max H for the minimum S."""
tangent = math.tan(math.radians(angle_degrees))
flank_run = H / tangent
short_edge = L - 2.0 * flank_run
max_height = max(0.0, 0.5 * (L - MIN_SHORT_EDGE_CM) * tangent)
return flank_run, short_edge, max_height
def _samples_per_turn_for_radius(radius_cm, requested, tooth_height_mm,
deviation_ratio=None):
"""Return the effective samples-per-turn for a cylinder radius.
A circle of radius R sampled at n points per turn has a maximum chord-to-arc
(sagitta) deviation of R * (1 - cos(pi / n)). The sweep guides the profile
along the cylinder face, so this deviation must stay within
deviation_ratio * tooth_height_mm or the kernel rejects the sweep. We raise
the sample count until the sagitta is within tolerance. The caller's
requested value is honoured as a lower bound.
deviation_ratio defaults to HELIX_DEVIATION_TOLERANCE_RATIO when None.
"""
radius_mm = radius_cm * 10.0
base = max(MIN_SAMPLES_PER_TURN, int(requested))
if radius_mm <= 0 or tooth_height_mm <= 0:
return base
if deviation_ratio is None:
deviation_ratio = HELIX_DEVIATION_TOLERANCE_RATIO
tol_mm = deviation_ratio * tooth_height_mm
# sagitta <= tol => n >= pi / acos(1 - tol / R)
ratio = tol_mm / radius_mm
if ratio >= 1.0:
return base # tiny radius; tolerance already met
required = math.pi / math.acos(max(-1.0, min(1.0, 1.0 - ratio)))
required = int(math.ceil(required))
return int(max(base, min(required, MAX_SAMPLES_PER_TURN)))
def _plan_helix_sampling(radius_cm, requested_ppt, turns, tooth_height_mm,
deviation_ratio=None):
"""Plan effective sampling for a helix of the given radius and turn count.
Returns a tuple (eff_ppt, turns, n_points, capped):
- eff_ppt: effective samples per turn (adaptive, never reduced for budget)
- turns: the number of turns that fit within the point budget
- n_points: total spline point count (excluding the closing duplicate)
- capped: True if turns were reduced because of the point budget
The sampling density is never sacrificed to fit the budget. If the adaptive
per-turn density would push the total beyond MAX_HELIX_POINTS, the turn
count is reduced so every retained turn keeps full precision.
deviation_ratio defaults to HELIX_DEVIATION_TOLERANCE_RATIO when None.
"""
eff_ppt = _samples_per_turn_for_radius(
radius_cm, requested_ppt, tooth_height_mm, deviation_ratio)
capped = False
if turns > 0 and eff_ppt > 0 and turns * eff_ppt > MAX_HELIX_POINTS:
turns = max(1, int(MAX_HELIX_POINTS // eff_ppt))
capped = True
n_points = max(4, int(turns * eff_ppt)) if turns > 0 else 0
return eff_ppt, turns, n_points, capped
# ══════════════════════════════════════════════════════
# 工具函数
# Utility functions
# ══════════════════════════════════════════════════════
def _get_cyl_info(face):
"""提取圆柱面参数"""
# Extract cylinder face parameters
geom = face.geometry
axis = geom.axis
origin = geom.origin
radius = geom.radius
bb = face.boundingBox
corners = [
bb.minPoint, bb.maxPoint,
adsk.core.Point3D.create(bb.minPoint.x, bb.minPoint.y, bb.maxPoint.z),
adsk.core.Point3D.create(bb.minPoint.x, bb.maxPoint.y, bb.minPoint.z),
adsk.core.Point3D.create(bb.maxPoint.x, bb.minPoint.y, bb.minPoint.z),
]
ax = adsk.core.Vector3D.create(axis.x, axis.y, axis.z)
ax.normalize()
# 统一 axis 方向:用 bb.minPoint/bb.maxPoint 判断,确保 axis 从物理底面指向顶面
v_min = adsk.core.Vector3D.create(
bb.minPoint.x - origin.x, bb.minPoint.y - origin.y, bb.minPoint.z - origin.z)
v_max = adsk.core.Vector3D.create(
bb.maxPoint.x - origin.x, bb.maxPoint.y - origin.y, bb.maxPoint.z - origin.z)
if v_min.dotProduct(ax) > v_max.dotProduct(ax):
ax.scaleBy(-1) # 翻转,使 axis 从底面指向顶面
projs = []
for c in corners:
v = adsk.core.Vector3D.create(c.x - origin.x, c.y - origin.y, c.z - origin.z)
projs.append(v.x * ax.x + v.y * ax.y + v.z * ax.z)
return radius, max(projs) - min(projs), min(projs), ax, origin
def _is_external_face(face):
"""判断圆柱面是外表面还是内表面(通过法线方向)"""
# Determine whether the cylinder face is external or internal (via normal direction)
g = face.geometry
eva = face.evaluator
(_, pt) = eva.getPointAtParameter(adsk.core.Point2D.create(0.5, 0.5))
(_, normal) = eva.getNormalAtPoint(pt)
rad = adsk.core.Vector3D.create(pt.x - g.origin.x, pt.y - g.origin.y, pt.z - g.origin.z)
rad.normalize()
return normal.dotProduct(rad) > 0
def _radial_dir(ax):
"""垂直于轴线的径向方向"""
# Radial direction perpendicular to the axis
ref = adsk.core.Vector3D.create(0, 1, 0)
if abs(ax.dotProduct(ref)) > 0.9:
ref = adsk.core.Vector3D.create(1, 0, 0)
u = ref.crossProduct(ax)
u.normalize()
return u
def _build_helix(face, L, flank_run, pts_per_turn, offset_cm=0,
tooth_height_mm=1.0, deviation_ratio=None):
"""生成螺旋线点列。offset_cm: 螺旋线起点距圆柱底端的偏移"""
# Generate helix point sequence. offset_cm: offset from cylinder bottom to helix start
radius, height, h_min, ax, origin = _get_cyl_info(face)
P = 2.0 * (L - flank_run)
usable = height - offset_cm
N = max(1, int(usable / P + 1e-9) - 1) # 留一圈空间;+1e-9防浮点截断
# Reserve one full turn of space
# Adapt sample density to the radius; if the point budget is exceeded the
# turn count is reduced (not the sampling density) so the path always hugs
# the cylinder surface.
eff_ppt, N, n_pts, capped = _plan_helix_sampling(
radius, pts_per_turn, N, tooth_height_mm, deviation_ratio)
hh = N * P
h_start = h_min + offset_cm # 偏移后的起始高度
# Adjusted starting height after offset
u = _radial_dir(ax)
v = ax.crossProduct(u)
v.normalize()
pts = adsk.core.ObjectCollection.create()
for i in range(n_pts + 1):
t = i / n_pts
angle = t * N * 2 * math.pi
hz = h_start + t * hh
pts.add(adsk.core.Point3D.create(
origin.x + hz * ax.x + radius * (math.cos(angle) * u.x + math.sin(angle) * v.x),
origin.y + hz * ax.y + radius * (math.cos(angle) * u.y + math.sin(angle) * v.y),
origin.z + hz * ax.z + radius * (math.cos(angle) * u.z + math.sin(angle) * v.z)))
return pts, N, hh, P, radius
def _create_trapezoid(root, perp_plane, face, L, H, angle_degrees,
start_pt, is_external):
"""在路径垂面上画梯形截面。
is_external=True → 向外长肉(外螺纹)
is_external=False → 向内长肉(内螺纹)
"""
# Draw trapezoid cross-section on the plane perpendicular to the path
_, _, h_min, ax, origin = _get_cyl_info(face)
# 径向方向:start_pt 在轴上的投影点 → 消除偏移影响
# Radial direction: project start_pt onto the axis → eliminate offset effect
proj_len = ((start_pt.x - origin.x) * ax.x +
(start_pt.y - origin.y) * ax.y +
(start_pt.z - origin.z) * ax.z)
axis_pt = adsk.core.Point3D.create(
origin.x + proj_len * ax.x,
origin.y + proj_len * ax.y,
origin.z + proj_len * ax.z)
rad_vec = adsk.core.Vector3D.create(
start_pt.x - axis_pt.x,
start_pt.y - axis_pt.y,
start_pt.z - axis_pt.z)
rad_vec.normalize()
sign = 1.0 if is_external else -1.0
flank_run, short_len, _ = _profile_dimensions(
L, H, angle_degrees)
# 梯形四点(世界坐标)
# Four trapezoid points (world coordinates)
B_world = start_pt
A_world = adsk.core.Point3D.create(
B_world.x + L * ax.x, B_world.y + L * ax.y, B_world.z + L * ax.z)
P_bot_world = adsk.core.Point3D.create(
B_world.x + sign * H * rad_vec.x + flank_run * ax.x,
B_world.y + sign * H * rad_vec.y + flank_run * ax.y,
B_world.z + sign * H * rad_vec.z + flank_run * ax.z)
P_top_world = adsk.core.Point3D.create(
A_world.x + sign * H * rad_vec.x - flank_run * ax.x,
A_world.y + sign * H * rad_vec.y - flank_run * ax.y,
A_world.z + sign * H * rad_vec.z - flank_run * ax.z)
sketch = root.sketches.add(perp_plane)
sketch.name = 'ThreadProfile'
B_sk = sketch.modelToSketchSpace(B_world)
A_sk = sketch.modelToSketchSpace(A_world)
P_bot_sk = sketch.modelToSketchSpace(P_bot_world)
P_top_sk = sketch.modelToSketchSpace(P_top_world)
lines = sketch.sketchCurves.sketchLines
lines.addByTwoPoints(B_sk, A_sk)
lines.addByTwoPoints(A_sk, P_top_sk)
lines.addByTwoPoints(P_top_sk, P_bot_sk)
lines.addByTwoPoints(P_bot_sk, B_sk)
return sketch, short_len
def _do_sweep(root, profile, helix_spline, guide_face, occurrence=None,
operation=adsk.fusion.FeatureOperations.NewBodyFeatureOperation):
"""扫掠:轮廓沿螺旋线路径,圆柱面做引导曲面"""
# Sweep: profile along helix path, using cylinder face as guide surface
path = root.features.createPath(helix_spline, False)
sweeps = root.features.sweepFeatures
sweep_input = sweeps.createInput(
profile, path, operation)
fv = adsk.fusion.BRepFaceVector()
fv.push_back(guide_face)
sweep_input.guideSurfaces = fv
if occurrence:
sweep_input.creationOccurrence = occurrence
return sweeps.add(sweep_input)
def generate_thread(face, tooth_width_mm, tooth_height_mm,
end_offset_mm=0.0, samples_per_turn=16,
join_to_target=False, feature_name='GeneratedThread',
max_turns_per_sweep=4, flank_angle_degrees=45.0,
deviation_ratio=None):
"""Generate a printable trapezoidal thread without opening the GUI.
Args:
face: Cylindrical BRepFace (native face or assembly-context proxy).
tooth_width_mm: Trapezoid long edge / tooth width in millimetres.
tooth_height_mm: Radial tooth height in millimetres.
end_offset_mm: Axial offset from the detected cylinder start.
samples_per_turn: Spline sample count per turn (minimum 4).
join_to_target: Join the generated thread body to the selected body.
feature_name: Browser name for generated sketches/features.
max_turns_per_sweep: Maximum turns in each sweep segment.
flank_angle_degrees: Angle between either flank and the thread axis.
deviation_ratio: Helix deviation as a fraction of tooth height
(default HELIX_DEVIATION_TOLERANCE_RATIO = 0.5). Lower values
increase sampling density and surface smoothness.
Returns:
A JSON-serialisable dict describing the generated thread.
Raises:
ValueError: Invalid face or dimensions.
RuntimeError: Fusion failed to construct or join the thread.
"""
face = adsk.fusion.BRepFace.cast(face)
if not face:
raise ValueError('face must be a BRepFace')
if not adsk.core.Cylinder.cast(face.geometry):
raise ValueError('face must be a true cylindrical BRep face')
L_cm = float(tooth_width_mm) / 10.0
H_cm = float(tooth_height_mm) / 10.0
offset_cm = float(end_offset_mm) / 10.0
pts_per_turn = max(4, int(samples_per_turn))
segment_turn_limit = max(1, int(max_turns_per_sweep))
angle_degrees = float(flank_angle_degrees)
if deviation_ratio is None:
deviation_ratio = HELIX_DEVIATION_TOLERANCE_RATIO
deviation_ratio = float(deviation_ratio)
if not (0.0 < deviation_ratio <= 1.0):
raise ValueError('deviation_ratio must be in (0, 1]')
if L_cm <= 0 or H_cm <= 0:
raise ValueError('tooth_width_mm and tooth_height_mm must be positive')
if not MIN_FLANK_ANGLE_DEG <= angle_degrees <= MAX_FLANK_ANGLE_DEG:
raise ValueError('flank_angle_degrees must be between 5 and 45 degrees')
flank_run_cm, short_cm, _ = _profile_dimensions(
L_cm, H_cm, angle_degrees)
if short_cm < MIN_SHORT_EDGE_CM - PROFILE_TOLERANCE_CM:
raise ValueError('short edge must be at least 0.2 mm')
if offset_cm < 0:
raise ValueError('end_offset_mm must be non-negative')
app = adsk.core.Application.get()
design = adsk.fusion.Design.cast(app.activeProduct)
if not design:
raise RuntimeError('No active Fusion design')
is_external = _is_external_face(face)
radius, cylinder_height, _, _, _ = _get_cyl_info(face)
if not is_external and H_cm >= radius:
raise ValueError('Internal thread tooth height must be smaller than the hole radius')
occurrence = adsk.fusion.Occurrence.cast(face.body.assemblyContext)
if occurrence:
comp = occurrence.component
target_body = face.body.nativeObject
else:
target_body = face.body
comp = target_body.parentComponent
pts, turns, helix_height, pitch, radius = _build_helix(
face, L_cm, flank_run_cm, pts_per_turn, offset_cm,
tooth_height_mm=H_cm * 10.0, deviation_ratio=deviation_ratio)
if turns < 1 or helix_height <= 0:
raise ValueError('Selected cylinder is too short for the requested thread and offset')
if occurrence:
inv = occurrence.transform2.copy()
inv.invert()
local_pts = adsk.core.ObjectCollection.create()
for i in range(pts.count):
pt = pts.item(i).copy()
pt.transformBy(inv)
local_pts.add(pt)
pts = local_pts
safe_name = feature_name or 'GeneratedThread'
timeline_start_index = design.timeline.count
segment_count = int(math.ceil(turns / segment_turn_limit))
sketch_helix = comp.sketches.add(comp.xYConstructionPlane)
sketch_helix.name = safe_name + '_Helix'
sketch_helix.isComputeDeferred = True
segment_splines = []
# Points are laid out uniformly across all turns, so map turn boundaries
# to point indices proportionally. Indexing by the requested pts_per_turn
# would be wrong once adaptive sampling raises the effective density.
total_points = pts.count - 1
for segment_index in range(segment_count):
first_turn = segment_index * segment_turn_limit
last_turn = min(turns, first_turn + segment_turn_limit)
first_point = int(round(first_turn / turns * total_points))
last_point = min(total_points,
int(round(last_turn / turns * total_points)))
segment_points = adsk.core.ObjectCollection.create()
for point_index in range(first_point, last_point + 1):
segment_points.add(pts.item(point_index))
segment_splines.append(
sketch_helix.sketchCurves.sketchFittedSplines.add(
segment_points))
sketch_helix.isComputeDeferred = False
plane_input = comp.constructionPlanes.createInput()
plane_input.setByDistanceOnPath(
segment_splines[0], adsk.core.ValueInput.createByReal(0))
perp_plane = comp.constructionPlanes.add(plane_input)
perp_plane.name = safe_name + '_ProfilePlane'
sketch_trap, short_cm = _create_trapezoid(
comp, perp_plane, face, L_cm, H_cm, angle_degrees,
pts.item(0), is_external)
sketch_trap.name = safe_name + '_Profile'
if sketch_trap.profiles.count == 0:
raise RuntimeError('Thread profile did not form a closed region')
segment_bodies = []
sweep_profile = sketch_trap.profiles.item(0)
for segment_index, spline in enumerate(segment_splines):
suffix = (
'' if segment_count == 1
else '_Segment_' + str(segment_index + 1))
segment_name = safe_name + suffix
source_body = (
sweep_profile.body
if adsk.fusion.BRepFace.cast(sweep_profile)
else None)
sweep_feature = _do_sweep(
comp, sweep_profile, spline, face, occurrence)
sweep_feature.name = segment_name + '_Sweep'
new_bodies = []
for body_index in range(sweep_feature.bodies.count):
candidate = sweep_feature.bodies.item(body_index)
if not source_body or candidate.entityToken != source_body.entityToken:
new_bodies.append(candidate)
if len(new_bodies) != 1:
raise RuntimeError(
'Expected one new body in sweep segment ' +
str(segment_index + 1) + ', got ' +
str(len(new_bodies)))
segment_body = new_bodies[0]
segment_body.name = segment_name + '_Body'
segment_bodies.append(segment_body)
if segment_index + 1 < segment_count:
end_faces = sweep_feature.endFaces
if not end_faces or end_faces.count != 1:
raise RuntimeError(
'Expected one end face in sweep segment ' +
str(segment_index + 1))
sweep_profile = end_faces.item(0)
thread_body = segment_bodies[0]
if len(segment_bodies) > 1:
tools = adsk.core.ObjectCollection.create()
for segment_body in segment_bodies[1:]:
tools.add(segment_body)
combine_input = comp.features.combineFeatures.createInput(
thread_body, tools)
combine_input.operation = (
adsk.fusion.FeatureOperations.JoinFeatureOperation)
combine_input.isKeepToolBodies = False
combine_feature = comp.features.combineFeatures.add(combine_input)
combine_feature.name = safe_name + '_Segments_Join'
thread_body.name = safe_name + '_Body'
joined = False
result_body = thread_body
if join_to_target:
tools = adsk.core.ObjectCollection.create()
tools.add(thread_body)
combine_input = comp.features.combineFeatures.createInput(
target_body, tools)
combine_input.operation = (
adsk.fusion.FeatureOperations.JoinFeatureOperation)
combine_input.isKeepToolBodies = False
combine_feature = comp.features.combineFeatures.add(combine_input)
combine_feature.name = safe_name + '_Join'
result_body = target_body
joined = True
timeline_group_name = ''
try:
timeline_end_index = design.timeline.count - 1
if timeline_end_index >= timeline_start_index:
timeline_group = design.timeline.timelineGroups.add(
timeline_start_index, timeline_end_index)
if timeline_group:
timeline_group.name = safe_name + '_Generation'
timeline_group_name = timeline_group.name
except Exception:
pass # timeline grouping is cosmetic; never fail the generation
app.activeViewport.fit()
return {
'success': True,
'thread_type': 'external' if is_external else 'internal',
'tooth_width_mm': L_cm * 10.0,
'short_edge_mm': short_cm * 10.0,
'tooth_height_mm': H_cm * 10.0,
'flank_angle_degrees': angle_degrees,
'pitch_mm': pitch * 10.0,
'turns': turns,
'thread_length_mm': helix_height * 10.0,
'end_offset_mm': offset_cm * 10.0,
'samples_per_turn': pts_per_turn,
'deviation_ratio': deviation_ratio,
'segment_count': segment_count,
'max_turns_per_sweep': segment_turn_limit,
'cylinder_radius_mm': radius * 10.0,
'cylinder_height_mm': cylinder_height * 10.0,
'joined_to_target': joined,
'timeline_group_name': timeline_group_name,
'result_body_token': result_body.entityToken,
}
def generate_thread_from_json(payload):
"""JSON-friendly automation entry point.
Required payload field:
face_token
Optional fields:
tooth_width_mm, tooth_height_mm, end_offset_mm,
samples_per_turn, join_to_target, feature_name,
max_turns_per_sweep, flank_angle_degrees
"""
if isinstance(payload, str):
payload = json.loads(payload)
if not isinstance(payload, dict):
raise ValueError('payload must be a dict or JSON object string')
token = payload.get('face_token')
if not token:
raise ValueError('payload.face_token is required')
design = adsk.fusion.Design.cast(
adsk.core.Application.get().activeProduct)
if not design:
raise RuntimeError('No active Fusion design')
entities = design.findEntityByToken(token)
if not entities:
raise ValueError('face_token did not resolve in the active design')
face = adsk.fusion.BRepFace.cast(entities[0])
if not face:
raise ValueError('face_token does not identify a BRepFace')
return generate_thread(
face=face,
tooth_width_mm=payload.get('tooth_width_mm', 3.0),
tooth_height_mm=payload.get('tooth_height_mm', 1.0),
end_offset_mm=payload.get('end_offset_mm', 0.0),
samples_per_turn=payload.get('samples_per_turn', 16),
join_to_target=bool(payload.get('join_to_target', False)),
feature_name=payload.get('feature_name', 'GeneratedThread'),
max_turns_per_sweep=payload.get('max_turns_per_sweep', 4),
flank_angle_degrees=payload.get('flank_angle_degrees', 45.0),
deviation_ratio=payload.get('deviation_ratio', None),
)
# ══════════════════════════════════════════════════════
# Command 事件处理器
# Command event handlers
# ══════════════════════════════════════════════════════
class MyCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
def notify(self, args):
try:
cmd = adsk.core.CommandCreatedEventArgs.cast(args).command
inputs = cmd.commandInputs
inputs.addTextBoxCommandInput('hdr', '',
'<b>螺纹生成工具(外/内螺纹自动识别)</b><br/>'
'选择圆柱外表面(螺杆)或圆孔内表面(螺母),自动识别。<br/>'
f'<a href="{PRIVACY_URL}">隐私政策 / Privacy Policy</a>', 3, True)
sel = inputs.addSelectionInput('face', '圆柱/圆孔面', '请点击圆柱外表面或圆孔内表面')
sel.addSelectionFilter('CylindricalFaces')
sel.setSelectionLimits(1, 1)
inputs.addTextBoxCommandInput('sep1', '',
'<b>── 梯形截面参数 ──</b>', 1, True)
inputs.addValueInput('long_L', '长边 L(齿宽)', 'mm',
adsk.core.ValueInput.createByString('3 mm'))
inputs.addValueInput('trap_H', '梯形高度 H(径向牙高)', 'mm',
adsk.core.ValueInput.createByString('1 mm'))
inputs.addValueInput('flank_angle', '牙侧角度(5°–45°)', 'deg',
adsk.core.ValueInput.createByString('45 deg'))
inputs.addTextBoxCommandInput(
'profile_status', '截面状态',
'<b>短边 S: 1.000 mm</b><br/>'
'<font color="green">当前截面为梯形</font>', 2, True)
inputs.addTextBoxCommandInput('sep2', '',
'<b>── 路径参数 ──</b>', 1, True)
inputs.addValueInput('ppt', '每圈采样点数', '',
adsk.core.ValueInput.createByReal(16))
inputs.addValueInput('offset', '端面偏移', 'mm',
adsk.core.ValueInput.createByString('0 mm'))
join_inp = inputs.addBoolValueInput(
'join_target', '合并到圆柱体', True, '', True)
join_inp.tooltip = '将生成的螺纹与所选圆柱体合并为一个实体'
join_inp.tooltipDescription = (
'勾选后,螺纹体会通过布尔合并与所选圆柱体合并为单一实体。<br/><br/>'
'取消勾选则螺纹与圆柱体保持为两个独立实体(仅贴合)。<br/><br/>'
'合并可消除放大时两实体之间的接缝。')
inputs.addBoolValueInput(
'show_advanced', '显示高级选项', False, '', False)
ratio_inp = inputs.addValueInput(
'dev_ratio', '路径偏差系数', '',
adsk.core.ValueInput.createByReal(
HELIX_DEVIATION_TOLERANCE_RATIO))
ratio_inp.isVisible = False
ratio_inp.tooltip = '路径偏差占牙高的比例(0.1–1.0)'
ratio_inp.tooltipDescription = (
'控制螺旋拟合样条偏离圆柱面的允许偏差,'
'以牙高 H 的比例表示。<br/><br/>'
'允许偏差 = 系数 × H。系数越小,每圈采样点越多,'
'牙侧面越光滑,但生成越慢。<br/><br/>'
'默认 0.5(允许偏差 = 牙高的一半),推荐范围 0.2–0.5。'
'过小会显著增加生成时间,过大可能导致扫掠失败。')
inputs.addTextBoxCommandInput('calc_info', '自动计算',
'<i>选择面后自动计算...</i>', 6, True)
on_exec = MyExecuteHandler()
on_change = MyInputChangedHandler()
on_validate = MyValidateHandler()
on_destroy = MyDestroyHandler()
cmd.execute.add(on_exec)
cmd.inputChanged.add(on_change)
cmd.validateInputs.add(on_validate)
cmd.destroy.add(on_destroy)
_handlers.extend([on_exec, on_change, on_validate, on_destroy])
except:
_ui.messageBox(traceback.format_exc(), '初始化失败')
class MyInputChangedHandler(adsk.core.InputChangedEventHandler):
def __init__(self):
super().__init__()
self._syncing_profile = False
self._profile_warning = ''
def notify(self, args):
try:
ea = adsk.core.InputChangedEventArgs.cast(args)
all_ins = ea.firingEvent.sender.commandInputs
sel_inp = adsk.core.SelectionCommandInput.cast(all_ins.itemById('face'))
L_inp = adsk.core.ValueCommandInput.cast(all_ins.itemById('long_L'))
H_inp = adsk.core.ValueCommandInput.cast(all_ins.itemById('trap_H'))
angle_inp = adsk.core.ValueCommandInput.cast(
all_ins.itemById('flank_angle'))
ppt_inp = adsk.core.ValueCommandInput.cast(all_ins.itemById('ppt'))
off_inp = adsk.core.ValueCommandInput.cast(all_ins.itemById('offset'))
adv_inp = adsk.core.BoolValueCommandInput.cast(
all_ins.itemById('show_advanced'))
ratio_inp = adsk.core.ValueCommandInput.cast(
all_ins.itemById('dev_ratio'))
calc_box = adsk.core.TextBoxCommandInput.cast(all_ins.itemById('calc_info'))
profile_box = adsk.core.TextBoxCommandInput.cast(
all_ins.itemById('profile_status'))
changed_id = ea.input.id if ea.input else ''
if (not self._syncing_profile and
changed_id in ('long_L', 'trap_H', 'flank_angle')):
self._syncing_profile = True
try:
requested_angle = math.degrees(angle_inp.value)
angle_deg = min(MAX_FLANK_ANGLE_DEG,
max(MIN_FLANK_ANGLE_DEG,
requested_angle))
if abs(angle_deg - requested_angle) > 1e-7:
angle_inp.value = math.radians(angle_deg)
self._profile_warning = (
'⚠ 牙侧角度仅允许 5°–45°,已自动调整为 '
f'{angle_deg:.1f}°。')
else:
self._profile_warning = ''
L_now = L_inp.value
H_now = H_inp.value
if L_now > MIN_SHORT_EDGE_CM and H_now > 0:
_, short_now, max_height = _profile_dimensions(
L_now, H_now, angle_deg)
if (short_now <
MIN_SHORT_EDGE_CM - PROFILE_TOLERANCE_CM):
H_inp.value = max_height
self._profile_warning = (
'⚠ 当前高度超过该角度允许的最大值,'
f'已自动将 H 调整为 {max_height*10:.3f} mm。'
'短边已限制为最小值 0.200 mm,'
'以避免截面自相交。')
elif abs(short_now - MIN_SHORT_EDGE_CM) <= (
PROFILE_TOLERANCE_CM):
H_inp.value = max_height
self._profile_warning = (
'⚠ 短边已达到最小值 0.200 mm,'
'继续增大 H 会导致截面自相交。')
finally:
self._syncing_profile = False
has_face = sel_inp.selectionCount > 0
L_val = L_inp.value
H_val = H_inp.value
angle_deg = math.degrees(angle_inp.value)
flank_run, raw_S, max_height = _profile_dimensions(
L_val, H_val, angle_deg)
ppt = max(4, int(ppt_inp.value))
offset = off_inp.value
# Toggle the advanced ratio input visibility
ratio_inp.isVisible = bool(adv_inp.value)
# Clamp the ratio to a sane range; use the default when invalid
ratio_val = float(ratio_inp.value)
if not (0.0 < ratio_val <= 1.0):
ratio_val = HELIX_DEVIATION_TOLERANCE_RATIO
if adv_inp.value:
ratio_inp.value = ratio_val
S = max(0.0, raw_S)
P = L_val + S
lines = []
if L_val <= MIN_SHORT_EDGE_CM or H_val <= 0:
profile_box.formattedText = (
f'<b>短边 S: {S*10:.3f} mm</b><br/>'
'<font color="red"><b>⚠ L 必须大于 0.2 mm,'
'且 H 必须大于 0。</b></font>')
elif self._profile_warning:
profile_box.formattedText = (
f'<b>短边 S: {S*10:.3f} mm</b><br/>'
f'<font color="orange"><b>{self._profile_warning}</b></font>')
elif S <= MIN_SHORT_EDGE_CM + PROFILE_TOLERANCE_CM:
profile_box.formattedText = (
'<b>短边 S: 0.200 mm</b><br/>'
'<font color="orange"><b>⚠ 已达到最小短边限制;'
'继续增大 H 会导致截面自相交。</b></font>')
else:
profile_box.formattedText = (
f'<b>短边 S: {S*10:.3f} mm</b><br/>'
'<font color="green">当前截面为梯形</font>')
if has_face and P > 0:
face = adsk.fusion.BRepFace.cast(sel_inp.selection(0).entity)
radius, height, _, _, _ = _get_cyl_info(face)
is_ext = _is_external_face(face)
typ_label = '外螺纹(螺杆)' if is_ext else '内螺纹(螺母)'
dir_label = '向外长肉' if is_ext else '向内长肉'
N = max(1, int((height - offset) / P + 1e-9) - 1) # 留一圈空间;+1e-9防浮点截断
# Reserve one full turn of space
if N * P > height - offset and N > 1:
N -= 1
eff_ppt, N, n_pts, capped = _plan_helix_sampling(
radius, ppt, N, H_val * 10.0, ratio_val)
act_h = N * P
n_total = n_pts + 1 if N > 0 else 0
# 螺旋路径总长度(考虑螺距)
circle_mm = 2 * math.pi * radius * 10 # 每圈周长 mm
P_mm = P * 10
path_m = N * math.sqrt(circle_mm**2 + P_mm**2) / 1000 if N > 0 else 0
lines.append(f'<b>类型:</b> {typ_label}({dir_label})')
lines.append(f'<b>长边 L:</b> {L_val*10:.2f} mm '
f'<b>短边 S:</b> {S*10:.2f} mm')
lines.append(f'<b>梯形高度 H:</b> {H_val*10:.2f} mm '
f'<b>螺距 P:</b> {P*10:.2f} mm')
lines.append(f'<b>牙侧角度:</b> {angle_deg:.2f}° '
f'<b>H 最大值:</b> {max_height*10:.2f} mm')
lines.append(f'<b>圆柱 R={radius*10:.2f} mm H={height*10:.2f} mm</b>')
lines.append(f'<b>转数:</b> {N} 螺旋高度={act_h*10:.2f} mm 偏移={offset*10:.1f} mm')
lines.append(f'<b>螺旋总长:</b> 约 {path_m:.0f} m <b>样条线点数:</b> {n_pts}(每圈 {eff_ppt} 点)')
if adv_inp.value:
lines.append(
f'<b>路径偏差系数:</b> {ratio_val:.2f} '
f'(允许偏差 ≤ {ratio_val * H_val * 10:.3f} mm)')
if capped:
lines.append('<font color="orange">⚠ 圈数已达样条点数预算上限,为保证路径贴合圆柱已自动减少圈数;如需更多圈数请增大端面偏移以外的可用长度或降低每圈采样</font>')
if not is_ext and H_val >= radius:
lines.append('<font color="red">⚠ H 必须 < 圆孔半径</font>')
else:
lines.append('<i>选择圆柱面后自动识别内外螺纹...</i>')
if self._profile_warning:
lines.append(
f'<font color="orange">{self._profile_warning}</font>')
calc_box.formattedText = '<br/>'.join(lines)
except:
pass
class MyValidateHandler(adsk.core.ValidateInputsEventHandler):
def notify(self, args):
try:
ea = adsk.core.ValidateInputsEventArgs.cast(args)
inputs = ea.inputs
sel = adsk.core.SelectionCommandInput.cast(inputs.itemById('face'))
L_inp = adsk.core.ValueCommandInput.cast(inputs.itemById('long_L'))
H_inp = adsk.core.ValueCommandInput.cast(inputs.itemById('trap_H'))
angle_inp = adsk.core.ValueCommandInput.cast(
inputs.itemById('flank_angle'))
L_val = L_inp.value
H_val = H_inp.value
angle_deg = math.degrees(angle_inp.value)
_, short_edge, _ = _profile_dimensions(
L_val, H_val, angle_deg)
valid = (
sel.selectionCount == 1
and L_val > MIN_SHORT_EDGE_CM and H_val > 0
and MIN_FLANK_ANGLE_DEG <= angle_deg <= MAX_FLANK_ANGLE_DEG
and short_edge >= MIN_SHORT_EDGE_CM - PROFILE_TOLERANCE_CM
)
# 内螺纹额外校验:H < radius
# Additional internal thread validation: H < radius
if valid and sel.selectionCount == 1:
face = adsk.fusion.BRepFace.cast(sel.selection(0).entity)
if not _is_external_face(face):
radius, _, _, _, _ = _get_cyl_info(face)
if H_val >= radius:
valid = False
ea.areInputsValid = valid
except:
pass
class MyExecuteHandler(adsk.core.CommandEventHandler):
def notify(self, args):
"""Read GUI inputs and delegate all modelling to the public API."""
try:
inputs = adsk.core.CommandEventArgs.cast(
args).command.commandInputs
selection = adsk.core.SelectionCommandInput.cast(
inputs.itemById('face'))
tooth_width = adsk.core.ValueCommandInput.cast(
inputs.itemById('long_L'))
tooth_height = adsk.core.ValueCommandInput.cast(
inputs.itemById('trap_H'))
flank_angle = adsk.core.ValueCommandInput.cast(
inputs.itemById('flank_angle'))
samples = adsk.core.ValueCommandInput.cast(
inputs.itemById('ppt'))
ratio_inp = adsk.core.ValueCommandInput.cast(
inputs.itemById('dev_ratio'))
join_inp = adsk.core.BoolValueCommandInput.cast(
inputs.itemById('join_target'))
ratio_val = float(ratio_inp.value)
if not (0.0 < ratio_val <= 1.0):
ratio_val = HELIX_DEVIATION_TOLERANCE_RATIO
result = generate_thread(
face=adsk.fusion.BRepFace.cast(
selection.selection(0).entity),
tooth_width_mm=tooth_width.value * 10.0,
tooth_height_mm=tooth_height.value * 10.0,
end_offset_mm=inputs.itemById('offset').value * 10.0,
samples_per_turn=max(4, int(samples.value)),
join_to_target=bool(join_inp.value),
feature_name='GeneratedThread',
flank_angle_degrees=math.degrees(flank_angle.value),
deviation_ratio=ratio_val,
)
thread_label = (
'外螺纹(螺杆)'
if result['thread_type'] == 'external'
else '内螺纹(螺母)')
message = (
f'✓ {thread_label}生成完成!\n\n'
f"【截面】L={result['tooth_width_mm']:.2f} mm "
f"S={result['short_edge_mm']:.2f} mm "
f"H={result['tooth_height_mm']:.2f} mm\n"
f"牙侧角度={result['flank_angle_degrees']:.2f}°\n"
f"【螺旋】P={result['pitch_mm']:.2f} mm "
f"转数={result['turns']} "
f"高度={result['thread_length_mm']:.2f} mm\n"
f"【结果】{'已合并到圆柱体(实体=1)' if result['joined_to_target'] else '独立螺纹体(实体=2:螺纹+圆柱)'}"
)
radius_mm = result['cylinder_radius_mm']
height_mm = result['tooth_height_mm']
clr = RECOMMENDED_CLEARANCE_MM
dia_clr = 2 * clr
if result['thread_type'] == 'external':
base_diameter = 2 * radius_mm + 2 * height_mm
suggested = base_diameter + dia_clr
message += (
'\n\n📌 配合螺母建议内径:\n'
f' 圆柱外径({2 * radius_mm:.1f} mm)+ '
f'{2 * height_mm:.1f} mm(2 × H)+ 间隙\n'
f' = {base_diameter:.1f} mm + 间隙\n'
f' 建议间隙(单侧)≈ {clr:.1f} mm → 内径 ≈ {suggested:.1f} mm\n'
f' (FDM 打印常用单侧间隙 0.2–0.4 mm,可按打印机精度调整)')
else:
base_diameter = 2 * radius_mm - 2 * height_mm
suggested = base_diameter - dia_clr
message += (
'\n\n📌 配合螺杆建议外径:\n'
f' 圆孔内径({2 * radius_mm:.1f} mm)- '
f'{2 * height_mm:.1f} mm(2 × H)- 间隙\n'
f' = {base_diameter:.1f} mm - 间隙\n'
f' 建议间隙(单侧)≈ {clr:.1f} mm → 外径 ≈ {suggested:.1f} mm\n'
f' (FDM 打印常用单侧间隙 0.2–0.4 mm,可按打印机精度调整)')
_ui.messageBox(message, '生成成功')
except:
_ui.messageBox(
traceback.format_exc(), '执行失败')
def _notify_legacy(self, args):
try:
inputs = adsk.core.CommandEventArgs.cast(args).command.commandInputs
sel_inp = adsk.core.SelectionCommandInput.cast(inputs.itemById('face'))
L_inp = adsk.core.ValueCommandInput.cast(inputs.itemById('long_L'))
H_inp = adsk.core.ValueCommandInput.cast(inputs.itemById('trap_H'))
ppt_inp = adsk.core.ValueCommandInput.cast(inputs.itemById('ppt'))
face = adsk.fusion.BRepFace.cast(sel_inp.selection(0).entity)
L_cm = L_inp.value
H_cm = H_inp.value
pts_per_turn = max(4, int(ppt_inp.value))
offset_cm = inputs.itemById('offset').value
is_external = _is_external_face(face)
design = adsk.fusion.Design.cast(_app.activeProduct)
root = design.rootComponent
# 确定工作上下文:实体用 root,零件用子组件
occ = adsk.fusion.Occurrence.cast(face.body.assemblyContext)
comp = occ.component if occ else root
# ── 步骤1:螺旋线路径 ──
# ── Step 1: Helix path ──
pts, turns, helix_height, P, radius = _build_helix(
face, L_cm, H_cm, pts_per_turn, offset_cm,
tooth_height_mm=H_cm * 10.0)
# 如果是子组件,将全局坐标转为局部坐标
if occ:
inv = occ.transform2.copy()
inv.invert()
local_pts = adsk.core.ObjectCollection.create()
for i in range(pts.count):
pt = pts.item(i).copy()
pt.transformBy(inv)
local_pts.add(pt)
pts = local_pts
sname = f'Helix_R{radius:.2f}_P{P:.2f}'
sketch_helix = comp.sketches.add(comp.xYConstructionPlane)
sketch_helix.name = sname
sketch_helix.isComputeDeferred = True
spline = sketch_helix.sketchCurves.sketchFittedSplines.add(pts)
sketch_helix.isComputeDeferred = False
# ── 步骤2:路径起点处垂直平面 ──
# ── Step 2: Perpendicular plane at path start ──
pi = comp.constructionPlanes.createInput()
pi.setByDistanceOnPath(spline, adsk.core.ValueInput.createByReal(0))
perp_plane = comp.constructionPlanes.add(pi)
perp_plane.name = 'PerpPlane'
# ── 步骤3:梯形截面 ──
# ── Step 3: Trapezoid cross-section ──
sketch_trap, short_cm = _create_trapezoid(
comp, perp_plane, face, L_cm, H_cm, 45.0,
pts.item(0), is_external)
# ── 步骤4:获取轮廓 ──
# ── Step 4: Get profile ──
if sketch_trap.profiles.count == 0:
raise RuntimeError('梯形未形成封闭轮廓,请检查 L > H')
profile = sketch_trap.profiles.item(0)
# ── 步骤5:Sweep ──
# ── Step 5: Sweep ──
sweep_feature = _do_sweep(comp, profile, spline, face, occ)
_app.activeViewport.fit()
S_mm = short_cm * 10
typ_label = '外螺纹(螺杆)' if is_external else '内螺纹(螺母)'
msg = (
f'✅ {typ_label} 生成完成!\n\n'
f'【截面】 L={L_cm*10:.2f} mm S={S_mm:.2f} mm H={H_cm*10:.2f} mm\n'
f'【螺旋】 P={P*10:.2f} mm 转数={turns} 高度={helix_height*10:.2f} mm\n'
f'【结果】 实体={sweep_feature.bodies.count}'
)
R_mm = radius * 10
if is_external:
nut_dia = 2 * R_mm + 2 * H_cm * 10
msg += (
f'\n\n📌 配合螺母建议内径:\n'
f' 螺母内径 ≈ 圆柱外径({2*R_mm:.1f}mm) + {2*H_cm*10:.1f}mm (2×H) + 间隙\n'
f' = {nut_dia:.1f}mm + 间隙(建议 0.3~0.5mm)'
)
else:
screw_dia = 2 * R_mm - 2 * H_cm * 10
msg += (
f'\n\n📌 配合螺杆建议外径:\n'
f' 螺杆外径 ≈ 圆孔内径({2*R_mm:.1f}mm) - {2*H_cm*10:.1f}mm (2×H) - 间隙\n'
f' = {screw_dia:.1f}mm - 间隙(建议 0.3~0.5mm)'
)
_ui.messageBox(msg, '生成成功')
except:
_ui.messageBox(traceback.format_exc(), '执行失败')
class MyDestroyHandler(adsk.core.CommandEventHandler):
def notify(self, args):
# 只清理命令执行相关的 handler,保留 commandCreated handler 以支持下次点击
global _handlers
_handlers[:] = [h for h in _handlers if isinstance(h, MyCommandCreatedHandler)]
# ══════════════════════════════════════════════════════
# 入口(Add-In 模式)
# Entry (Add-In mode)
# ══════════════════════════════════════════════════════