-
Notifications
You must be signed in to change notification settings - Fork 4
/
ABENICS.py
1349 lines (1089 loc) · 52 KB
/
ABENICS.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
"""
Fusion360 Script to make Special Spherical Gear, ABENICS
Script to make ABENICS with Fusion360.
This script is derived from SpurGear.py which is a sample of Fusion360 written by Brian Ekins
Kazuki Abe, Kenjiro Tadakuma and Riichiro Tadakuma develop ABENICS.
ABENICS system is patent pending.
You have to pay attention to create and use the gears and application.
Note:
Default length unit of Fusion360 Script is cm.
IEEE Paper of ABENICS: https://ieeexplore.ieee.org/document/9415699
Video :https://www.youtube.com/watch?v=hhDdfiRCQS4
Gear: https://en.wikipedia.org/wiki/Gear
Patent: https://jstore.jst.go.jp/nationalPatentDetail.html?pat_id=38455
"""
import adsk.core
import adsk.fusion
import adsk.cam
import traceback
import math
# Globals
_app = adsk.core.Application.cast(None)
_ui = adsk.core.UserInterface.cast(None)
_units = ''
# Command inputs
_imgInputEnglish = adsk.core.ImageCommandInput.cast(None)
_imgInputMetric = adsk.core.ImageCommandInput.cast(None)
# adsk standard system
_standard = adsk.core.DropDownCommandInput.cast(None)
# common gear parameters
_pressureAngle = adsk.core.DropDownCommandInput.cast(None)
_pressureAngleCustom = adsk.core.ValueCommandInput.cast(None)
_module = adsk.core.ValueCommandInput.cast(None)
_rootFilletRad = adsk.core.ValueCommandInput.cast(None)
_backlash = adsk.core.ValueCommandInput.cast(None)
_diaPitch = adsk.core.ValueCommandInput.cast(None)
_gear_ratio = adsk.core.StringValueCommandInput.cast(None)
# CS Gear
_num_teeth_cs = adsk.core.StringValueCommandInput.cast(None)
# MP Gear
_thickness = adsk.core.ValueCommandInput.cast(None)
_holeDiam = adsk.core.ValueCommandInput.cast(None)
# Engrave
_num_rotation_steps = adsk.core.StringValueCommandInput.cast(None)
# reference
_pitch_diameter_cs = adsk.core.TextBoxCommandInput.cast(None)
_pitch_diameter_mp = adsk.core.TextBoxCommandInput.cast(None)
_errMessage = adsk.core.TextBoxCommandInput.cast(None)
_handlers = []
_app_name = 'ABENICS'
def defineCommandDialog(inputs, standard, pressureAngle):
global _standard, _pressureAngle, _pressureAngleCustom, _diaPitch, _module, _rootFilletRad, _thickness, _holeDiam, _backlash, _imgInputEnglish, _imgInputMetric, _errMessage
# _imgInputEnglish = inputs.addImageCommandInput(
# 'gearImageEnglish', '', 'Resources/GearEnglish.png')
# _imgInputEnglish.isFullWidth = True
_imgInputMetric = inputs.addImageCommandInput(
'gearImageMetric', '', 'Resources/GearMetric.png')
_imgInputMetric.isFullWidth = True
_standard = inputs.addDropDownCommandInput(
'standard', 'Standard', adsk.core.DropDownStyles.TextListDropDownStyle)
# if standard == "English":
# _standard.listItems.add('English', True)
# _standard.listItems.add('Metric', False)
# _imgInputMetric.isVisible = False
# else:
# _standard.listItems.add('English', False)
_standard.listItems.add('Metric', True)
# _imgInputEnglish.isVisible = False
_pressureAngle = inputs.addDropDownCommandInput(
'pressureAngle', 'Pressure Angle', adsk.core.DropDownStyles.TextListDropDownStyle)
if pressureAngle == '14.5 deg':
_pressureAngle.listItems.add('14.5 deg', True)
else:
_pressureAngle.listItems.add('14.5 deg', False)
if pressureAngle == '20 deg':
_pressureAngle.listItems.add('20 deg', True)
else:
_pressureAngle.listItems.add('20 deg', False)
if pressureAngle == '25 deg':
_pressureAngle.listItems.add('25 deg', True)
else:
_pressureAngle.listItems.add('25 deg', False)
if pressureAngle == 'Custom':
_pressureAngle.listItems.add('Custom', True)
else:
_pressureAngle.listItems.add('Custom', False)
class ABENICS:
"""
Attributes:
module (float): module of gears
pressure_angle (float): pressure angle of gears
backlash (float): backlash
diameter_cs (float): diameter of pitch circle of a ball gear
num_teeth_cs (int): the num. of teeth of the cs-gear as a spurgear
diameter_mp (float): diameter of pitch circle of the mp-gear
num_teeth_mp (int): the num. of teeth of the mp-gear
diameter_hole_mp (float): hole diameter of the mp-gear
thickness_mp (float): thickness of the mp-gear
gear_ratio (float): gear ratio (CS/MP) should be 2.0
Notes:
module = diameter / num_teeth
pitch_angle = 2 * pi / num_teeth
https://en.wikipedia.org/wiki/Backlash_(engineering)
"""
def __init__(self, design,
module=1.0, pressure_angle=20.0 * math.pi/180.0,
num_teeth_cs=40, gear_ratio=2, thickness=4.0, hole_diameter=0.4, backlash=0) -> None:
# common parameters
self.module = module
self.pressure_angle = pressure_angle # [rad]
self.backlash = backlash
self.gear_ratio = gear_ratio
self.num_teeth_cs = num_teeth_cs
self.diameter_cs = 0.1*(self.module*self.num_teeth_cs) # mm->cm
self.pitch_angle = 2.0*math.pi/self.num_teeth_cs
self.diameter_mp = self.diameter_cs/self.gear_ratio
self.num_teeth_mp = int(self.num_teeth_cs/self.gear_ratio)
self.diameter_hole_mp = hole_diameter
self.thickness_mp = thickness
# Create a new component by creating an occurrence.
self.root_occurrences = design.rootComponent.occurrences
def print(self):
print('module : {:0.2f}'.format(self.module))
print('pressure_angle : {:0.2f} deg'.format(
self.pressure_angle*(180/math.pi)))
print('backlash : {:0.2f} mm'.format(10*self.backlash))
print('gear_ratio : {:0.2f}'.format(self.gear_ratio))
print('num_teeth_cs : {:0.2f}'.format(self.num_teeth_cs))
print('diameter_cs : {:0.2f} mm'.format(10*self.diameter_cs))
print('diameter_mp : {:0.2f} mm'.format(10*self.diameter_mp))
def make_sh_cutter_comp(self):
mat = adsk.core.Matrix3D.create()
newOcc = self.root_occurrences.addNewComponent(mat)
self.sh_cutter_comp = adsk.fusion.Component.cast(newOcc.component)
self.sh_cutter_comp.name = 'SH-Cutter'
def make_cs_comp(self):
mat = adsk.core.Matrix3D.create()
newOcc = self.root_occurrences.addNewComponent(mat)
self.cs_comp = adsk.fusion.Component.cast(newOcc.component)
self.cs_comp.name = 'CS-Gear:{}'.format(self.num_teeth_cs)
def make_mp_comp(self):
mat = adsk.core.Matrix3D.create()
newOcc = self.root_occurrences.addNewComponent(mat)
self.mp_comp = adsk.fusion.Component.cast(newOcc.component)
self.mp_comp.name = 'MP-Gear:{}'.format(self.num_teeth_mp)
def draw_tooth(self, sketch, root_diameter, tip_diameter, angle=0, backlash=None):
"""draw tooth of a gear
"""
base_diameter = self.diameter_cs * \
math.cos(self.pressure_angle)
# Calculate points along the involute curve.
involute_point_count = 15 # resolution
involuteIntersectionRadius = 0.5 * base_diameter
involute_points_a = []
involute_points_a = get_involutePoints(
base_diameter, tip_diameter, num=involute_point_count)
# Get the point along the tooth that's at the pitch diameter and then
# calculate the angle to that point.
pitch_involute_point = involutePoint(
0.5*base_diameter, 0.5*self.diameter_cs)
pitch_point_angle = math.atan(
pitch_involute_point.y / pitch_involute_point.x)
# Determine the angle defined by the tooth thickness as measured at
# the pitch diameter circle.
# ! this is half circular pitch angle
tooth_thickness_angle = (2 * math.pi) / (2 * self.num_teeth_cs)
if backlash is None:
backlash = self.backlash
# Determine the angle needed for the specified backlash.
backlashAngle = (backlash / (0.5*self.diameter_cs)) * .25
# Determine the angle to rotate the curve.
rotate_angle = -((0.5*tooth_thickness_angle) +
pitch_point_angle - backlashAngle)
# Rotate the involute so the middle of the tooth lies on the x axis.
involute_points_a = rotate_points(involute_points_a, rotate_angle)
# Create a new set of points with a negated y. This effectively mirrors the original
# points about the X axis.
involute_points_b = []
for i in range(0, involute_point_count):
involute_points_b.append(adsk.core.Point3D.create(
involute_points_a[i].x, -involute_points_a[i].y, 0))
# rotate points by inputted angle
involute_points_a = rotate_points(
involute_points_a, angle)
involute_points_b = rotate_points(
involute_points_b, angle)
curve1Dist, curve1Angle = xy2polar(involute_points_a)
curve2Dist, curve2Angle = xy2polar(involute_points_b)
sketch.isComputeDeferred = True
# Create and load an object collection with the points.
point_set = adsk.core.ObjectCollection.create()
for i in range(0, involute_point_count):
point_set.add(involute_points_a[i])
# Create the first spline.
spline_a = sketch.sketchCurves.sketchFittedSplines.add(point_set)
# Add the involute points for the second spline to an ObjectCollection.
point_set = adsk.core.ObjectCollection.create()
for i in range(0, involute_point_count):
point_set.add(involute_points_b[i])
# Create the second spline.
spline_b = sketch.sketchCurves.sketchFittedSplines.add(point_set)
# Draw the arc for the top of the tooth.
midPoint = adsk.core.Point3D.create((0.5*tip_diameter), 0, 0)
midPoint = rotate_points(midPoint, angle)
sketch.sketchCurves.sketchArcs.addByThreePoints(
spline_a.endSketchPoint, midPoint, spline_b.endSketchPoint)
# Check to see if involute goes down to the root or not. If not, then
# create lines to connect the involute to the root.
if(base_diameter < root_diameter):
sketch.sketchCurves.sketchLines.addByTwoPoints(
spline_b.startSketchPoint, spline_a.startSketchPoint)
else:
rootPoint1 = adsk.core.Point3D.create(
(0.5*root_diameter - 0.001) * math.cos(curve1Angle[0]), (0.5*root_diameter) * math.sin(curve1Angle[0]), 0)
line1 = sketch.sketchCurves.sketchLines.addByTwoPoints(
rootPoint1, spline_a.startSketchPoint)
rootPoint2 = adsk.core.Point3D.create(
(0.5*root_diameter - 0.001) * math.cos(curve2Angle[0]), (0.5*root_diameter) * math.sin(curve2Angle[0]), 0)
line2 = sketch.sketchCurves.sketchLines.addByTwoPoints(
rootPoint2, spline_b.startSketchPoint)
baseLine = sketch.sketchCurves.sketchLines.addByTwoPoints(
line1.startSketchPoint, line2.startSketchPoint)
# Make the lines tangent to the spline so the root fillet will behave correctly.
line1.isFixed = True
line2.isFixed = True
sketch.geometricConstraints.addTangent(spline_a, line1)
sketch.geometricConstraints.addTangent(spline_b, line2)
def assign_values(self, **kwargs):
pass
def draw_gear(self, sketch, axis_angle=0, backlash=None):
# https://eow.alc.co.jp/search?q=dedendum
# https://khkgears.net/new/gear_knowledge/abcs_of_gears-b/basic_gear_terminology_calculation.html
# Tooth depth
# h = 2.25 * self.module
addendum = 1.0 * self.module
dedendum = 1.25 * self.module
dedendum *= 0.1 # mm->cm
root_dia = self.diameter_cs - 2 * dedendum
# root_dia = self.diameter_cs - 2.5*self.module
baseCircleDia = self.diameter_cs * math.cos(self.pressure_angle)
# tip diameter
tip_diameter = self.diameter_cs + 2 * self.module * 0.1
origin = adsk.core.Point3D.create(0, 0, 0)
# Draw a root fan shape.
arc_start = adsk.core.Point3D.create(0.5*root_dia, 0, 0)
arc_end = adsk.core.Point3D.create(-0.5*root_dia, 0, 0)
arc_start = rotate_points(arc_start, axis_angle)
arc_end = rotate_points(arc_end, axis_angle)
sketch.sketchCurves.sketchArcs.addByCenterStartSweep(
origin, arc_start, math.pi)
l = sketch.sketchCurves.sketchLines.addByTwoPoints(
arc_start,
arc_end)
# draw tip circle
c = sketch.sketchCurves.sketchCircles.addByCenterRadius(
adsk.core.Point3D.create(0, 0, 0), 0.5*tip_diameter)
c.isConstruction = True
# draw tooth
for i in range(int(0.5*self.num_teeth_cs)):
angle = self.pitch_angle * i + 0.5*self.pitch_angle + axis_angle
self.draw_tooth(sketch,
root_diameter=root_dia,
tip_diameter=tip_diameter,
angle=angle,
backlash=backlash)
sketch.isComputeDeferred = False
return sketch, l
def revolve_ballgear(self, comp, sk, ax_line,
operation=adsk.fusion.FeatureOperations.NewBodyFeatureOperation,
bodies=None):
# revolve profiles
revolves = comp.features.revolveFeatures
profile_set = adsk.core.ObjectCollection.create()
for i in range(len(sk.profiles)):
profile_set.add(sk.profiles.item(i))
revInput = revolves.createInput(
profile_set, ax_line, operation)
if bodies is not None:
revInput.participantBodies = bodies
angle = adsk.core.ValueInput.createByReal(2*math.pi)
revInput.setAngleExtent(False, angle)
rev = revolves.add(revInput)
return rev
def draw_mp_sketch(self, sketch):
tip_diameter = self.diameter_mp + 2 * self.module * 0.1
center = adsk.core.Point3D.create(
0.5*self.diameter_mp+0.5*self.diameter_cs, 0, 0)
c = sketch.sketchCurves.sketchCircles.addByCenterRadius(
center, 0.5*tip_diameter)
sketch.sketchCurves.sketchCircles.addByCenterRadius(
center, 0.5*self.diameter_hole_mp)
def extrude_mp(self, sketch, thickness):
prof = adsk.fusion.Profile.cast(None)
# Find the profile that uses both circles.
for prof in sketch.profiles:
if prof.profileLoops.count == 2:
break
extrudes = self.mp_comp.features.extrudeFeatures
extInput = extrudes.createInput(
prof, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
# Define that the extent is a distance extent of 5 cm.
distance = adsk.core.ValueInput.createByReal(thickness)
# extInput.setDistanceExtent(False, distance)
extInput.setSymmetricExtent(distance, True)
mp_extrude = extrudes.add(extInput)
return mp_extrude
def engrave(self):
combines = self.mp_comp.features.combineFeatures
tool_bodies = adsk.core.ObjectCollection.create()
tool_bodies.add(self.sh_cutter_comp.bRepBodies.item(0))
combine_input = combines.createInput(
targetBody=self.mp_comp.bRepBodies.item(0),
toolBodies=tool_bodies
)
combine_input.isKeepToolBodies = True
combine_input.operation = adsk.fusion.FeatureOperations.CutFeatureOperation
return combines.add(combine_input)
def rotate_gears(self, angle):
"""rotate gear bodies
Args:
angle (float): 0--2*math.pi
"""
z_up = adsk.core.Vector3D.create(0, 0, 1)
# rotate cs gear
moves = self.sh_cutter_comp.features.moveFeatures
bodies = adsk.core.ObjectCollection.create()
bodies.add(self.sh_cutter_comp.bRepBodies.item(0))
tf = adsk.core.Matrix3D.create()
tf.setToRotation(
angle=angle/self.gear_ratio,
axis=z_up,
origin=adsk.core.Point3D.create(0, 0, 0)
)
move_input = moves.createInput(bodies, tf)
move_sh = moves.add(move_input)
# rotate mp gear
moves = self.mp_comp.features.moveFeatures
bodies = adsk.core.ObjectCollection.create()
bodies.add(self.mp_comp.bRepBodies.item(0))
tf = adsk.core.Matrix3D.create()
x = 0.5 * self.diameter_cs + 0.5*self.diameter_mp
tf.setToRotation(
angle=-angle,
axis=z_up,
origin=adsk.core.Point3D.create(x, 0, 0)
)
move_input = moves.createInput(bodies, tf)
move_mp = moves.add(move_input)
return move_sh, move_mp
def Create():
# Draw Spurgear for a ball gear
# Revolve the spurgear sketch around x-axis to create a new body
# Revolve the spurgear sketch around y-axis
# Draw Circles for a pinion gear
# Extrude the sketch to make a new body
# rotate ball gear and the new body and engrave teeth
pass
def run(context):
try:
global _app, _ui
_app = adsk.core.Application.get()
_ui = _app.userInterface
cmdDef = _ui.commandDefinitions.itemById('adskABENICSPythonScript')
if not cmdDef:
# Create a command definition.
cmdDef = _ui.commandDefinitions.addButtonDefinition(
'adskABENICSPythonScript', 'ABENICS', 'Creates a ABENICS component', 'Resources/ABENICS')
# Connect to the command created event.
onCommandCreated = GearCommandCreatedHandler()
cmdDef.commandCreated.add(onCommandCreated)
_handlers.append(onCommandCreated)
# Execute the command.
cmdDef.execute()
# prevent this module from being terminate when the script returns, because we are waiting for event handlers to fire
adsk.autoTerminate(False)
except:
if _ui:
_ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
class GearCommandDestroyHandler(adsk.core.CommandEventHandler):
def __init__(self):
super().__init__()
def notify(self, args):
try:
eventArgs = adsk.core.CommandEventArgs.cast(args)
# when the command is done, terminate the script
# this will release all globals which will remove all event handlers
adsk.terminate()
except:
if _ui:
_ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
# Verfies that a value command input has a valid expression and returns the
# value if it does. Otherwise it returns False. This works around a
# problem where when you get the value from a ValueCommandInput it causes the
# current expression to be evaluated and updates the display. Some new functionality
# is being added in the future to the ValueCommandInput object that will make
# this easier and should make this function obsolete.
def getCommandInputValue(commandInput, unitType):
try:
valCommandInput = adsk.core.ValueCommandInput.cast(commandInput)
if not valCommandInput:
return (False, 0)
# Verify that the expression is valid.
des = adsk.fusion.Design.cast(_app.activeProduct)
unitsMgr = des.unitsManager
if unitsMgr.isValidExpression(valCommandInput.expression, unitType):
value = unitsMgr.evaluateExpression(
valCommandInput.expression, unitType)
return (True, value)
else:
return (False, 0)
except:
if _ui:
_ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
def setInitialUnit(design):
defaultUnits = design.unitsManager.defaultLengthUnits
# Determine whether to use inches or millimeters as the intial default.
global _units
if defaultUnits == 'in' or defaultUnits == 'ft':
_units = 'in'
else:
_units = 'mm'
# Event handler for the commandCreated event.
def AssignEvents(cmd):
onExecute = GearCommandExecuteHandler()
cmd.execute.add(onExecute)
_handlers.append(onExecute)
onInputChanged = GearCommandInputChangedHandler()
cmd.inputChanged.add(onInputChanged)
_handlers.append(onInputChanged)
onValidateInputs = GearCommandValidateInputsHandler()
cmd.validateInputs.add(onValidateInputs)
_handlers.append(onValidateInputs)
onDestroy = GearCommandDestroyHandler()
cmd.destroy.add(onDestroy)
_handlers.append(onDestroy)
class GearCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
def __init__(self):
super().__init__()
def notify(self, args):
"""notify command information
system call this method just after executing this script
"""
try:
eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
# Verify that a Fusion design is active.
des = adsk.fusion.Design.cast(_app.activeProduct)
if not des:
_ui.messageBox(
'A Fusion design must be active when invoking this command.')
return()
defaultUnits = des.unitsManager.defaultLengthUnits
# Determine whether to use inches or millimeters as the initial default.
global _units
# if defaultUnits == 'in' or defaultUnits == 'ft':
# _units = 'in'
# else:
_units = 'mm'
# Define the default values and get the previous values from the attributes.
# if _units == 'in':
# standard = 'English'
# else:
standard = 'Metric'
standardAttrib = des.attributes.itemByName(_app_name, 'standard')
if standardAttrib:
standard = standardAttrib.value
# if standard == 'English':
# _units = 'in'
# else:
_units = 'mm'
pressureAngle = '20 deg' # initial value
pressureAngleAttrib = des.attributes.itemByName(
_app_name, 'pressureAngle')
if pressureAngleAttrib:
pressureAngle = pressureAngleAttrib.value
pressureAngleCustom = 20 * (math.pi/180.0)
pressureAngleCustomAttrib = des.attributes.itemByName(
_app_name, 'pressureAngleCustom')
if pressureAngleCustomAttrib:
pressureAngleCustom = float(pressureAngleCustomAttrib.value)
metricModule = '1'
moduleAttrib = des.attributes.itemByName(_app_name, 'module')
if moduleAttrib:
metricModule = moduleAttrib.value
backlash = '0'
backlashAttrib = des.attributes.itemByName(_app_name, 'backlash')
if backlashAttrib:
backlash = backlashAttrib.value
rootFilletRad = str(0)
rootFilletRadAttrib = des.attributes.itemByName(
_app_name, 'rootFilletRad')
if rootFilletRadAttrib:
rootFilletRad = rootFilletRadAttrib.value
thickness = str(0.5 * 4)
thicknessAttrib = des.attributes.itemByName(
_app_name, 'thickness')
if thicknessAttrib:
thickness = thicknessAttrib.value
holeDiam = str(0.4)
holeDiamAttrib = des.attributes.itemByName(_app_name, 'holeDiam')
if holeDiamAttrib:
holeDiam = holeDiamAttrib.value
num_teeth_cs = '40'
num_teeth_sh_attr = des.attributes.itemByName(
_app_name, 'num_teeth_cs')
if num_teeth_sh_attr:
num_teeth_cs = num_teeth_sh_attr.value
gear_ratio = '2'
gear_ratio_attr = des.attributes.itemByName(
_app_name, 'gear_ratio')
if gear_ratio_attr:
gear_ratio = gear_ratio_attr.value
num_rotation_steps = '36'
num_rotation_steps_attr = des.attributes.itemByName(
_app_name, 'num_rotation_steps')
if num_rotation_steps_attr:
num_rotation_steps = num_rotation_steps_attr.value
cmd = eventArgs.command
cmd.isExecutedWhenPreEmpted = False
inputs = cmd.commandInputs
global _standard, _pressureAngle, _pressureAngleCustom, _diaPitch, _module, _rootFilletRad, _thickness, _holeDiam, _backlash, _imgInputMetric, _errMessage
global _num_teeth_cs, _gear_ratio, _num_rotation_steps
# Define the command dialog.
defineCommandDialog(inputs, standard, pressureAngle)
_pressureAngleCustom = inputs.addValueInput(
'pressureAngleCustom', 'Custom Angle', 'deg', adsk.core.ValueInput.createByReal(pressureAngleCustom))
if pressureAngle != 'Custom':
_pressureAngleCustom.isVisible = False
_module = inputs.addValueInput(
'module', 'Module', '', adsk.core.ValueInput.createByReal(float(metricModule)))
# if standard == 'English':
# _module.isVisible = False
# elif standard == 'Metric':
# _diaPitch.isVisible = False
_backlash = inputs.addValueInput(
'backlash', 'Backlash', _units, adsk.core.ValueInput.createByReal(float(backlash)))
_rootFilletRad = inputs.addValueInput(
'rootFilletRad', 'Root Fillet Radius', _units, adsk.core.ValueInput.createByReal(float(rootFilletRad)))
# hide rootfillet to avoid confusion
# todo: activate root fillet
_rootFilletRad.isVisible = False
_thickness = inputs.addValueInput(
'thickness', 'Gear Thickness', _units, adsk.core.ValueInput.createByReal(float(thickness)))
_holeDiam = inputs.addValueInput(
'holeDiam', 'Hole Diameter', _units, adsk.core.ValueInput.createByReal(float(holeDiam)))
_num_teeth_cs = inputs.addStringValueInput(
'num_teeth_cs', 'Num Teeth of CS-Gear', num_teeth_cs)
_gear_ratio = inputs.addValueInput(
'gear_ratio', 'Gear Ratio', '', adsk.core.ValueInput.createByReal(float(gear_ratio)))
_num_rotation_steps = inputs.addStringValueInput(
'num_rotation_steps', 'Num Rotation Steps to Engrave', num_rotation_steps)
# dependant variables
global _pitch_diameter_cs, _pitch_diameter_mp
_pitch_diameter_cs = inputs.addTextBoxCommandInput(
'pitch_diameter_cs', 'CS-Gear Diameter', '', 1, True)
_pitch_diameter_mp = inputs.addTextBoxCommandInput(
'pitch_diameter_mp', 'MP-Gear Diameter', '', 1, True)
_errMessage = inputs.addTextBoxCommandInput(
'errMessage', '', '', 2, True)
_errMessage.isFullWidth = True
# Connect to the command related events.
AssignEvents(cmd)
except:
if _ui:
_ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
def SaveValueAsAttributes(attribs):
"""
Args:
attribs : attributes, adsk.fusion.Design.cast(_app.activeProduct).attributes
"""
# if _standard.selectedItem.name == 'English':
# diaPitch = _module.value*2.54
# elif _standard.selectedItem.name == 'Metric':
# diaPitch = 25.4 / _module.value
attribs.add(_app_name, 'standard', _standard.selectedItem.name)
attribs.add(_app_name, 'pressureAngle',
_pressureAngle.selectedItem.name)
attribs.add(_app_name, 'pressureAngleCustom',
str(_pressureAngleCustom.value))
attribs.add(_app_name, 'module', str(_module.value))
attribs.add(_app_name, 'rootFilletRad', str(_rootFilletRad.value))
attribs.add(_app_name, 'backlash', str(_backlash.value))
attribs.add(_app_name, 'gear_ratio', str(_gear_ratio.value))
# CS Gear
attribs.add(_app_name, 'num_teeth_cs', str(_num_teeth_cs.value))
# MP Gear
attribs.add(_app_name, 'thickness', str(_thickness.value))
attribs.add(_app_name, 'holeDiam', str(_holeDiam.value))
attribs.add(_app_name, 'num_rotation_steps',
str(_num_rotation_steps.value))
# Event handler for the execute event.
class GearCommandExecuteHandler(adsk.core.CommandEventHandler):
def __init__(self):
super().__init__()
def notify(self, args):
"""
system executes this method when you press the [run] button
"""
try:
eventArgs = adsk.core.CommandEventArgs.cast(args)
# if _standard.selectedItem.name == 'English':
# diaPitch = _diaPitch.value*25.4
# elif _standard.selectedItem.name == 'Metric':
# diaPitch = _module.value
# Save the current values as attributes.
des = adsk.fusion.Design.cast(_app.activeProduct)
attribs = des.attributes
SaveValueAsAttributes(attribs)
# Get the current values.
if _pressureAngle.selectedItem.name == 'Custom':
pressureAngle = _pressureAngleCustom.value
else:
if _pressureAngle.selectedItem.name == '14.5 deg':
pressureAngle = 14.5 * (math.pi/180)
elif _pressureAngle.selectedItem.name == '20 deg':
pressureAngle = 20.0 * (math.pi/180)
elif _pressureAngle.selectedItem.name == '25 deg':
pressureAngle = 25.0 * (math.pi/180)
rootFilletRad = _rootFilletRad.value
num_teeth = int(_num_teeth_cs.value)
num_rotation_steps = int(_num_rotation_steps.value)
# Create the gear.
# gearComp = drawGear(des, diaPitch, numTeeth, thickness,
# rootFilletRad, pressureAngle, backlash, holeDiam)
abenics = ABENICS(design=des,
module=_module.value,
pressure_angle=pressureAngle,
num_teeth_cs=num_teeth,
gear_ratio=_gear_ratio.value,
thickness=_thickness.value,
hole_diameter=_holeDiam.value,
backlash=_backlash.value)
abenics.print()
### Make SH cutter ###
abenics.make_sh_cutter_comp()
sketches = abenics.sh_cutter_comp.sketches
xyPlane = abenics.sh_cutter_comp.xYConstructionPlane
baseSketch = sketches.add(xyPlane)
# draw gear sketch enlarged by backlash
sk, ax_line = abenics.draw_gear(
baseSketch, backlash=-abenics.backlash)
abenics.revolve_ballgear(abenics.sh_cutter_comp, sk, ax_line)
### MP Gear ###
abenics.make_mp_comp()
sketches = abenics.mp_comp.sketches
xyPlane = abenics.mp_comp.xYConstructionPlane
mp_sketch = sketches.add(xyPlane)
abenics.draw_mp_sketch(mp_sketch)
abenics.extrude_mp(mp_sketch, abenics.thickness_mp)
## Engrave MP-Gear and rotate both gears ###
delta_angle = (2*math.pi) / num_rotation_steps
for i in range(num_rotation_steps):
timelineGroups = des.timeline.timelineGroups
e = abenics.engrave() # engrove mp-gear with cs-cutter
cs, mp = abenics.rotate_gears(delta_angle)
timelineGroup = timelineGroups.add(
e.timelineObject.index, mp.timelineObject.index)
if i == 0:
first_group = timelineGroup
last_group = timelineGroup
# try to group engroving features
# this will be fail
try:
timelineGroups = des.timeline.timelineGroups
timelineGroup = timelineGroups.add(
first_group.index,
last_group.index)
except:
pass
# remove sh_cutter
remove_features = abenics.sh_cutter_comp.features.removeFeatures
# remove = remove_features.add(abenics.sh_cutter_comp) # Invalid Input
remove = remove_features.add(
abenics.sh_cutter_comp.bRepBodies.item(0))
### CS Gear ###
abenics.make_cs_comp()
# Create a new sketch.
sketches = abenics.cs_comp.sketches
xyPlane = abenics.cs_comp.xYConstructionPlane
baseSketch = sketches.add(xyPlane)
sk, ax_line = abenics.draw_gear(baseSketch)
abenics.revolve_ballgear(abenics.cs_comp, sk, ax_line)
# intersect gear
i_sketch = sketches.add(xyPlane)
sk, ax_line = abenics.draw_gear(i_sketch, axis_angle=0.5*math.pi)
# bodies = adsk.core.ObjectCollection.create()
# bodies.add(abenics.cs_comp.bRepBodies.item(0))
rev_feature = abenics.revolve_ballgear(
abenics.cs_comp,
sk, ax_line,
operation=adsk.fusion.FeatureOperations.IntersectFeatureOperation,
bodies=[abenics.cs_comp.bRepBodies.item(0)])
except:
if _ui:
_ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
# Event handler for the inputChanged event.
class GearCommandInputChangedHandler(adsk.core.InputChangedEventHandler):
def __init__(self):
super().__init__()
def notify(self, args):
"""
system call this method when values in input-boxes change.
"""
try:
eventArgs = adsk.core.InputChangedEventArgs.cast(args)
changedInput = eventArgs.input
global _units
if changedInput.id == 'standard':
pass
des = adsk.fusion.Design.cast(_app.activeProduct)
d_cs = _module.value*int(_num_teeth_cs.value)
d_mp = d_cs/(_gear_ratio.value+1.0e-9)
d_mp = round(d_mp, 2)
_pitch_diameter_cs.text = '{:0.2f} mm'.format(d_cs)
_pitch_diameter_mp.text = '{:0.2f} mm'.format(d_mp)
# _pitch_diameter_cs.text = des.unitsManager.formatInternalValue(
# 0.1*d_cs, _units, True)
# _pitch_diameter_mp.text = des.unitsManager.formatInternalValue(
# 0.1*d_mp, _units, True)
if changedInput.id == 'pressureAngle':
if _pressureAngle.selectedItem.name == 'Custom':
_pressureAngleCustom.isVisible = True
else:
_pressureAngleCustom.isVisible = False
except:
if _ui:
_ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
# Event handler for the validateInputs event.
class GearCommandValidateInputsHandler(adsk.core.ValidateInputsEventHandler):
def __init__(self):
super().__init__()
def notify(self, args):
try:
"""system may call this after InputChangedEvent
"""
eventArgs = adsk.core.ValidateInputsEventArgs.cast(args)
_errMessage.text = ''
# Verify that at least 4 teeth are specified.
if not _num_teeth_cs.value.isdigit():
_errMessage.text = 'The number of teeth must be a whole number.'
eventArgs.areInputsValid = False
return
else:
numTeeth = int(_num_teeth_cs.value)
if numTeeth < 4:
_errMessage.text = 'The number of teeth must be 4 or more.'
eventArgs.areInputsValid = False
return
# _pitch_diameter_mp.text : "400 mm"
pd = _pitch_diameter_mp.text.split(' ')
pitch_diameter = float(pd[0])
dedendum = 1.25 * _module.value
dedendum *= 0.1 # mm->cm
rootDia = pitch_diameter - (2 * dedendum)
if _pressureAngle.selectedItem.name == 'Custom':
pressureAngle = _pressureAngleCustom.value
else:
if _pressureAngle.selectedItem.name == '14.5 deg':
pressureAngle = 14.5 * (math.pi/180)
elif _pressureAngle.selectedItem.name == '20 deg':
pressureAngle = 20.0 * (math.pi/180)
elif _pressureAngle.selectedItem.name == '25 deg':
pressureAngle = 25.0 * (math.pi/180)
baseCircleDia = pitch_diameter * math.cos(pressureAngle)
baseCircleCircumference = 2 * math.pi * (baseCircleDia / 2)
des = adsk.fusion.Design.cast(_app.activeProduct)
result = getCommandInputValue(_holeDiam, _units)
if result[0] == False:
eventArgs.areInputsValid = False
return
else:
holeDiam = result[1]
if holeDiam >= (rootDia - 0.01):
_errMessage.text = 'The center hole diameter is too large. It must be less than ' + \
des.unitsManager.formatInternalValue(
rootDia - 0.01, _units, True)
eventArgs.areInputsValid = False
return
toothThickness = baseCircleCircumference / (numTeeth * 2)
if _rootFilletRad.value > toothThickness * .4:
_errMessage.text = 'The root fillet radius is too large. It must be less than ' + \
des.unitsManager.formatInternalValue(
toothThickness * .4, _units, True)
eventArgs.areInputsValid = False
return
except:
if _ui:
_ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
def _isArrayLike(obj):
return hasattr(obj, '__iter__') and hasattr(obj, '__len__')
def get_involutePoints(bd, od, num=15):
# Calculate points along the involute curve.
"""
Args:
bd (float) : base circle diameter
od (float) : outside circle diameter
"""
# involuteIntersectionRadius
# r = 0.5 * bd
points = []
involute_size = 0.5 * (od - bd) # height
for i in range(0, num):
r = (0.5*bd) + ((involute_size / (num - 1)) * i)
p = involutePoint(0.5 * bd, r)
points.append(p)
return points
def xy2polar(points):
"""
convert position in xy-coordinate sys. to r-theta one