@rulecad/cad 0.7.38 → 0.7.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/EXAMPLES.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [The tutorial](TUTORIAL.md) ends with a wall hook checked against its screw. These examples carry on from there, one
4
4
  for each thing the [README](README.md) describes after that: parts, variants and releases, joints and poses, a model
5
- from elsewhere, an optimised part, a board, a mechanism printed flat, gears, and a gearbox. Each is a few files and the commands to run
5
+ from elsewhere, an optimised part, a board, a mechanism printed flat, gears, a gearbox, a motor, and a robot joint. Each is a few files and the commands to run
6
6
  them. The tests write every file here and run every command, so what you read is what works.
7
7
 
8
8
  They start from a workspace `npm create rulecad my-designs` makes, as the tutorial does, and run in order: later
@@ -819,3 +819,425 @@ The check says `the carrier drives the sun and the planets (the ring held): 4 tu
819
819
  carrier, the same way`, and each planet's centre distance and contact ratio. The sweep turns the crank from −180° to
820
820
  180°, the sun four times as far, and looks for anything that touches. Move a planet's anchor off its 120° and the
821
821
  check fails it: it can't mesh with the sun and the ring at once there.
822
+
823
+ ## 10. A motor: the focus slider, driven
824
+
825
+ The same slide, with a 28BYJ-48 geared stepper in place of the knob: 5 V, a few pounds to buy, slow and strong. A motor in an
826
+ assembly is an item with `"motor"`, drawn from `@rulecad/motors`, bought and not printed. Its shaft turns the joint it
827
+ drives, the viewer's slider moves in the motor's steps, and `loads` say what it has to do. Its figures come with their
828
+ kinds: the 28BYJ-48's torque varies between makers, and the check says what its answer rests on.
829
+
830
+ The pinion takes the motor's shaft, two flats and all, with `v.motors.bore`. The motor sits under the plate, shaft up
831
+ through it, so its body needs room below: two feet stand the rail up.
832
+
833
+ ```json projects/home/objects/drive-pinion.json
834
+ {
835
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
836
+ "name": "drive-pinion",
837
+ "title": "Motor pinion",
838
+ "version": "0.1.0",
839
+ "uses": ["x1c"],
840
+ "engine": "manifold",
841
+ "anchors": { "axis": { "at": [0, 0, "0 - gap"], "axis": [0, 0, 1] } },
842
+ "variables": {
843
+ "module": { "value": 1, "unit": "mm", "rule": "As the rack" },
844
+ "teeth": { "value": 14, "rule": "As the knob's pinion" },
845
+ "shift": { "value": 0.2, "rule": "14 teeth need at least 0.19" },
846
+ "width": { "value": "x1c.layer * 30", "unit": "mm", "rule": "The rack's width" },
847
+ "gap": { "value": "x1c.layer + 0.1", "unit": "mm", "rule": "Clear of the plate" },
848
+ "tip": { "value": 5.1, "unit": "mm", "rule": "Where the shaft's tip is from the pinion's underside: 10 mm of shaft less the 4.6 mm plate and the gap" }
849
+ }
850
+ }
851
+ ```
852
+
853
+ ```js projects/home/objects/drive-pinion.js
854
+ // A pinion with the motor's shaft in it: the flats of the bore run only as far as the shaft's flats do.
855
+ export function main (v) {
856
+ const motor = v.motors.motorModel('28byj48')
857
+ return v.ops.subtract(v.gears.spur({ module: v.module, teeth: v.teeth, shift: v.shift, width: v.width }), v.motors.bore(motor, { depth: v.width, tip: v.tip }, v.ops))
858
+ }
859
+ ```
860
+
861
+ ```json projects/home/objects/drive-rail.json
862
+ {
863
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
864
+ "name": "drive-rail",
865
+ "title": "Motor rail",
866
+ "version": "0.1.0",
867
+ "uses": ["x1c"],
868
+ "engine": "manifold",
869
+ "anchors": {
870
+ "axle": { "at": [0, "centre", "thick"], "axis": [0, 0, 1] },
871
+ "track": { "at": ["start", 0, "thick"], "axis": [1, 0, 0] }
872
+ },
873
+ "variables": {
874
+ "centre": { "value": 7.2, "unit": "mm", "rule": "The pinion's axis above the rack's pitch line: m z / 2 + x m" },
875
+ "length": { "value": 120, "unit": "mm", "rule": "The rack and its travel" },
876
+ "start": { "value": -37.7, "unit": "mm", "rule": "The rack's middle under the pinion at rest" },
877
+ "thick": { "value": "x1c.layer * 23", "unit": "mm", "rule": "23 layers: the motor's boss pocket, and enough for its M3 screws" },
878
+ "y0": { "value": -14.5, "unit": "mm", "rule": "Past the motor's near ear" },
879
+ "y1": { "value": 29, "unit": "mm", "rule": "Past its far ear, 17.5 mm off the axis" },
880
+ "plate": { "value": 26, "unit": "mm", "rule": "Wide enough round the motor's boss and its ears" },
881
+ "guide_y": { "value": "0 - 5.45 - x1c.line / 2", "unit": "mm", "rule": "Behind the rack's back, half a line clear" },
882
+ "guide": { "value": "x1c.line * 4", "unit": "mm", "rule": "The guide wall: four lines" },
883
+ "guide_height": { "value": "x1c.layer * 20", "unit": "mm", "rule": "Most of the rack's width" },
884
+ "hole": { "value": 3.5, "unit": "mm", "rule": "M3 clearance, for the feet" },
885
+ "foot_x": { "value": 52, "unit": "mm", "rule": "Each foot's screw, from the middle" },
886
+ "foot_y": { "value": -11, "unit": "mm", "rule": "On the strip, behind the guide" }
887
+ }
888
+ }
889
+ ```
890
+
891
+ ```js projects/home/objects/drive-rail.js
892
+ // The rail: a strip under the rack, a plate for the motor (turned 90° on its shaft, so its ears clear the rack), a wall
893
+ // behind the rack, and the motor's own cuts.
894
+ import jscad from '@jscad/modeling'
895
+ const { cuboid, cylinder } = jscad.primitives
896
+ const { translate, rotateZ } = jscad.transforms
897
+
898
+ export function main (v) {
899
+ const motor = v.motors.motorModel('28byj48')
900
+ const strip = cuboid({ size: [v.length, 12, v.thick], center: [0, v.y0 + 6, v.thick / 2] })
901
+ const seat = cuboid({ size: [v.plate, v.y1 - v.y0, v.thick], center: [8, (v.y0 + v.y1) / 2, v.thick / 2] })
902
+ const guide = cuboid({ size: [v.length, v.guide, v.guide_height], center: [0, v.guide_y - v.guide / 2, v.thick + v.guide_height / 2] })
903
+ const cuts = translate([0, v.centre, 0], rotateZ(Math.PI / 2, v.motors.mount(motor, { plate: v.thick, screw: 'M3' }, v.ops)))
904
+ const screws = [1, -1].map((s) => cylinder({ radius: v.hole / 2, height: v.thick + 2, center: [s * v.foot_x, v.foot_y, v.thick / 2] }))
905
+ return v.ops.subtract(v.ops.union(strip, seat, guide), cuts, screws)
906
+ }
907
+ ```
908
+
909
+ ```json projects/home/objects/drive-foot.json
910
+ {
911
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
912
+ "name": "drive-foot",
913
+ "title": "Rail foot",
914
+ "version": "0.1.0",
915
+ "uses": ["x1c"],
916
+ "variables": {
917
+ "height": { "value": 21, "unit": "mm", "rule": "Under the motor: its 19 mm can and 2 mm to the table" },
918
+ "size": { "value": 12, "unit": "mm", "rule": "As wide as the strip" },
919
+ "long": { "value": 28, "unit": "mm", "rule": "Across the strip's end, for a stance that doesn't rock" },
920
+ "hole": { "value": 2.9, "unit": "mm", "rule": "M3 screw, self-tapped into the plastic" },
921
+ "depth": { "value": 12, "unit": "mm", "rule": "Plenty for an M3 × 16" }
922
+ }
923
+ }
924
+ ```
925
+
926
+ ```js projects/home/objects/drive-foot.js
927
+ // A foot: a block under each end of the rail, screwed on from above.
928
+ import jscad from '@jscad/modeling'
929
+ const { cuboid, cylinder } = jscad.primitives
930
+ const { subtract } = jscad.booleans
931
+
932
+ export function main (v) {
933
+ const block = cuboid({ size: [v.size, v.long, v.height], center: [0, 0, v.height / 2] })
934
+ return subtract(block, cylinder({ radius: v.hole / 2, height: v.depth, center: [0, 0, v.height - v.depth / 2] }))
935
+ }
936
+ ```
937
+
938
+ The assembly says the motor drives the pinion's joint, the slide follows by its `mesh`, and the load is a force on the
939
+ slide: a 200 g camera on a rail with the friction of plastic on plastic, about 1 N. The `shaft` fit reads the bore from
940
+ the pinion as drawn. `duty` says the motor runs a fifth of the time, since a focus stack is mostly standing still.
941
+
942
+ ```json projects/home/assemblies/driven.json
943
+ {
944
+ "title": "Motorised focus slider",
945
+ "kind": "fit",
946
+ "items": [
947
+ { "id": "rail", "object": "drive-rail" },
948
+ { "id": "foot_a", "object": "drive-foot", "at": ["0 - rail.foot_x", "rail.foot_y", "0 - foot_a.height"] },
949
+ { "id": "foot_b", "object": "drive-foot", "at": ["rail.foot_x", "rail.foot_y", "0 - foot_b.height"] },
950
+ { "id": "drive", "motor": { "model": "28byj48", "drives": "pinion", "duty": 0.2, "screw": "M3" }, "at": [0, "rail.centre", 0], "rotate": [0, 0, 90] },
951
+ { "id": "gear", "object": "drive-pinion" },
952
+ { "id": "rack", "object": "rack" }
953
+ ],
954
+ "joints": [
955
+ { "id": "pinion", "type": "revolute", "parent": "rail.axle", "child": "gear.axis", "label": "Motor" },
956
+ { "id": "slide", "type": "prismatic", "parent": "rail.track", "child": "rack.slide", "min": -100, "max": 100,
957
+ "mesh": { "with": "pinion", "module": "gear.module", "teeth": ["gear.teeth", "rack.teeth"], "shift": ["gear.shift", 0] } }
958
+ ],
959
+ "fits": [
960
+ { "a": "foot_a", "b": "rail", "fastens": true, "min": 0, "note": "A foot, screwed on" },
961
+ { "a": "foot_b", "b": "rail", "fastens": true, "min": 0, "note": "A foot, screwed on" },
962
+ { "a": "drive", "b": "rail", "fastens": true, "min": 0, "note": "The motor, on its two ears" },
963
+ { "a": "drive", "b": "gear", "shaft": true, "note": "The motor's shaft in the pinion" }
964
+ ],
965
+ "loads": [{ "joint": "slide", "force": 1, "note": "A 200 g camera sliding, plastic on plastic" }],
966
+ "poses": { "home": { "pinion": 0 } }
967
+ }
968
+ ```
969
+
970
+ ```sh
971
+ npx cad check home/driven
972
+ npx cad check home/driven --sweep --steps 12
973
+ ```
974
+
975
+ The check says which motor it is and how far a step moves (`0.0879° a step`, or 0.0107 mm of slide), that its shaft is
976
+ on the pinion's axis, the force reaching the slide against the 1 N it has to push and how many times over, how fast the
977
+ slide moves, and that the slide holds with the power off: the 28BYJ-48's own gearbox friction, far more than the load can
978
+ turn it back with. The torque's line ends `(rests on community figures: measure it)`, because that's what its torque is.
979
+
980
+ ## 11. A robot joint: a stepper through a compound planetary
981
+
982
+ A shoulder for a small desktop arm: a NEMA 17 turning a 38:1 gearbox on one axis, 500 g at 150 mm on the output. The
983
+ gearbox is a compound planetary: two rings a few teeth apart, one held and one the output, with stepped planets (18 teeth on the
984
+ held ring and the sun, 21 on the output ring). `compoundPlanetary` found the teeth; three planets of 18/21, a sun of 18,
985
+ rings of 54 and 57. The planets are held by the sun and the two rings: there's no carrier to print, and the assembly's
986
+ `carrier` is a speck that's only there to carry the planets' joints. At 38:1 the gearbox is under half efficient, so
987
+ the load can't turn it backwards: the joint holds with the power off.
988
+
989
+ ```json projects/home/objects/joint-housing.json
990
+ {
991
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
992
+ "name": "joint-housing",
993
+ "title": "Joint housing and fixed ring",
994
+ "version": "0.1.0",
995
+ "uses": ["x1c"],
996
+ "engine": "manifold",
997
+ "anchors": { "axis": { "at": [0, 0, "plate"], "axis": [0, 0, 1] } },
998
+ "variables": {
999
+ "plate": { "value": 5, "unit": "mm", "rule": "Enough for M3 screws into a NEMA 17 (1.5 × their size)" },
1000
+ "width": { "value": 8, "unit": "mm", "rule": "The fixed ring's face: strong enough for the motor's whole torque" },
1001
+ "rim": { "value": 62, "unit": "mm", "rule": "Round the 54-tooth ring, three lines and more of wall" },
1002
+ "module": { "value": 1, "unit": "mm", "rule": "The gears'" },
1003
+ "teeth": { "value": 54, "rule": "The held ring" },
1004
+ "post_r": { "value": 37, "unit": "mm", "rule": "Three posts outside the output ring's 33 mm" },
1005
+ "post": { "value": 7, "unit": "mm", "rule": "Each post's diameter" },
1006
+ "post_height": { "value": 19.7, "unit": "mm", "rule": "From the plate to under the clips, just over the output ring" },
1007
+ "pilot": { "value": 2.9, "unit": "mm", "rule": "An M3 screw, self-tapped" },
1008
+ "pilot_depth": { "value": 8, "unit": "mm", "rule": "For an M3 × 10" }
1009
+ }
1010
+ }
1011
+ ```
1012
+
1013
+ ```js projects/home/objects/joint-housing.js
1014
+ // A motor plate with the fixed ring standing on it. The motor bolts underneath, its shaft up through the middle.
1015
+ import jscad from '@jscad/modeling'
1016
+ const { cylinder } = jscad.primitives
1017
+ const { translate } = jscad.transforms
1018
+
1019
+ export function main (v) {
1020
+ const motor = v.motors.motorModel('nema17')
1021
+ const plate = cylinder({ radius: v.rim / 2, height: v.plate, center: [0, 0, v.plate / 2], segments: 96 })
1022
+ const ring = translate([0, 0, v.plate], v.gears.internal({ module: v.module, teeth: v.teeth, width: v.width, rim: v.rim }))
1023
+ const at = (a) => [v.post_r * Math.cos(a), v.post_r * Math.sin(a)]
1024
+ const angles = [Math.PI / 6, (5 * Math.PI) / 6, (3 * Math.PI) / 2]
1025
+ const lobes = angles.map((a) => cylinder({ radius: v.post, height: v.plate, center: [...at(a), v.plate / 2], segments: 32 }))
1026
+ const posts = angles.map((a) => cylinder({ radius: v.post / 2, height: v.post_height + v.plate, center: [...at(a), (v.post_height + v.plate) / 2], segments: 32 }))
1027
+ const arms = angles.map((a) => jscad.transforms.rotateZ(a, jscad.primitives.cuboid({ size: [v.post_r - v.rim / 2 + 2, v.post, v.plate], center: [(v.post_r + v.rim / 2 - 2) / 2, 0, v.plate / 2] })))
1028
+ const pilots = angles.map((a) => cylinder({ radius: v.pilot / 2, height: v.pilot_depth, center: [...at(a), v.plate + v.post_height - v.pilot_depth / 2], segments: 24 }))
1029
+ return v.ops.subtract(v.ops.union(plate, ring, lobes, posts, arms), v.motors.mount(motor, { plate: v.plate, counterbore: true }, v.ops), pilots)
1030
+ }
1031
+ ```
1032
+
1033
+ ```json projects/home/objects/joint-sun.json
1034
+ {
1035
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
1036
+ "name": "joint-sun",
1037
+ "title": "Sun gear on the motor's shaft",
1038
+ "version": "0.1.0",
1039
+ "uses": ["x1c"],
1040
+ "engine": "manifold",
1041
+ "anchors": { "axis": { "at": [0, 0, "0 - gap"], "axis": [0, 0, 1] } },
1042
+ "variables": {
1043
+ "gap": { "value": 0.3, "unit": "mm", "rule": "Clear of the motor plate" },
1044
+ "module": { "value": 1, "unit": "mm", "rule": "The gears'" },
1045
+ "teeth": { "value": 18, "rule": "As the planets' first step" },
1046
+ "width": { "value": 8, "unit": "mm", "rule": "The first stage" },
1047
+ "hub": { "value": 12, "unit": "mm", "rule": "A hub above the teeth, inside the planets' second step" },
1048
+ "tall": { "value": 16, "unit": "mm", "rule": "Up through both stages, so 12 mm of the shaft's flat is gripped" },
1049
+ "tip": { "value": 18.7, "unit": "mm", "rule": "Where the shaft's 24 mm tip is from the sun's underside, 5.3 mm above the mounting face" }
1050
+ }
1051
+ }
1052
+ ```
1053
+
1054
+ ```js projects/home/objects/joint-sun.js
1055
+ // The sun with a hub above it, up through both stages, for grip on the shaft's flat.
1056
+ import jscad from '@jscad/modeling'
1057
+ const { cylinder } = jscad.primitives
1058
+
1059
+ export function main (v) {
1060
+ const motor = v.motors.motorModel('nema17')
1061
+ const gear = v.gears.spur({ module: v.module, teeth: v.teeth, width: v.width })
1062
+ const hub = cylinder({ radius: v.hub / 2, height: v.tall, center: [0, 0, v.tall / 2], segments: 64 })
1063
+ return v.ops.subtract(v.ops.union(gear, hub), v.motors.bore(motor, { depth: v.tall, tip: v.tip }, v.ops))
1064
+ }
1065
+ ```
1066
+
1067
+ ```json projects/home/objects/joint-planet.json
1068
+ {
1069
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
1070
+ "name": "joint-planet",
1071
+ "title": "Stepped planet",
1072
+ "version": "0.1.0",
1073
+ "uses": ["x1c"],
1074
+ "engine": "manifold",
1075
+ "anchors": { "axis": { "at": [0, 0, "0 - gap"], "axis": [0, 0, 1] } },
1076
+ "variables": {
1077
+ "gap": { "value": 0.3, "unit": "mm", "rule": "Clear of the motor plate" },
1078
+ "module": { "value": 1, "unit": "mm", "rule": "The gears'" },
1079
+ "low": { "value": 18, "rule": "On the sun and the held ring" },
1080
+ "high": { "value": 21, "rule": "On the output ring" },
1081
+ "width": { "value": 8, "unit": "mm", "rule": "Each stage" }
1082
+ }
1083
+ }
1084
+ ```
1085
+
1086
+ ```js projects/home/objects/joint-planet.js
1087
+ // A planet in two steps, in one piece, printed with the wider step on the bed.
1088
+ import jscad from '@jscad/modeling'
1089
+ const { translate } = jscad.transforms
1090
+
1091
+ export function main (v) {
1092
+ const low = v.gears.spur({ module: v.module, teeth: v.low, width: v.width })
1093
+ const high = translate([0, 0, v.width], v.gears.spur({ module: v.module, teeth: v.high, width: v.width }))
1094
+ return v.ops.union(low, high)
1095
+ }
1096
+ ```
1097
+
1098
+ ```json projects/home/objects/joint-output.json
1099
+ {
1100
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
1101
+ "name": "joint-output",
1102
+ "title": "Output ring and flange",
1103
+ "version": "0.1.0",
1104
+ "uses": ["x1c"],
1105
+ "engine": "manifold",
1106
+ "anchors": { "axis": { "at": [0, 0, "top + width"], "axis": [0, 0, -1] }, "tip": { "at": [150, 0, "top + width"], "axis": [0, 0, -1] } },
1107
+ "variables": {
1108
+ "top": { "value": 3, "unit": "mm", "rule": "The flange, printed on the bed" },
1109
+ "width": { "value": 8, "unit": "mm", "rule": "The output ring's face" },
1110
+ "rim": { "value": 66, "unit": "mm", "rule": "Round the 57-tooth ring" },
1111
+ "module": { "value": 1, "unit": "mm", "rule": "The gears'" },
1112
+ "teeth": { "value": 57, "rule": "The output ring" },
1113
+ "hole": { "value": 3.5, "unit": "mm", "rule": "M3 clearance, on a 40 mm circle, for the arm" },
1114
+ "middle": { "value": 15, "unit": "mm", "rule": "A hole in the middle for the motor's shaft to come up in" },
1115
+ "bolt": { "value": 20, "unit": "mm", "rule": "Radius of the arm's bolt circle" }
1116
+ }
1117
+ }
1118
+ ```
1119
+
1120
+ ```js projects/home/objects/joint-output.js
1121
+ // The output ring, drawn as it prints: its flange on the bed, the teeth standing on it; it goes on upside down.
1122
+ import jscad from '@jscad/modeling'
1123
+ const { cylinder } = jscad.primitives
1124
+ const { translate } = jscad.transforms
1125
+
1126
+ export function main (v) {
1127
+ const flange = cylinder({ radius: v.rim / 2, height: v.top, center: [0, 0, v.top / 2], segments: 96 })
1128
+ const ring = translate([0, 0, v.top], v.gears.internal({ module: v.module, teeth: v.teeth, width: v.width, rim: v.rim }))
1129
+ const holes = [0, 1, 2, 3].map((k) => cylinder({ radius: v.hole / 2, height: v.top + 1, center: [v.bolt * Math.cos(k * Math.PI / 2), v.bolt * Math.sin(k * Math.PI / 2), v.top / 2], segments: 24 }))
1130
+ const middle = cylinder({ radius: v.middle / 2, height: v.top + 1, center: [0, 0, v.top / 2], segments: 48 })
1131
+ return v.ops.subtract(v.ops.union(flange, ring), holes, middle)
1132
+ }
1133
+ ```
1134
+
1135
+ Three clips on three posts keep the output ring from lifting off. It turns under them with 0.3 mm to spare.
1136
+
1137
+ ```json projects/home/objects/joint-clip.json
1138
+ {
1139
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
1140
+ "name": "joint-clip",
1141
+ "title": "Retaining clip",
1142
+ "version": "0.1.0",
1143
+ "uses": ["x1c"],
1144
+ "variables": {
1145
+ "reach": { "value": 6, "unit": "mm", "rule": "In over the flange's edge, 4 mm" },
1146
+ "back": { "value": 4, "unit": "mm", "rule": "Round the post" },
1147
+ "wide": { "value": 8, "unit": "mm", "rule": "As wide as the post and a little" },
1148
+ "thick": { "value": 3, "unit": "mm", "rule": "Fifteen layers" },
1149
+ "hole": { "value": 3.5, "unit": "mm", "rule": "M3 clearance" }
1150
+ }
1151
+ }
1152
+ ```
1153
+
1154
+ ```js projects/home/objects/joint-clip.js
1155
+ // A flat tab screwed to a post, its nose over the flange.
1156
+ import jscad from '@jscad/modeling'
1157
+ const { cuboid, cylinder } = jscad.primitives
1158
+ const { subtract } = jscad.booleans
1159
+
1160
+ export function main (v) {
1161
+ const tab = cuboid({ size: [v.reach + v.back, v.wide, v.thick], center: [(v.back - v.reach) / 2, 0, v.thick / 2] })
1162
+ return subtract(tab, cylinder({ radius: v.hole / 2, height: v.thick + 1, center: [0, 0, v.thick / 2], segments: 24 }))
1163
+ }
1164
+ ```
1165
+
1166
+ ```json projects/home/objects/joint-speck.json
1167
+ {
1168
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
1169
+ "name": "joint-speck",
1170
+ "title": "Carrier (not printed)",
1171
+ "version": "0.1.0",
1172
+ "role": "reference",
1173
+ "anchors": {
1174
+ "axis": { "at": [0, 0, 0], "axis": [0, 0, 1] },
1175
+ "a": { "at": [18, 0, 0], "axis": [0, 0, 1] },
1176
+ "b": { "at": ["0 - 9", "18 * sind(120)", 0], "axis": [0, 0, 1] },
1177
+ "c": { "at": ["0 - 9", "0 - 18 * sind(120)", 0], "axis": [0, 0, 1] }
1178
+ },
1179
+ "variables": { "r": { "value": 0.2, "unit": "mm", "rule": "A speck, so the planets' joints have something to hang from" } }
1180
+ }
1181
+ ```
1182
+
1183
+ ```js projects/home/objects/joint-speck.js
1184
+ // Nothing is printed here: the planets ride on the sun and the rings. A mark for the planets' joints to be on.
1185
+ import jscad from '@jscad/modeling'
1186
+ const { sphere } = jscad.primitives
1187
+
1188
+ export function main (v) { return sphere({ radius: v.r, center: [0, 0, 60] }) }
1189
+ ```
1190
+
1191
+ The joint's load is a mass on the output. The check finds the worst angle by running the motor through its range.
1192
+
1193
+ ```json projects/home/assemblies/shoulder.json
1194
+ {
1195
+ "title": "Robot shoulder",
1196
+ "kind": "fit",
1197
+ "gravity": [0, -1, 0],
1198
+ "items": [
1199
+ { "id": "housing", "object": "joint-housing" },
1200
+ { "id": "motor", "motor": { "model": "nema17", "drives": "drive", "speed": 300, "duty": 0.3 } },
1201
+ { "id": "sun", "object": "joint-sun" },
1202
+ { "id": "carrier", "object": "joint-speck" },
1203
+ { "id": "p1", "object": "joint-planet" },
1204
+ { "id": "p2", "object": "joint-planet" },
1205
+ { "id": "p3", "object": "joint-planet" },
1206
+ { "id": "output", "object": "joint-output" },
1207
+ { "id": "clip1", "object": "joint-clip", "at": ["37 * cosd(30)", "37 * sind(30)", 24.7], "rotate": [0, 0, 30] },
1208
+ { "id": "clip2", "object": "joint-clip", "at": ["37 * cosd(150)", "37 * sind(150)", 24.7], "rotate": [0, 0, 150] },
1209
+ { "id": "clip3", "object": "joint-clip", "at": [0, -37, 24.7], "rotate": [0, 0, 270] }
1210
+ ],
1211
+ "joints": [
1212
+ { "id": "drive", "type": "revolute", "parent": "housing.axis", "child": "sun.axis", "label": "Motor" },
1213
+ { "id": "turn", "type": "revolute", "parent": "housing.axis", "child": "carrier.axis" },
1214
+ { "id": "s1", "type": "revolute", "parent": "carrier.a", "child": "p1.axis" },
1215
+ { "id": "s2", "type": "revolute", "parent": "carrier.b", "child": "p2.axis" },
1216
+ { "id": "s3", "type": "revolute", "parent": "carrier.c", "child": "p3.axis" },
1217
+ { "id": "out", "type": "revolute", "parent": { "at": [0, 0, 13.4], "axis": [0, 0, 1] }, "child": "output.axis" }
1218
+ ],
1219
+ "planetary": [{ "sun": "sun", "carrier": "carrier", "ring": "housing", "planets": ["p1", "p2", "p3"], "drive": "sun", "module": 1, "teeth": [18, 18, 54], "output": { "ring": "output", "planet": 21, "teeth": 57 } }],
1220
+ "fits": [
1221
+ { "a": "motor", "b": "housing", "fastens": true, "min": 0, "note": "The motor, on its four screws" },
1222
+ { "a": "clip1", "b": "housing", "fastens": true, "min": 0, "note": "A clip, screwed on" },
1223
+ { "a": "clip2", "b": "housing", "fastens": true, "min": 0, "note": "A clip, screwed on" },
1224
+ { "a": "clip3", "b": "housing", "fastens": true, "min": 0, "note": "A clip, screwed on" },
1225
+ { "a": "motor", "b": "sun", "shaft": true, "note": "The motor's shaft in the sun" }
1226
+ ],
1227
+ "loads": [{ "mass": 0.5, "at": "output.tip", "note": "500 g at 150 mm: a forearm" }],
1228
+ "poses": { "home": { "drive": 0 } }
1229
+ }
1230
+ ```
1231
+
1232
+ ```sh
1233
+ npx cad check home/shoulder
1234
+ ```
1235
+
1236
+ The check says the output ring turns 1/38 of the motor's turn, the other way; that 7.44 N m reaches the joint at 300 rpm
1237
+ against the 0.735 N m it needs at its worst, ten times over; that it turns a full turn in 7.6 s at that speed; and
1238
+ that the gears, under 50% efficient, hold it with the power off. `npx cad check home/shoulder --sweep --steps 24` turns the
1239
+ motor all the way round and finds no teeth touching, and neither do the output ring's steps.
1240
+
1241
+ Ten times over is more margin than the job needs, but the gearbox is the size it is for what the motor could do to it, not
1242
+ the arm: stalled against a stop, the 7.44 N m at the output puts 33 MPa on the planets' top teeth (`strength`, the Lewis
1243
+ equation, for teeth 8 mm wide), against PLA's 39. Give that a home switch, or a smaller current.
package/README.md CHANGED
@@ -153,6 +153,7 @@ own copy anywhere and name it in `viewUrl`.
153
153
  `notchHinge`, `bistable`, `livingHinge` as shapes, each with a `<name>Model(shape, { E })` giving its stiffness and the
154
154
  strain at a travel, and `printable(shape, printer, material, model)` for how it prints. Drawn flat: bending along y,
155
155
  width up z, so a flexure bends within its layers.
156
+ - `v.motors`: motors (`@rulecad/motors`): `motorModel`, `mount` and `bore` for the holes a part needs round a motor and its shaft, `performance` for its torque and speed. In an assembly a motor is an item (see Motors).
156
157
  - `v.gears`: gears (`@rulecad/gears`): `spur`, `rack` and `internal` as shapes, from a module and teeth, each with its
157
158
  model (`gearModel`, `rackModel`, `internalModel`) and `printable(model, printer, width)`. Drawn flat: the axis up z,
158
159
  the first tooth on +x, the face on the bed. Two gears in an assembly mesh with a joint's `mesh` (see Joints).
@@ -404,6 +405,19 @@ then y, then z, as `rotate` does.
404
405
  and a quick look for parts pushed into each other when you let a slider go. The quick look can miss parts that cross
405
406
  without a corner going in, so `--sweep` is the real check.
406
407
 
408
+ ### Motors
409
+
410
+ An item can be a motor instead of a printed object: `{ "id": "drive", "motor": { "model": "nema17", "drives": "elbow" }, "at": […], "rotate": […] }`. It comes from `@rulecad/motors`, is bought and not printed (a reference, in the assembly but never on a plate), and its anchors (`shaft`, `tip`, `face`, `horn`, `hole1` …) work in joints like any other. `set` changes a figure (`{ "holding_torque": { "value": 0.5, "kind": "measured", "source": "…" } }`), `speed` is the motor's speed (rpm), `margin` how many times over the torque must be (2 by default), `duty` the share of the time it runs.
411
+
412
+ - `"drives"`: the joint it turns, a revolute. The viewer's slider moves in a stepper's steps; a servo brings its range. Whatever follows that joint through a `mesh` or a `planetary` moves with it. `motor.axis` fails if its shaft isn't on the joint's axis.
413
+ - `"loads"` at the top of the assembly say what it has to do: `{ "joint": "elbow", "torque": 0.5 }` (N m), `{ "joint": "slide", "force": 12 }` (N), or `{ "mass": 0.2, "at": "forearm.tip" }` (kg, a mass carried at an anchor, whose torque at each joint comes from where the pose puts it; the check runs the motor through its range and reports the worst). `"gravity": [0, -1, 0]` says which way is down, if not `-z`.
414
+ - A compound planetary is a `planetary` with `"output": { "ring", "planet", "teeth" }`: a second ring on the planets' second step, following them in phase.
415
+ - `motor.torque`: what reaches the joint through the gears, against the load: a fail under 1 times, a warning under the margin. It says what its figures rest on. `motor.speed`: how fast it moves and how long its range takes. Stages pass on `stageEfficiency` of the power (0.95 a mesh, an estimate).
416
+ - `motor.holds`: with the power on (holding torque, or stall torque) and off (detent torque, a built-in gearbox's friction, a worm that locks, gears under 50% efficient, or `"brake": "a ratchet and pawl"` on the joint). Dropping with the power off is a warning: it may be what you want.
417
+ - `motor.mount`: the part a motor is fastened to (a `fastens` fit), read as drawn: how thick it is at the screw holes against the screws' size, and the screws' bearing on the plastic under the motor's full torque. How far the whole part bends isn't checked yet.
418
+ - `motor.heat`: the motor's case against the softening point of the material the project prints in. Too hot says the current to set the driver to.
419
+ - A `"shaft": true` fit (or `"press"`) between a motor and what it drives reads the bore from the part as drawn: that it's on the shaft (`shaft.seat`), that its flat is there (`shaft.flat`; the shaft turns to meet it, so where the flat faces doesn't matter), how much of the flat it grips (`shaft.grip`), and, pressed on, the hoop stress in the hub (`shaft.hoop`).
420
+
407
421
  ## Optimised parts
408
422
 
409
423
  `cad optimise` finds the stiffest layout of a flat part: where to put a fixed amount of material so the part bends
package/lib/assembly.mjs CHANGED
@@ -30,8 +30,9 @@ import { bounds } from '@rulecad/printcheck';
30
30
  import { closest, closestAt, inside, distanceToFace, overlapAt } from '@rulecad/fit';
31
31
  import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
32
32
  import { DOFS, frame, turn, mul, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
33
- import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase, contact, wormModel, wormMesh, bevelModel, bevelMesh } from '@rulecad/gears';
33
+ import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase, contact, wormModel, wormMesh, bevelModel, bevelMesh, compoundEfficiency } from '@rulecad/gears';
34
34
  import { ops as booleans } from '@rulecad/shapes';
35
+ import { motorBuilt, motorDrives, shaftFits, loadsOf, motorChecks, shaftFit } from './motors.mjs';
35
36
 
36
37
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
37
38
  export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
@@ -94,6 +95,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
94
95
  for (const [k, r] of Object.entries(a.requires || {})) requires.push({ object: k, range: r, from: ref });
95
96
  const built = new Map(); // each object or component is built once per set of values, however many copies are placed
96
97
  const source = async (it, extra) => {
98
+ if (it.motor) { const key = JSON.stringify(['motor', it.id, it.motor]); if (!built.has(key)) built.set(key, motorBuilt(it.motor, num, it.id)); return built.get(key); }
97
99
  // from: inputs worked out from items built before this one ({ "usb_y": "board.pcb.pico_y" }): numbers, in this
98
100
  // assembly's names, so a part can take a value only another part knows once it's built
99
101
  const from = Object.fromEntries(Object.entries(it.from || {}).map(([k, x]) => [k, num(x)]));
@@ -130,7 +132,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
130
132
  let builtCount = 0;
131
133
  for (const it of a.items || []) {
132
134
  if (!/^[a-z][\w-]*$/.test(it.id || '')) throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
133
- if (!it.object === !it.assembly) throw new Error(`item ${it.id}: give either "object" or "assembly"`);
135
+ if ([it.object, it.assembly, it.motor].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly" or "motor"`);
134
136
  // Copies: one, a grid from repeat x/y, or a layout's keys. Each: { id, offset (from at), extra (values to set) }
135
137
  const rx = it.repeat?.x, ry = it.repeat?.y, rl = it.repeat?.layout, copies = [];
136
138
  if (rl) {
@@ -184,6 +186,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
184
186
  for (const c of copies) { placed.push([it, c]); ids.push(c.id); }
185
187
  }
186
188
  const motion = motionOf(a, placed, num, ref);
189
+ fits.push(...shaftFits(motion.drives, motion.joints, placed.map(([, c]) => c.id)).map((x) => ({ ...x, num })));
187
190
  for (const [it, c] of placed) {
188
191
  const src = c.src, id = c.id;
189
192
  if (src.sub) {
@@ -339,7 +342,7 @@ function motionOf(a, placed, num, ref) {
339
342
  joints.push({ id: j.id, type: j.type, parent: p.item, child: c.item, a: p.frame, b: c.frame, dofs,
340
343
  ...(j.label ? { label: j.label } : {}), ...(path ? { path } : {}), ...(j.cone != null ? { cone: num(j.cone) } : {}),
341
344
  ...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}),
342
- ...(j.mesh ? { meshSpec: j.mesh } : {}) });
345
+ ...(j.mesh ? { meshSpec: j.mesh } : {}), ...(j.brake ? { brake: j.brake } : {}) });
343
346
  }
344
347
  for (const j of joints) if (j.follow) {
345
348
  const l = joints.find((x) => x.id === j.follow[0]);
@@ -353,6 +356,7 @@ function motionOf(a, placed, num, ref) {
353
356
  return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
354
357
  });
355
358
  const meshes = [...gearMeshes(joints, items, num), ...planetaries(a.planetary || [], joints, items, num)];
359
+ const drives = motorDrives(a, placed, joints, num), loads = loadsOf(a, anchor, num, joints);
356
360
  const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).filter(([id]) => !id.includes('.')).map(([id, v]) => {
357
361
  if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
358
362
  return [id, Array.isArray(v) ? v.map(num) : num(v)];
@@ -364,7 +368,7 @@ function motionOf(a, placed, num, ref) {
364
368
  const marks = placed.flatMap(([, c], k) => Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
365
369
  try { return { item: k, id: c.id, name, frame: frameOf(spec, evalIn(c.src.b.values, `${c.src.objName} anchor ${name}`)) }; } catch { return null; }
366
370
  })).filter(Boolean);
367
- return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes };
371
+ return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes, drives, loads, gravity: (a.gravity || [0, 0, -1]).map(num) };
368
372
  }
369
373
 
370
374
  // A pair measured from its drawn teeth (@rulecad/gears contact: backlash, transmission error, interference), kept in
@@ -429,15 +433,16 @@ function planetaries(list, joints, items, num) {
429
433
  // the third's rotation for the driver's: from the relation, with the held one still
430
434
  const rot = (d) => { const r = { [held[0]]: 0, [drive]: sg[drive] * d }; r[third] = (sigma0 - coef[drive] * r[drive]) / coef[third]; return r; };
431
435
  // a straight line in the driver's value (f: degrees in, radians out): [ratio, offset in degrees]
432
- const lin = (f) => { const a = f(0), b = f(1); return [(b - a) / DEG, a / DEG]; };
436
+ const lin = (f) => { const a = f(0), b = f(1), o = a / DEG; return [(b - a) / DEG, ((o + 180) % 360 + 360) % 360 - 180]; }; // (the offset a part-turn: a whole turn is the same place)
437
+ const free = (j) => { j.dofs[0] = [-1e6, 1e6, j.dofs[0][2]]; }; // what follows a sun can turn past a turn
433
438
  const [k3, o3] = lin((d) => sg[third] * rot(d * DEG)[third]);
434
- follower.follow = [lead.id, k3, o3];
439
+ follower.follow = [lead.id, k3, o3]; free(follower);
435
440
  const findings = [], f = (level, text, code, between) => findings.push({ level, text, code, ...(between ? { between } : {}) });
436
441
  pl.forEach((p, i) => {
437
442
  // the planet's first tooth from the sun's mesh: π = −(S/P) σ + β (1 + S/P) + π − π/P, β the planet's place
438
443
  const tooth = (d) => { const r = rot(d * DEG), beta = p.beta + r.carrier; return -(S / P) * r.sun + beta * (1 + S / P) + Math.PI - Math.PI / P; };
439
444
  const [kp, op] = lin((d) => p.s * (tooth(d) - p.gamma - rot(d * DEG).carrier));
440
- p.joint.follow = [lead.id, kp, op];
445
+ p.joint.follow = [lead.id, kp, op]; free(p.joint);
441
446
  // and with the ring: in phase with it too, or it can't go there
442
447
  const ringTooth = (P / R) * tooth(0) + p.beta * (1 - P / R) - Math.PI / R, pitch = (2 * Math.PI) / R;
443
448
  const miss = (((ringTooth - gr) % pitch) + pitch * 1.5) % pitch - pitch / 2;
@@ -451,7 +456,25 @@ function planetaries(list, joints, items, num) {
451
456
  }
452
457
  });
453
458
  const ratioText = `the ${drive} drives the ${third}${held[0] === 'carrier' ? '' : ' and the planets'} (the ${held[0]} held): ${Number(Math.abs(k3).toFixed(4))} turns of the ${third} for each turn of the ${drive}, ${k3 * sg[drive] * sg[third] < 0 ? 'opposite ways' : 'the same way'}`;
454
- out.push({ joint: follower.id, with: lead.id, kind: 'planetary', text: ratioText, findings, between: [O, O], planetary: true });
459
+ out.push({ joint: follower.id, with: lead.id, kind: 'planetary', text: ratioText, findings, between: [O, O], planetary: true, members: [follower.id, ...planetJoints.map((j) => j.id)] });
460
+ // A second ring, on the planets' second step: it follows the planets' turning as the first ring would
461
+ if (g.output) {
462
+ const k2 = index(g.output.ring, 'output ring'), j2 = moving(k2), P2 = num(g.output.planet), R2 = num(g.output.teeth), oc = { ...common };
463
+ if (!j2 || j2.type !== 'revolute') throw new Error(`${what}: the output ring ${g.output.ring} turns on a revolute`);
464
+ if (j2.follow || j2.meshSpec) throw new Error(`${what}: ${j2.id} follows the planets here: give it no follow or mesh of its own`);
465
+ if (R2 - P2 !== R - P) throw new Error(`${what}: the output ring and the planets' second step must differ as the first do: ${R2} - ${P2} isn't ${R} - ${P}, so one centre distance can't serve both`);
466
+ let p2, r2;
467
+ try { p2 = gearModel({ ...oc, teeth: P2 }); r2 = internalModel({ ...oc, teeth: R2 }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
468
+ const g2 = ang(flat(col(W(k2), 0), Z), X0, Z), s2 = sign(j2), p0 = pl[0], ps = Math.PI / R2;
469
+ const toothAt = (d) => { const r = rot(d * DEG); return -(S / P) * r.sun + (p0.beta + r.carrier) * (1 + S / P) + Math.PI - Math.PI / P; };
470
+ const ring2 = (d) => { const r = rot(d * DEG); return (P2 / R2) * toothAt(d) + (p0.beta + r.carrier) * (1 - P2 / R2) - ps - g2; };
471
+ const [k, o] = lin((d) => s2 * ring2(d));
472
+ j2.follow = [lead.id, k, o]; free(j2);
473
+ const eff = compoundEfficiency({ planet: P, planet2: P2, ring: R, ring2: R2 }), fails = [], ff = (level, text, code) => fails.push({ level, text, code, between: [O, O] });
474
+ for (const x of meshOf(p2, r2, { centre: pl[0].r }).findings) ff(x.level, `${pl[0].id} and the output ring: ${x.text}`, x.code);
475
+ pl.forEach((p, i) => { const t2 = (P2 / R2) * ((-(S / P) * sigma0 + p.beta * (1 + S / P) + Math.PI - Math.PI / P)) + p.beta * (1 - P2 / R2) - ps, pitch2 = (2 * Math.PI) / R2, miss = (((t2 - (P2 / R2) * ((-(S / P) * sigma0 + p0.beta * (1 + S / P) + Math.PI - Math.PI / P)) - p0.beta * (1 - P2 / R2) + ps) % pitch2) + pitch2 * 1.5) % pitch2 - pitch2 / 2; if (Math.abs(miss) > 1e-6) ff('fail', `planet ${p.id} can't mesh with the output ring where it is: every tooth count a multiple of the planets puts them all in phase`, 'planetary.phase'); });
476
+ out.push({ joint: j2.id, with: lead.id, kind: 'planetary', efficiency: eff, text: `the second ring turns ${Number(Math.abs(k).toFixed(5))} of the ${drive}'s turn, ${k * s2 * sg[drive] < 0 ? 'the other way' : 'the same way'} (${Number((1 / Math.abs(k)).toFixed(2))}:1, about ${Math.round(eff * 100)}% efficient, an estimate)`, findings: fails, between: [O, O], planetary: true });
477
+ }
455
478
  });
456
479
  return out;
457
480
  }
@@ -527,7 +550,7 @@ function wormDrive(j, lead, spec, teeth, common, joints, items, num) {
527
550
  const m = wormMesh({ ...common, starts: teeth[0], ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}), ...(ws.hand ? { hand: ws.hand } : {}) }, { teeth: teeth[1] });
528
551
  const c = meshOf(wheel, rackModel({ ...common, teeth: 4 }), { centre: dist - w.pitch / 2 });
529
552
  const findings = [...m.findings, ...c.findings.filter((x) => x.code === 'mesh.centre').map((x) => ({ ...x, text: x.text.replace("centre to the rack's pitch line", "the wheel's centre to the worm's pitch cylinder") }))];
530
- return { joint: j.id, with: lead.id, kind: 'worm', findings, between: [Ow.map((x, i) => x + U[i] * at), O2], text: `a worm of ${teeth[0]} start${teeth[0] > 1 ? 's' : ''}, ${Number((teeth[1] / teeth[0]).toFixed(3))} turns of the worm for one of the wheel` };
553
+ return { joint: j.id, with: lead.id, kind: 'worm', worm: m, findings, between: [Ow.map((x, i) => x + U[i] * at), O2], text: `a worm of ${teeth[0]} start${teeth[0] > 1 ? 's' : ''}, ${Number((teeth[1] / teeth[0]).toFixed(3))} turns of the worm for one of the wheel` };
531
554
  }
532
555
 
533
556
  // Gears that mesh: "mesh": { "with": <the driving joint>, "module", "teeth": [its, this one's], "shift"?, "ring"? } on
@@ -652,6 +675,9 @@ function saveOverlaps() {
652
675
  }
653
676
 
654
677
  // checkAssembly(built) -> findings, as @rulecad/printcheck: { level, text, card? } (card: a short line for the mirror)
678
+ // What a project prints in, for the motors' heat and press-fit checks
679
+ const materialOf = (project) => { try { return readJson(path.join(paths.project(project), 'project.json')).material; } catch { return null; } };
680
+
655
681
  export function checkAssembly(s) {
656
682
  const out = [], f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }), mm = (n) => `${Number(n.toFixed(3))}`;
657
683
  // Versions: every pin, from this assembly and its components, against every copy of that object
@@ -696,7 +722,9 @@ export function checkAssembly(s) {
696
722
  for (const x of s.fits) {
697
723
  if (x.poses && !x.poses.includes(s.pose)) continue; // a fit for some poses only: the folded screen over the keys
698
724
  if (x.holes) { holesFit(x); continue; }
725
+ if (x.silent) continue; // lets a pair overlap, and has nothing to report
699
726
  if (x.engage != null) { engageFit(x); continue; }
727
+ if (x.shaft != null) { shaftFit(x, s, f, { placeItems, jointValues, mul, materialName: materialOf(s.project) }); continue; }
700
728
  const A = pickIn(x.a, x), key = x.note || `${x.a} / ${x.b}`;
701
729
  const lo = x.min != null ? x.num(x.min) : -Infinity, hi = x.max != null ? x.num(x.max) : Infinity;
702
730
  const reach = Math.max(2, ...[lo, hi].filter(Number.isFinite)) + 1; // look past the range, so a gap near it is measured
@@ -806,6 +834,7 @@ export function checkAssembly(s) {
806
834
  }
807
835
  }
808
836
  }
837
+ motorChecks(s, f, { placeItems, jointValues, mul }, materialOf(s.project));
809
838
  // Plates print everything: no references
810
839
  if (s.a.kind === 'plate') {
811
840
  const refs = s.objects.filter((o) => o.role === 'reference' && !o.unplaced); // an unplaced item only lends its numbers
@@ -898,8 +927,8 @@ export function motionData(s) {
898
927
  }));
899
928
  return { motion: {
900
929
  items: mo.items.map(([n, ...m]) => [n, ...m.map(r)]),
901
- joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone }) => ({ id, type, parent, child, a: a.map(r), b: b.map(r), dofs: dofs.map((d) => d.map(r)),
902
- ...(label ? { label } : {}), ...(follow ? { follow } : {}), ...(path ? { path: path.map((p) => p.map(r)) } : {}), ...(cone != null ? { cone } : {}) })),
930
+ joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone, step }) => ({ id, type, parent, child, a: a.map(r), b: b.map(r), dofs: dofs.map((d) => d.map(r)),
931
+ ...(label ? { label } : {}), ...(follow ? { follow } : {}), ...(path ? { path: path.map((p) => p.map(r)) } : {}), ...(cone != null ? { cone } : {}), ...(step ? { step } : {}) })),
903
932
  poses: mo.poses, ...(s.pose ? { pose: s.pose } : {}),
904
933
  part: s.parts.map((p) => names.indexOf(p.item)),
905
934
  ...(allow.length ? { allow } : {}),
package/lib/design.mjs CHANGED
@@ -33,6 +33,7 @@ import { optimised, forDesign } from './optimise.mjs';
33
33
  import * as shapes from '@rulecad/shapes';
34
34
  import * as flexures from '@rulecad/flexures';
35
35
  import * as gears from '@rulecad/gears';
36
+ import * as motors from '@rulecad/motors';
36
37
  import { engineId, packageVersion, materialise } from './versions.mjs';
37
38
  import { satisfies } from '@rulecad/versions';
38
39
 
@@ -126,11 +127,11 @@ const CACHE = paths.cache('builds'), CACHE_VERSION = 3;
126
127
  const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
127
128
  // What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
128
129
  // boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
129
- const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears')));
130
+ const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))), motorsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/motors')));
130
131
  // (every module of a helper package but its tests: they change nothing a design builds)
131
132
  const helperSources = (dir) => fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs').sort().map((f) => source(pathToFileURL(path.join(dir, f)).href)).join('');
132
133
  const feaDir = path.dirname(createRequire(pathToFileURL(path.join(flexuresDir, 'package.json')).href).resolve('@rulecad/fea')); // (flexures' own, wherever npm put it)
133
- const own = source(import.meta.url) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling'); // every shapes module, not just its entry
134
+ const own = source(import.meta.url) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(motorsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling'); // every shapes module, not just its entry
134
135
  // A lamina's slow stages (the physics, the flood's probe) are kept apart from the builds, keyed by the library's code
135
136
  // and their own inputs, so a build that changes only what comes after them (a strap, a check, a rule's words) has them
136
137
  // at once: .cache/stages/. A design in the sandbox can't write them, so the sandbox hands them back and the tool writes them
@@ -220,7 +221,7 @@ export async function build(d, set = {}, { mirror = false } = {}) {
220
221
  throw syntaxAt(located(e, d.js, 'design.run'), d);
221
222
  });
222
223
  if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
223
- const w = watch(values, { shapes, flexures, gears, ops: await shapes.ops(booleans(object)), ...(pcb ? { pcb } : {}) }, optional);
224
+ const w = watch(values, { shapes, flexures, gears, motors, ops: await shapes.ops(booleans(object)), ...(pcb ? { pcb } : {}) }, optional);
224
225
  read = w.read;
225
226
  let made;
226
227
  try { ({ shapes: made, mechanism } = unpack(await mod.main(w.v))); } catch (e) { throw Object.assign(located(e, d.js, 'design.run'), { line: lineOf(e, pathToFileURL(d.js).href) || undefined }); }
package/lib/motors.mjs ADDED
@@ -0,0 +1,265 @@
1
+ // Motors in assemblies: an item with "motor" is drawn from @rulecad/motors, its shaft turns a joint (the assembly's
2
+ // slider is the motor turning), and the assembly can say what it has to do: "loads" on joints or masses on links.
3
+ // From those, what reaches each loaded joint through the meshes and planetaries, whether the joint holds with the
4
+ // power on and off, and whether the shaft and its mount are fit for it.
5
+ import crypto from 'node:crypto';
6
+ import { createRequire } from 'node:module';
7
+ import { motorModel, motorParts, mountModel, performance } from '@rulecad/motors';
8
+ import { stageEfficiency } from '@rulecad/gears';
9
+ import { named } from './parts.mjs';
10
+
11
+ const require = createRequire(import.meta.url);
12
+ const n3 = (x, d = 3) => String(Number(x.toFixed(d)));
13
+ const G = 9.80665; // m/s²
14
+
15
+ // A motor item, built: its parts (body and shaft), anchors from its model, its figures as values and rules
16
+ export function motorBuilt(spec, num, id) {
17
+ const what = `item ${id}: motor`;
18
+ if (!spec || typeof spec !== 'object' || !spec.model) throw new Error(`${what}: give { "model": "nema17", "drives": "<joint>" }`);
19
+ const set = Object.fromEntries(Object.entries(spec.set || {}).map(([k, v]) => { if (typeof v !== 'string') return [k, v]; try { return [k, num(v)]; } catch { return [k, v]; } }));
20
+ const model = motorModel(spec.model, set), { body, shaft } = motorParts(model);
21
+ const parts = named(shaft ? { body, shaft } : { body }, { body: { label: `${model.name} body` }, ...(shaft ? { shaft: { label: `${model.name} shaft` } } : {}) });
22
+ const anchors = Object.fromEntries(Object.entries(model.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis }]));
23
+ const values = Object.fromEntries(Object.entries(model.figures).filter(([, f]) => typeof f.value === 'number').map(([k, f]) => [k, f.value]));
24
+ const entries = Object.entries(model.figures).map(([k, f]) => ({ name: `${model.name}.${k}`, value: f.value, unit: f.unit, rule: f.rule, kind: f.kind, source: f.source, checked: f.checked, set: model.name }));
25
+ const hash = crypto.createHash('sha256').update(JSON.stringify(model.figures)).digest('hex').slice(0, 16);
26
+ const b = { object: { name: model.name, title: model.name, role: 'reference', version: '0.0.0', anchors }, values, entries, deps: [], units: {}, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash };
27
+ return { key: `motor:${id}:${hash}`, objName: `motor:${model.name}`, b, version: '0.0.0', role: 'reference', motor: model, spec };
28
+ }
29
+
30
+ // Which joint each motor drives, checked by name; a servo's range and a stepper's step go on the joint. The shaft
31
+ // turns in what it drives, so that pair may overlap: the body is still checked against everything.
32
+ export function motorDrives(a, placed, joints, num) {
33
+ const drives = [], taken = new Map();
34
+ placed.forEach(([it, c], k) => {
35
+ if (!it.motor) return;
36
+ const what = `item ${c.id}: motor`, id = it.motor.drives;
37
+ if (id == null) { drives.push({ item: k, id: c.id, model: c.src.motor, spec: it.motor, joint: null }); return; } // on the bench, turning nothing
38
+ const j = joints.find((x) => x.id === id);
39
+ if (!j) throw new Error(`${what}: drives "${id}", which isn't a joint (${joints.map((x) => x.id).join(', ') || 'none'})`);
40
+ if (j.type !== 'revolute') throw new Error(`${what}: a motor turns a revolute (${j.id} is a ${j.type}): drive the gear, and let the slide follow it`);
41
+ if (j.follow) throw new Error(`${what}: ${j.id} follows ${j.follow[0]}: a motor drives the joint that leads the train`);
42
+ if (taken.has(id)) throw new Error(`${what}: ${id} is driven by ${taken.get(id)} already: one motor to a joint`);
43
+ taken.set(id, c.id);
44
+ const model = c.src.motor, spec = (a.joints || []).find((x) => x.id === id);
45
+ if (model.range != null) {
46
+ const half = model.range / 2, d = j.dofs[0];
47
+ if (spec.min == null && spec.max == null) { d[0] = -half; d[1] = half; d[2] = Math.min(half, Math.max(-half, d[2])); }
48
+ else if (d[0] < -half - 1e-9 || d[1] > half + 1e-9) throw new Error(`${what}: a ${model.name} turns ${model.range}°, and ${j.id} asks for ${d[0]}° to ${d[1]}°`);
49
+ }
50
+ if (model.stepAngle) j.step = model.stepAngle;
51
+ drives.push({ item: k, id: c.id, model, spec: it.motor, joint: id });
52
+ });
53
+ return drives;
54
+ }
55
+
56
+ // The fits a motor brings with it, in the assembly's own shape
57
+ export const shaftFits = (drives, joints, ids) => drives.filter((d) => d.joint && d.model.shaft.length).map((d) => ({ a: `${d.id}.shaft`, b: ids[joints.find((j) => j.id === d.joint).child], min: -1000, silent: true }));
58
+
59
+ // "loads": [{ "joint": "elbow", "torque": 0.5 }, { "joint": "slide", "force": 12 }, { "mass": 0.2, "at": "forearm.tip" }]
60
+ export function loadsOf(a, anchor, num, joints) {
61
+ return (a.loads || []).map((l, i) => {
62
+ const what = `load ${i + 1}`;
63
+ if (l.mass != null) { if (l.at == null) throw new Error(`${what}: a mass needs "at", an anchor on what carries it`); const m = num(l.mass); if (!(m > 0)) throw new Error(`${what}: mass is above 0 kg (got ${m})`); return { mass: m, ...anchor(l.at, what), note: l.note }; }
64
+ const j = joints.find((x) => x.id === l.joint);
65
+ if (!j) throw new Error(`${what}: give a "mass" and "at", or a "joint" with its "torque" or "force" (joints: ${joints.map((x) => x.id).join(', ')})`);
66
+ if (j.type === 'prismatic' ? l.force == null : l.torque == null) throw new Error(`${what}: ${j.id} is a ${j.type}, so give its ${j.type === 'prismatic' ? 'force (N)' : 'torque (N m)'}`);
67
+ return { joint: j.id, value: num(j.type === 'prismatic' ? l.force : l.torque), note: l.note };
68
+ });
69
+ }
70
+
71
+ // ---------- the train from a motor to a joint ----------
72
+ // Walks up the follow links from a joint to the one that leads it: the turns of that lead per turn of this joint
73
+ // (or per mm, where the joint slides), the share of power that gets through, what's in the way.
74
+ function trainFrom(motion, id) {
75
+ const stages = [], meshes = motion.meshes || [];
76
+ let j = motion.joints.find((x) => x.id === id), ratio = 1, efficiency = 1, slide = j.type === 'prismatic' ? 1 : null, locks = null;
77
+ while (j.follow) {
78
+ const [lead, r] = j.follow, m = meshes.find((x) => x.joint === j.id) || meshes.find((x) => x.planetary && (x.members || []).includes(j.id));
79
+ const kind = m?.kind === 'external' ? 'spur' : m?.kind || 'spur';
80
+ const eff = m?.efficiency ?? stageEfficiency(kind, kind === 'worm' ? { worm: m.worm } : {});
81
+ efficiency *= eff; stages.push({ joint: j.id, kind, ratio: r, efficiency: eff });
82
+ if (kind === 'worm' && m.worm.locks) locks = `the worm (its ${n3(m.worm.leadAngle, 1)}° lead is under the friction angle)`;
83
+ if (slide != null && stages.length === 1) slide = Math.abs(r); // mm of slide for each degree of the gear
84
+ else ratio *= 1 / Math.abs(r);
85
+ j = motion.joints.find((x) => x.id === lead);
86
+ }
87
+ return { root: j.id, ratio, efficiency, stages, slide, locks };
88
+ }
89
+
90
+ // World axis of a joint and the world position of a point on an item
91
+ const rowsAt = (W, p) => [0, 1, 2].map((k) => W[4 * k] * p[0] + W[4 * k + 1] * p[1] + W[4 * k + 2] * p[2] + W[4 * k + 3]);
92
+ const axisOf = (motion, worlds, j, mul) => { const P = j.parent < 0 ? j.a : mul(worlds[j.parent], j.a); return { O: [P[3], P[7], P[11]], Z: [P[2], P[6], P[10]] }; };
93
+ const sub = (a, b) => a.map((x, i) => x - b[i]), dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
94
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
95
+
96
+ // The load at one joint, at one set of joint values (N m on a revolute, N on a slide), from every mass carried beyond it
97
+ function loadAt(motion, loads, worlds, j, mul) {
98
+ const { O, Z } = axisOf(motion, worlds, j, mul), byChild = new Map(motion.joints.map((x) => [x.child, x]));
99
+ const beyond = (k) => { for (let i = k, n = 0; i >= 0 && n < 99; n++) { const x = byChild.get(i); if (!x) return false; if (x === j) return true; i = x.parent; } return false; };
100
+ let total = 0;
101
+ for (const l of loads) {
102
+ if (l.joint === j.id) total += l.value;
103
+ else if (l.mass != null && beyond(l.item)) {
104
+ const X = rowsAt(worlds[l.item], [l.frame[3], l.frame[7], l.frame[11]]), g = motion.gravity || [0, 0, -1], F = g.map((c) => (c * l.mass * G) / Math.hypot(...g));
105
+ total += j.type === 'prismatic' ? dot(Z, F) : dot(Z, cross(sub(X, O), F)) / 1000;
106
+ }
107
+ }
108
+ return total;
109
+ }
110
+
111
+ // The worst load on a joint: at each named pose, and with the motor run through its range
112
+ function worstLoad(motion, loads, j, drive, { placeItems, jointValues, mul }) {
113
+ let worst = 0, where = null;
114
+ const look = (values, label) => { const t = loadAt(motion, loads, placeItems(motion, values), j, mul); if (Math.abs(t) > Math.abs(worst)) { worst = t; where = label; } };
115
+ const poses = Object.keys(motion.poses || {});
116
+ for (const p of poses.length ? poses : [null]) look(jointValues(motion, p ?? undefined), p);
117
+ const root = drive && motion.joints.find((x) => x.id === drive.joint);
118
+ if (root) {
119
+ const base = jointValues(motion, motion.pose ?? undefined), [lo, hi] = root.dofs[0];
120
+ for (let k = 0; k <= 24; k++) { const a = lo + ((hi - lo) * k) / 24, set = Object.fromEntries(Object.entries(base).filter(([id]) => !motion.joints.find((x) => x.id === id)?.follow)); look(jointValues(motion, { ...set, [root.id]: [a] }), `${root.id} at ${n3(a, 1)}°`); }
121
+ }
122
+ return { torque: Math.abs(worst), where };
123
+ }
124
+
125
+ // A motor's speed if the assembly doesn't say: its corner speed, its rated speed, or half its free speed
126
+ function workingSpeed(model, spec) {
127
+ if (spec.speed != null) return spec.speed;
128
+ const p = performance(model, {});
129
+ return model.type === 'dc' ? p.limit / 2 : model.figures.pull_in_torque ? p.limit : model.type === 'servo' ? p.limit : model.type === 'brushless' ? p.limit / 4 : p.limit / 5;
130
+ }
131
+
132
+ const material = (name) => { const n = String(name || 'pla').toLowerCase().split(/\s/)[0]; try { return { name: n, ...Object.fromEntries(Object.entries(require(`@rulecad/rules/${n}.json`).rules).map(([k, r]) => [k, r.value])) }; } catch { return null; } };
133
+
134
+ // The findings: f(level, text, card, extra), as the assembly's check makes them
135
+ export function motorChecks(s, f, helpers, materialName) {
136
+ const motion = s.motion, drives = motion?.drives || [], loads = motion?.loads || [], { placeItems, jointValues, mul } = helpers;
137
+ if (!drives.length) { if (loads.length) f('warn', `there are loads, but no motor: nothing has been checked against them (add a "motor" item that "drives" a joint)`, null, { code: 'motor.loads' }); return; }
138
+ const worlds = placeItems(motion, jointValues(motion, motion.pose ?? undefined));
139
+ for (const d of drives) {
140
+ const m = d.model, grams = n3(m.mass * 1000, 1), K = d.spec.margin != null ? d.spec.margin : 2, W = worlds[d.item];
141
+ f('info', `${d.id}: ${m.name}, ${grams} g${d.joint ? `, drives ${d.joint}` : ''}${m.stepAngle ? `, ${n3(m.stepAngle, 4)}° a step` : ''}${m.range ? `, ${m.range}° of travel` : ''}`, null, { code: 'motor.model', refs: { item: d.id, joint: d.joint }, values: { model: m.name, grams: m.mass * 1000, stepAngle: m.stepAngle } });
142
+ if (!d.joint) continue;
143
+ // Its shaft on the joint's axis
144
+ const j = motion.joints.find((x) => x.id === d.joint), { O, Z } = axisOf(motion, worlds, j, mul), S = rowsAt(W, m.anchors.shaft.origin), A = [W[2], W[6], W[10]];
145
+ const off = cross(sub(S, O), Z), apart = Math.hypot(...off), tilt = Math.abs(1 - Math.abs(dot(A, Z)));
146
+ if (apart > 0.05 || tilt > 1e-6) { f('fail', `${d.id}'s shaft isn't on ${d.joint}'s axis: ${n3(apart, 2)} mm off${tilt > 1e-6 ? ', and not parallel to it' : ''}`, `${d.id}: shaft off axis`, { code: 'motor.axis', at: S, refs: { item: d.id, joint: d.joint } }); continue; }
147
+ f('pass', `${d.id}'s shaft is on ${d.joint}'s axis`, null, { code: 'motor.axis', at: S });
148
+ // Everything it drives that carries a load
149
+ const driven = motion.joints.filter((x) => trainFrom(motion, x.id).root === d.joint).map((x) => ({ j: x, t: trainFrom(motion, x.id), load: worstLoad(motion, loads, x, d, helpers) })).filter((x) => x.load.torque > 0);
150
+ const motorSpeed = workingSpeed(m, d.spec), loaded = driven.length ? driven : [];
151
+ if (!loaded.length) {
152
+ const here = performance(m, { speed: motorSpeed });
153
+ f('info', `${d.id} gives ${n3(here.motor.torque)} N m at ${n3(motorSpeed, 1)} rpm; no loads on what it drives, so nothing to check that against (add "loads")`, null, { code: 'motor.torque' });
154
+ continue;
155
+ }
156
+ // Reflected to the motor's own shaft: what each load needs of it, and what it would take to hold against it
157
+ let need = 0, back = 0, backOn = 0;
158
+ const lines = [], at = (x) => axisOf(motion, worlds, x, mul).O;
159
+ let locked = null;
160
+ for (const { j: x, t, load } of loaded) {
161
+ // the lead's torque for a load here: a slide's force through the pinion, a revolute's torque down the ratio
162
+ const atLead = t.slide != null ? (load.torque * t.slide * 180) / Math.PI / 1000 : load.torque;
163
+ const unit = t.slide != null ? 'N' : 'N m', reduction = t.ratio;
164
+ const η = t.efficiency, needed = atLead / (reduction * η);
165
+ need += needed; const ηback = Math.max(0, 2 - 1 / η);
166
+ if (t.locks) locked = t.locks;
167
+ else if (η <= 0.5) locked = `the gears (${n3(η * 100, 0)}% forwards, under the 50% where they can't be driven backwards)`;
168
+ back += (atLead / reduction) * ηback; backOn += atLead / reduction;
169
+ lines.push({ x, t, load, unit, reduction, atLead, η });
170
+ }
171
+ const speedOut = motorSpeed / loaded[0].t.ratio, rated = performance(m, { speed: motorSpeed }), avail = rated.motor.torque, margin = need ? avail / need : Infinity;
172
+ const main = lines[0], what = main.unit === 'N m' ? `${n3(main.load.torque)} N m` : `${n3(main.load.torque, 2)} N`, gives = main.unit === 'N m' ? `${n3(avail * main.reduction * main.η)} N m` : `${n3((avail * main.reduction * main.η * Math.PI * 1000) / (main.t.slide * 180), 1)} N`;
173
+ const trust = rated.rests.filter((k) => k !== 'spec' && k !== 'measured'), caveat = trust.length ? ` (rests on ${trust.join(' and ')} figures: measure it)` : '';
174
+ const level = margin < 1 ? 'fail' : margin < K ? 'warn' : 'pass', fix = margin < 1 && main.t.slide == null ? ` A ratio of ${n3((main.reduction * K) / margin, 1)}:1 would give it ${K} times` : '';
175
+ f(level, `${d.id} into ${main.x.id}${lines.length > 1 ? ` and ${lines.length - 1} more` : ''}: ${gives} there against ${what} needed${main.load.where ? ` (worst: ${main.load.where})` : ''}, ${n3(margin, 2)} times over${caveat}.${fix}`, level === 'pass' ? null : `${d.id}: ${n3(margin, 2)}× torque`, { code: 'motor.torque', at: at(main.x), refs: { item: d.id, joint: main.x.id }, values: { available: avail * main.reduction * main.η, needed: main.load.torque, margin } });
176
+ if (d.spec.speed != null && performance(m, { speed: motorSpeed }).findings.some((x) => x.code === 'motor.speed')) f('fail', `${d.id} is asked for ${motorSpeed} rpm, past what a ${m.name} does`, `${d.id}: too fast`, { code: 'motor.speed', refs: { item: d.id } });
177
+ else {
178
+ const slideRate = main.x.type === 'prismatic' ? (speedOut * 360 * main.t.slide) / 60 : null, span = slideRate ? main.x.dofs[0][1] - main.x.dofs[0][0] : 0, time = slideRate ? span / slideRate : 60 / speedOut; // along a slide's travel, or a turn
179
+ f('info', `${main.x.id} moves at ${slideRate ? `${n3(slideRate, 2)} mm/s` : `${n3(speedOut, 2)} rpm`} with ${d.id} at ${n3(motorSpeed, 1)} rpm: ${slideRate ? 'its whole range' : 'a turn'} in ${n3(time, 1)} s`, null, { code: 'motor.speed', at: at(main.x), values: { rpm: speedOut, time } });
180
+ }
181
+ mountCheck(s, d, f, W, avail, materialName);
182
+ // Does it hold?
183
+ const fig = (k) => m.figures[k]?.value, kt = m.type === 'brushless' ? 60 / (2 * Math.PI * fig('kv')) : 0;
184
+ const on = fig('holding_torque') ?? fig('stall_torque') ?? (kt ? kt * fig('rated_current') : 0), off_ = fig('detent_torque') ?? fig('friction_torque') ?? null, brake = lines.map((l) => motion.joints.find((x) => x.id === l.x.id)?.brake).find(Boolean) ?? motion.joints.find((x) => x.id === d.joint)?.brake;
185
+ const backS = n3(back), pmargin = backOn ? on / backOn : Infinity;
186
+ if (locked || brake) f('pass', `${main.x.id} holds with the power off: ${brake ? `its brake (${brake})` : locked} is what holds it`, null, { code: 'motor.holds', at: at(main.x) });
187
+ else if (off_ != null && back <= off_) f('pass', `${main.x.id} holds with the power off: ${backS} N m back at the motor against ${n3(off_)} N m of ${fig('detent_torque') != null ? 'detent' : 'gearbox friction'}`, null, { code: 'motor.holds', at: at(main.x) });
188
+ else if (off_ != null) f('warn', `${main.x.id} drops with the power off: ${backS} N m back at the motor against ${n3(off_)} N m of ${fig('detent_torque') != null ? 'detent' : 'gearbox friction'}. A worm, a ratchet, or more ratio`, `${main.x.id}: drops unpowered`, { code: 'motor.holds', at: at(main.x), values: { back, holds: off_ } });
189
+ else f('warn', `${main.x.id}: there's no figure for what holds it with the power off (${m.name} gives none): assume it can be turned back, and measure it`, `${main.x.id}: unpowered unknown`, { code: 'motor.holds', at: at(main.x) });
190
+ if (pmargin < 1) f('fail', `${main.x.id} slips with the power on: ${n3(backOn)} N m back at the motor against ${n3(on)} N m of ${fig('holding_torque') != null ? 'holding' : 'stall'} torque`, `${main.x.id}: slips`, { code: 'motor.holds', at: at(main.x), values: { back: backOn, holds: on } });
191
+ else f('pass', `${main.x.id} holds with the power on, ${n3(pmargin, 1)} times over`, null, { code: 'motor.holds', at: at(main.x), values: { margin: pmargin } });
192
+ // The case, against what it's bolted to
193
+ const mat = material(materialName), rise = fig('temperature_rise');
194
+ if (mat?.softening != null && rise != null) {
195
+ const duty = d.spec.duty != null ? d.spec.duty : 1, room = 25, caseT = room + rise * duty, ok = caseT <= mat.softening, name = mat.name.toUpperCase(), I = fig('rated_current');
196
+ if (ok) f('pass', `${d.id}'s case reaches at most ${n3(caseT, 1)} °C ${duty < 1 ? `at ${n3(duty * 100, 0)}% duty` : 'at rated current'}, under ${name}'s ${mat.softening} °C`, null, { code: 'motor.heat', at: S });
197
+ else { const k = Math.sqrt((mat.softening - room) / (rise * duty)); f('warn', `${d.id}'s case can reach ${n3(caseT, 1)} °C at rated current, past where ${name} softens (${mat.softening} °C). Set the driver to ${I ? `${n3(I * k, 2)} A` : `${n3(k * 100, 0)}% of its current`} (${n3(k * 100, 0)}% of the torque), or print the mount in a material that takes it`, `${d.id}: mount will soften`, { code: 'motor.heat', at: S, values: { case: caseT, softening: mat.softening } }); }
198
+ }
199
+ }
200
+ }
201
+
202
+ // The part a motor is fastened to, under the motor's full torque as a reaction at its screws: how thick it is at the
203
+ // holes (read from the part as drawn), and the screws' bearing on the plastic. Not yet: how far the whole part bends.
204
+ function mountCheck(s, d, f, W, avail, materialName) {
205
+ const m = d.model, top = (n) => String(n).split(/[.@]/)[0], fit = s.fits.find((x) => x.fastens && [top(x.a), top(x.b)].includes(d.id));
206
+ if (!fit || !m.mount.holes.length) return;
207
+ const other = top(fit.a) === d.id ? top(fit.b) : top(fit.a), parts = s.parts.filter((p) => p.item === other || p.leaf === other);
208
+ if (!parts.length) return;
209
+ const inv = (p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
210
+ const pts = parts.flatMap((p) => p.triangles.flat().map(inv)), side = m.mount.side, nominal = mountModel(m, { plate: 10 }), hd = nominal.holes[0].diameter;
211
+ let t = Infinity, plate = 0; // the shortest wall a hole has, and the plate round it (more, if the screw's head is sunk)
212
+ for (const [hx, hy] of m.mount.holes) for (const p of pts) { const r = Math.hypot(p[0] - hx, p[1] - hy), z = p[2] * side; if (r < hd / 2 + 2 && z > 0.5) { t = Math.min(t, z); plate = Math.max(plate, z); } }
213
+ if (t === Infinity) return f('warn', `${d.id}: couldn't find the plate at its screw holes in ${other}`, `${d.id}: mount not found`, { code: 'motor.mount' });
214
+ const here = mountModel(m, { plate: +plate.toFixed(2), ...(d.spec.screw ? { screw: d.spec.screw } : {}) }), mat = material(materialName) || material('pla'), radius = Math.max(...m.mount.holes.map(([x, y]) => Math.hypot(x, y))), each = avail / (m.mount.holes.length * radius / 1000), bearing = each / (hd * t), margin = mat.strength / bearing;
215
+ for (const x of here.findings) f(x.level, `${d.id} on ${other}: ${x.text}`, x.level === 'pass' ? null : `${d.id}: ${x.code.split('.')[1]}`, { code: 'motor.mount' });
216
+ f(margin < 2 ? 'fail' : 'pass', `${d.id} on ${other}: ${n3(plate, 2)} mm of plate at the screws, each taking ${n3(each, 1)} N against the torque (bearing ${n3(bearing, 1)} MPa, ${n3(margin, 0)} times under ${mat.name.toUpperCase()}'s ${mat.strength} MPa)`, margin < 2 ? `${d.id}: screws pull through` : null, { code: 'motor.mount', values: { plate, bearing, margin } });
217
+ }
218
+
219
+ // A "shaft" fit: a motor's shaft in the bore of a part. Reads the bore from the part as drawn: a slice across the
220
+ // shaft at the grip, a ray out from the axis every few degrees, the wall inside and outside.
221
+ export function shaftFit(x, s, f, { placeItems, jointValues, mul, materialName, holeComp = 0.1 }) {
222
+ // (a printed hole comes out holeComp smaller across, so a drawn bore is that much tighter on the real shaft)
223
+ const motion = s.motion, top = (n) => String(n).split(/[.@]/)[0], drives = motion?.drives || [], d = drives.find((y) => y.id === top(x.a) || y.id === top(x.b)), other = d && (top(x.a) === d.id ? top(x.b) : top(x.a)), label = x.note || `${d?.id ?? x.a}'s shaft in ${other ?? x.b}`;
224
+ if (!d) return f('fail', `${label}: neither ${x.a} nor ${x.b} is a motor`, null, { code: 'shaft.motor' });
225
+ const worlds = placeItems(motion, jointValues(motion, motion.pose ?? undefined)), W = worlds[d.item], m = d.model, S = m.shaft, r = S.diameter / 2;
226
+ const inv = (p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
227
+ const parts = s.parts.filter((p) => p.item === other || p.leaf === other);
228
+ if (!parts.length) return f('fail', `${label}: no part "${other}"`, null, { code: 'shaft.part' });
229
+ const tris = parts.flatMap((p) => p.triangles).map((t) => t.map(inv));
230
+ // How far along the shaft the part reaches, near the axis
231
+ let lo = Infinity, hi = -Infinity; for (const t of tris) for (const p of t) if (Math.hypot(p[0], p[1]) < r + 6) { lo = Math.min(lo, p[2]); hi = Math.max(hi, p[2]); }
232
+ const from = Math.max(lo, S.base), to = Math.min(hi, S.tip), on = to - from;
233
+ if (!(on > 0.05)) return f('fail', `${label}: the part isn't on the shaft (it reaches ${n3(lo, 2)} to ${n3(hi, 2)} mm along it; the shaft runs ${n3(S.base, 2)} to ${n3(S.tip, 2)})`, `${label}: not on the shaft`, { code: 'shaft.seat' });
234
+ const flatFrom = S.flats ? S.tip - S.flatLength : S.tip, flatOn = Math.max(0, to - Math.max(from, flatFrom)), z = S.flats && flatOn > 0.2 ? (Math.max(from, flatFrom) + to) / 2 : (from + to) / 2;
235
+ // The slice at z, as segments
236
+ const segs = [];
237
+ for (const t of tris) { const c = []; for (let i = 0; i < 3; i++) { const a = t[i], b = t[(i + 1) % 3]; if ((a[2] - z) * (b[2] - z) < 0) { const u = (z - a[2]) / (b[2] - a[2]); c.push([a[0] + u * (b[0] - a[0]), a[1] + u * (b[1] - a[1])]); } } if (c.length === 2) segs.push(c); }
238
+ // Each ray: the nearest wall out from the axis, and the part's outside beyond it
239
+ const hits = (ang) => { const dx = Math.cos(ang), dy = Math.sin(ang), out = []; for (const [p, q] of segs) { const ex = q[0] - p[0], ey = q[1] - p[1], den = dx * ey - dy * ex; if (Math.abs(den) < 1e-12) continue; const t = (p[0] * ey - p[1] * ex) / den, u = (p[0] * dy - p[1] * dx) / den; if (t > 1e-6 && u >= 0 && u <= 1) out.push(t); } return out.sort((a, b) => a - b); };
240
+ // The shaft's section at an angle, its flat turned to psi: the shaft turns to meet the bore as it goes on, so the flat is
241
+ // read from the bore. Rays at every 5°; the best angle is the one that leaves the most room at the closest point.
242
+ const flatY = S.flats === 2 ? S.across / 2 : S.across - r;
243
+ const section = (ang, psi) => { const a = Math.sin(ang - psi); if (S.flats === 2) return Math.min(r, flatY / Math.abs(a || 1e-9)); if (S.flats === 1 && a > 0) return Math.min(r, flatY / a); return r; };
244
+ const N = 72, inner = [];
245
+ let minWall = Infinity;
246
+ for (let k = 0; k < N; k++) { const ang = (2 * Math.PI * k) / N, h = hits(ang); if (!h.length) return f('fail', `${label}: at ${n3(z, 1)} mm along the shaft, the part doesn't go round it`, `${label}: no bore`, { code: 'shaft.bore' }); inner.push([ang, h[0]]); if (h.length > 1) minWall = Math.min(minWall, h[1] - h[0]); }
247
+ const gapAt = (psi) => Math.min(...inner.map(([a, h]) => h - section(a, psi)));
248
+ let gap = S.flats ? -Infinity : gapAt(0);
249
+ if (S.flats) for (let k = 0; k < N; k++) gap = Math.max(gap, gapAt((2 * Math.PI * k) / N));
250
+ const code = (c) => ({ code: c, refs: { item: d.id, part: other } }), press = x.shaft === 'press' || gap < 0;
251
+ if (S.flats) {
252
+ const radial = inner.map(([, h]) => h);
253
+ if (Math.max(...radial) - Math.min(...radial) < 0.2) return f('fail', `${label}: the bore is round and the shaft has a flat: nothing turns the part but friction. Cut the flat in the bore (bore() in @rulecad/motors), or add a grub screw`, `${label}: round bore`, { ...code('shaft.flat') });
254
+ }
255
+ if (gap > 0.5) f('fail', `${label}: the bore is ${n3(gap, 2)} mm clear of the shaft at its closest: too slack to hold`, `${label}: slack`, code('shaft.bore'));
256
+ if (gap < -0.2) f('fail', `${label}: the bore is ${n3(-gap, 2)} mm tighter than the shaft: it won't go on`, `${label}: too tight`, code('shaft.bore'));
257
+ const grip = S.flats ? Math.min(flatOn, on) : on, want = S.flats ? Math.min(1.5 * S.diameter, 0.8 * S.flatLength) : 1.5 * S.diameter;
258
+ if (grip < want) f('warn', `${label}: only ${n3(grip, 1)} mm of ${S.flats ? 'the flat' : 'the shaft'} is in the bore: ${n3(want, 1)} mm or more, or it rocks and rounds out`, `${label}: short grip`, code('shaft.grip'));
259
+ else f('pass', `${label}: ${n3(grip, 1)} mm of ${S.flats ? 'the flat' : 'the shaft'} in the bore, ${n3(gap, 2)} mm of play at the closest`, null, code('shaft.grip'));
260
+ if (press && minWall < Infinity) {
261
+ const a = r, u = Math.max(0, holeComp / 2 - gap), b = a + minWall, Kf = (b * b + a * a) / (b * b - a * a), mat = material(materialName) || material('pla'), E = mat.modulus, nu = mat.poisson ?? 0.36, sigma = (E * (u / a) * Kf) / (Kf + nu), limit = mat.strength;
262
+ if (sigma > limit) f('fail', `${label}: pressing it on stretches a ${n3(minWall, 2)} mm wall to ${n3(sigma, 1)} MPa, past ${mat.name.toUpperCase()}'s ${limit} MPa: it splits. A thicker hub or a slide fit`, `${label}: hub splits`, { ...code('shaft.hoop'), values: { stress: sigma, strength: limit } });
263
+ else f('pass', `${label}: pressing it on stretches the wall to ${n3(sigma, 1)} MPa (${mat.name.toUpperCase()} takes ${limit} MPa)`, null, { ...code('shaft.hoop') });
264
+ }
265
+ }
@@ -1,11 +1,11 @@
1
- // The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears and files of
1
+ // The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears, @rulecad/motors and files of
2
2
  // its own project, nothing else (no node: modules: no files, network or processes). The tool's own modules are free.
3
3
  import { builtinModules } from 'node:module';
4
4
 
5
5
  let project = '';
6
6
  export async function initialize(data) { project = data?.project || ''; }
7
7
 
8
- const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears'];
8
+ const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors'];
9
9
  const deny = (spec, why) => Object.assign(new Error(`designs can't import "${spec}": ${why}`), { code: 'design.sandbox' });
10
10
 
11
11
  // The same check, for in-thread hooks (synchronous) and worker hooks (async)
@@ -5,6 +5,7 @@ import path from 'node:path';
5
5
  import * as shapes from '@rulecad/shapes';
6
6
  import * as flexures from '@rulecad/flexures';
7
7
  import * as gears from '@rulecad/gears';
8
+ import * as motors from '@rulecad/motors';
8
9
  import { named, faces, unpack, watch } from './parts.mjs';
9
10
  import { lineOf } from './errors.mjs';
10
11
 
@@ -28,7 +29,7 @@ console.log = console.info = console.debug = (...a) => console.error(...a);
28
29
  try {
29
30
  const mod = await import(js);
30
31
  if (typeof mod.main !== 'function') throw Object.assign(new Error('the design has no exported main(v)'), { code: 'design.main' });
31
- const { v, read } = watch(values, { shapes, flexures, gears, ops: await shapes.ops(engine || 'jscad') }, optional);
32
+ const { v, read } = watch(values, { shapes, flexures, gears, motors, ops: await shapes.ops(engine || 'jscad') }, optional);
32
33
  const { shapes: made, mechanism } = unpack(await mod.main(v));
33
34
  const parts = named(made, meta).map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) }));
34
35
  done({ parts, read: [...read], ...(mechanism ? { mechanism } : {}), ...(Object.keys(kept).length ? { stages: kept } : {}) });
package/lib/sandbox.mjs CHANGED
@@ -40,7 +40,7 @@ function readable() {
40
40
  // Every node_modules above the workspace and the tool (package lookups read their links), and where links lead
41
41
  const up = (dir) => { const out = []; for (let d = dir; ; d = path.dirname(d)) { out.push(path.join(d, 'node_modules')); if (path.dirname(d) === d) return out; } };
42
42
  const dirs = [WS, TOOL, ...[...up(WS), ...up(TOOL)].filter((d) => fs.existsSync(d)),
43
- ...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
43
+ ...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors', '@rulecad/rules/x1c.json', '@rulecad/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
44
44
  return [...new Set(dirs.filter(Boolean).flatMap((d) => [d, real(d)]).filter(Boolean))];
45
45
  }
46
46
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.38",
3
+ "version": "0.7.40",
4
4
  "description": "The cad command: JSCAD designs from traceable rules, checked for printing and fit, versioned by what fits, shared as links and exported as Bambu 3MF.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -70,7 +70,8 @@
70
70
  "@rulecad/fea": "^0.2.1",
71
71
  "@rulecad/topopt": "^0.3.0",
72
72
  "@rulecad/flexures": "^0.5.0",
73
- "@rulecad/gears": "^0.3.0"
73
+ "@rulecad/gears": "^0.3.2",
74
+ "@rulecad/motors": "^0.1.2"
74
75
  },
75
76
  "peerDependencies": {
76
77
  "@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0 || ^0.4.0 || ^0.5.0"
@@ -19,6 +19,8 @@
19
19
  "joints": { "type": "array", "items": { "$ref": "#/$defs/joint" } },
20
20
  "loops": { "type": "array", "items": { "$ref": "#/$defs/loop" } },
21
21
  "planetary": { "type": "array", "items": { "$ref": "#/$defs/planetary" } },
22
+ "gravity": { "$ref": "#/$defs/vec3", "description": "Which way down is, for masses in loads (default [0, 0, -1])" },
23
+ "loads": { "type": "array", "description": "What the assembly has to do: a torque (N m) or force (N) on a joint, or a mass (kg) carried at an anchor", "items": { "type": "object", "additionalProperties": false, "properties": { "joint": { "type": "string" }, "torque": { "$ref": "#/$defs/expr" }, "force": { "$ref": "#/$defs/expr" }, "mass": { "$ref": "#/$defs/expr" }, "at": { "$ref": "#/$defs/anchorRef" }, "note": { "type": "string" } } } },
22
24
  "poses": { "type": "object", "description": "Named sets of joint values ({ \"hinge\": 90 }), and of items' variables (\"action.travel\": 25: a flexure drawn bent in that pose, printed as drawn)", "additionalProperties": { "type": "object", "additionalProperties": { "$ref": "#/$defs/values" } } },
23
25
  "pose": { "type": "string" }
24
26
  },
@@ -35,6 +37,7 @@
35
37
  "id": { "type": "string" },
36
38
  "object": { "type": "string" },
37
39
  "assembly": { "type": "string" },
40
+ "motor": { "type": "object", "required": ["model"], "additionalProperties": false, "description": "A motor from @rulecad/motors: bought, not printed; its shaft turns the joint it drives", "properties": { "model": { "type": "string" }, "drives": { "type": "string" }, "set": { "type": "object", "description": "Figures that differ from the catalogue's, by name" }, "speed": { "$ref": "#/$defs/expr", "description": "The motor's speed, rpm (default: what it does comfortably)" }, "margin": { "$ref": "#/$defs/expr", "description": "How many times over the torque must be (default 2)" }, "duty": { "$ref": "#/$defs/expr", "description": "The share of the time it runs, 0 to 1 (default 1), for its heat" }, "screw": { "type": "string", "description": "The screws through a motor's plain holes, if not the size they take: M3" } } },
38
41
  "variant": { "type": "string" },
39
42
  "set": { "type": "object" },
40
43
  "at": { "$ref": "#/$defs/vec3" },
@@ -66,6 +69,7 @@
66
69
  "b": { "$ref": "#/$defs/names" },
67
70
  "engage": { "$ref": "#/$defs/expr", "description": "a goes at least this far (mm) onto b along the joint between them: a part slid onto a shaft or a pin, not resting on its end" },
68
71
  "radius": { "$ref": "#/$defs/expr", "description": "With engage: how near the joint's axis to look (mm, default 10)" },
72
+ "shaft": { "anyOf": [{ "type": "boolean" }, { "enum": ["slide", "press"] }], "description": "a or b is a motor, and the other takes its shaft: reads the bore from the part as drawn" },
69
73
  "fastens": { "type": "boolean", "description": "a and b are fastened together (pins, screws, a press): what holds a part that has no joint" },
70
74
  "min": { "$ref": "#/$defs/expr" },
71
75
  "max": { "$ref": "#/$defs/expr" },
@@ -100,6 +104,7 @@
100
104
  "min": { "$ref": "#/$defs/values" },
101
105
  "max": { "$ref": "#/$defs/values" },
102
106
  "value": { "$ref": "#/$defs/values" },
107
+ "brake": { "type": "string", "description": "What holds this joint with the power off (a ratchet, a detent): counted by motor.holds" },
103
108
  "follow": { "type": "string" },
104
109
  "ratio": { "$ref": "#/$defs/expr" },
105
110
  "offset": { "$ref": "#/$defs/values" },
@@ -130,6 +135,7 @@
130
135
  "required": ["sun", "carrier", "ring", "planets", "module", "teeth"],
131
136
  "additionalProperties": false,
132
137
  "properties": {
138
+ "output": { "type": "object", "required": ["ring", "planet", "teeth"], "additionalProperties": false, "description": "A compound planetary: a second ring, on the planets' second step", "properties": { "ring": { "type": "string" }, "planet": { "$ref": "#/$defs/expr" }, "teeth": { "$ref": "#/$defs/expr" } } },
133
139
  "sun": { "type": "string" }, "carrier": { "type": "string" }, "ring": { "type": "string" },
134
140
  "planets": { "type": "array", "minItems": 1, "items": { "type": "string" } },
135
141
  "drive": { "enum": ["sun", "carrier", "ring"] },