@rulecad/cad 0.7.34 → 0.7.36

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, and gears. Each is a few files and the commands to run
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
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
@@ -460,30 +460,47 @@ export function main (v) {
460
460
  "title": "Slide base",
461
461
  "version": "0.1.0",
462
462
  "uses": ["x1c"],
463
+ "engine": "manifold",
463
464
  "anchors": {
464
465
  "axle": { "at": [0, "centre", "thick"], "axis": [0, 0, 1] },
465
466
  "track": { "at": ["start", 0, "thick"], "axis": [1, 0, 0] }
466
467
  },
467
468
  "variables": {
468
469
  "centre": { "value": 7.2, "unit": "mm", "rule": "The pinion's axle above the rack's pitch line: its pitch radius and its shift, m z / 2 + x m" },
469
- "length": { "value": 140, "unit": "mm", "rule": "Room for the rack's whole travel" },
470
+ "length": { "value": 120, "unit": "mm", "rule": "The rack (75.4 mm) and its travel, ±22 mm" },
470
471
  "start": { "value": -37.7, "unit": "mm", "rule": "The rack's middle under the knob at rest: half its 24 teeth, 12 × π" },
471
- "wide": { "value": 40, "unit": "mm", "rule": "Under the rack and the knob" },
472
- "thick": { "value": "x1c.layer * 15", "unit": "mm", "rule": "Fifteen layers" }
472
+ "strip": { "value": 12, "unit": "mm", "rule": "The strip under the rack, from behind its guide to under its teeth" },
473
+ "boss": { "value": 12, "unit": "mm", "rule": "Round the axle's foot" },
474
+ "foot": { "value": 40, "unit": "mm", "rule": "A foot across the middle, so it stands without rocking" },
475
+ "thick": { "value": "x1c.layer * 15", "unit": "mm", "rule": "Fifteen layers" },
476
+ "pin": { "value": "3.2 - x1c.line / 2", "unit": "mm", "rule": "The axle: the pinion's 3.2 mm bore less half a line, so it turns" },
477
+ "pin_height": { "value": "x1c.layer * 60", "unit": "mm", "rule": "Up through the pinion and its knob" },
478
+ "guide_y": { "value": "0 - 5.45 - x1c.line / 2", "unit": "mm", "rule": "Behind the rack's back (1.25 + 4.2 mm under its pitch line), half a line clear" },
479
+ "guide": { "value": "x1c.line * 4", "unit": "mm", "rule": "The guide wall: four lines" },
480
+ "guide_height": { "value": "x1c.layer * 20", "unit": "mm", "rule": "Most of the rack's width" }
473
481
  }
474
482
  }
475
483
  ```
476
484
 
477
485
  ```js projects/home/objects/rail.js
478
- // The base: a plate under the rack's travel and the knob, the axle above the rack.
486
+ // The base as little as holds it: a strip under the rack's travel with a wall behind the rack (so it slides straight
487
+ // and can't back away from the pinion), a boss carrying the pinion's axle, and a foot across the middle.
479
488
  import jscad from '@jscad/modeling'
489
+ const { cuboid, cylinder } = jscad.primitives
480
490
 
481
491
  export function main (v) {
482
- return jscad.primitives.cuboid({ size: [v.length, v.wide, v.thick], center: [0, v.wide / 4, v.thick / 2] })
492
+ const y0 = v.guide_y - v.guide, strip = cuboid({ size: [v.length, v.strip, v.thick], center: [0, y0 + v.strip / 2, v.thick / 2] })
493
+ const boss = cylinder({ radius: v.boss / 2, height: v.thick, center: [0, v.centre, v.thick / 2] })
494
+ const neck = cuboid({ size: [v.boss, v.centre - y0, v.thick], center: [0, (y0 + v.centre) / 2, v.thick / 2] })
495
+ const foot = cuboid({ size: [v.boss, v.foot, v.thick], center: [0, y0 + v.foot / 2 - v.boss, v.thick / 2] })
496
+ const axle = cylinder({ radius: v.pin / 2, height: v.pin_height, center: [0, v.centre, v.thick + v.pin_height / 2] })
497
+ 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] })
498
+ return v.ops.union(strip, boss, neck, foot, axle, guide)
483
499
  }
484
500
  ```
485
501
 
486
- The assembly: the knob turns on the base's axle, and the rack slides along its track, its middle under the knob at
502
+ The assembly: the knob turns on the base's axle (a pin printed with the base), and the rack slides along its track
503
+ against a guide wall, its middle under the knob at
487
504
  rest, so half a turn either way (±22 mm) keeps the pinion on its teeth. The slide's joint doesn't say
488
505
  how far it moves for a turn of the knob: its `mesh` says which joint drives it, and the gears' module and teeth (read
489
506
  from the parts, so they can't disagree). The check works out the travel a turn and the phase that puts a tooth in a
@@ -513,9 +530,290 @@ npx cad check home/slider --sweep --steps 12
513
530
  ```
514
531
 
515
532
  The check says `knob drives slide: 43.98 mm of rack a turn`, the contact ratio, and that the axle is where the gears
516
- need it (`centre distance 7.2 mm, as they need`). Set the base's `centre` to 7 and it fails: the teeth would jam. The
533
+ need it (`centre distance 7.2 mm, as they need`). Set the base's `centre` to 6.9 and it fails: 0.3 mm closer is more than the
534
+ teeth's 0.15 mm of backlash allows, and they would jam. The
517
535
  sweep turns the knob from −180° to 180° with the rack following, and names any teeth that touch on the way. The link
518
536
  carries the knob as a slider, with the rack moving with it: `npx cad link home/slider --md`.
519
537
 
520
538
  To see the gears' geometry, `@rulecad/gears/diagram` draws a pair the way a textbook does: pitch and base circles,
521
539
  the line of action and the path of contact.
540
+
541
+ ## 9. A gearbox: a spool winder through a planetary
542
+
543
+ A crank that winds a spool four times for each turn: a planetary gearbox, the crank on the carrier, the spool on the
544
+ sun, the ring held in the case. `planetary()` in `@rulecad/gears` finds the teeth for the ratio and checks that they
545
+ put together:
546
+
547
+ ```js
548
+ planetary({ module: 1, ratio: 0.25, planets: 3, held: 'ring', input: 'carrier', output: 'sun' })
549
+ // 0.25 : 1 (carrier to sun, ring held), as asked: sun 18, planets 18 × 3, ring 54
550
+ ```
551
+
552
+ The ring is the sun and two planets across (18 + 2 × 18 = 54), and the planets go in evenly: 18 + 54 = 72 is a whole
553
+ number of threes. The parts: a case with the ring on it and a pin for the sun, the sun with the spool's shaft, three
554
+ planets, the carrier with the planets' pins and the crank arm, and the crank's handle.
555
+
556
+ ```json projects/home/objects/winder-case.json
557
+ {
558
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
559
+ "name": "winder-case",
560
+ "title": "Winder case",
561
+ "version": "0.1.0",
562
+ "uses": ["x1c"],
563
+ "engine": "manifold",
564
+ "variables": {
565
+ "radius": { "value": 33, "unit": "mm", "rule": "The ring's rim: the case is a rim under it" },
566
+ "rim": { "value": "x1c.line * 14", "unit": "mm", "rule": "The rim under the ring's, wide enough for its push pins" },
567
+ "snap": { "value": 2, "unit": "mm", "rule": "Two push pins hold the ring still: their shafts" },
568
+ "snap_lip": { "value": 0.3, "unit": "mm", "rule": "The barb's lip, clicking over the floor of the ring's counterbore" },
569
+ "snap_back": { "value": 90, "unit": "deg", "rule": "A square back: it holds for good" },
570
+ "snap_at": { "value": 30.6, "unit": "mm", "rule": "Halfway across the ring's rim, between its roots and its outside" },
571
+ "snap_length": { "value": 4, "unit": "mm", "rule": "Up the ring's 6 mm rim to its 2 mm counterbore" },
572
+ "flange": { "value": 2, "unit": "mm", "rule": "A push pin's foot flange, buried in the rim" },
573
+ "hub": { "value": 12, "unit": "mm", "rule": "Round the sun's axle" },
574
+ "spoke": { "value": "x1c.line * 12", "unit": "mm", "rule": "Three spokes from the hub to the rim" },
575
+ "spokes": { "value": 3, "rule": "Three: it stands without rocking" },
576
+ "t": { "value": "x1c.layer * 15", "unit": "mm", "rule": "Base, fifteen layers" },
577
+ "pin": { "value": 3, "unit": "mm", "rule": "The sun's axle" },
578
+ "pin_height": { "value": 22, "unit": "mm", "rule": "Up through the sun and its shaft" }
579
+ }
580
+ }
581
+ ```
582
+
583
+ ```js projects/home/objects/winder-case.js
584
+ // The case as little as holds it: a rim the ring sits on (two push pins hold it still), a hub with the sun's axle
585
+ // standing in it, and spokes between.
586
+ import jscad from '@jscad/modeling'
587
+ const { cylinder, cuboid } = jscad.primitives
588
+ const { rotateZ } = jscad.transforms
589
+
590
+ export function main (v) {
591
+ const rim = v.ops.subtract(cylinder({ radius: v.radius, height: v.t, center: [0, 0, v.t / 2] }), cylinder({ radius: v.radius - v.rim, height: v.t, center: [0, 0, v.t / 2] }))
592
+ const spokes = Array.from({ length: v.spokes }, (_, k) => rotateZ((2 * Math.PI * k) / v.spokes, cuboid({ size: [v.radius - v.rim / 2, v.spoke, v.t], center: [(v.radius - v.rim / 2) / 2, 0, v.t / 2] })))
593
+ const snaps = [0, Math.PI].map((a) => jscad.transforms.translate([v.snap_at * Math.cos(a), v.snap_at * Math.sin(a), v.t - v.flange], v.flexures.snapPin({ diameter: v.snap, length: v.snap_length, lip: v.snap_lip, back: v.snap_back }, v.ops)))
594
+ return v.ops.union(rim, cylinder({ radius: v.hub / 2, height: v.t, center: [0, 0, v.t / 2] }), ...spokes, ...snaps,
595
+ cylinder({ radius: v.pin / 2, height: v.pin_height, center: [0, 0, v.t + v.pin_height / 2] }))
596
+ }
597
+ ```
598
+
599
+ ```json projects/home/objects/winder-ring.json
600
+ {
601
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
602
+ "name": "winder-ring",
603
+ "title": "Winder ring gear",
604
+ "version": "0.1.0",
605
+ "uses": ["x1c"],
606
+ "engine": "manifold",
607
+ "variables": {
608
+ "rim": { "value": 66, "unit": "mm", "rule": "Across the outside: a rim wide enough for the push pins' holes" },
609
+ "snap": { "value": 2, "unit": "mm", "rule": "The case's push pins" },
610
+ "clear": { "value": "x1c.line / 2", "unit": "mm", "rule": "Half a line round a pin" },
611
+ "snap_at": { "value": 30.6, "unit": "mm", "rule": "As the case's pins" },
612
+ "counterbore": { "value": 2, "unit": "mm", "rule": "Deep enough that a barb clicks below the ring's top, clear of the crank arm" },
613
+ "barb": { "value": 1.6, "unit": "mm", "rule": "The counterbore's radius: the barb and its clearance" },
614
+ "module": { "value": 1, "unit": "mm", "rule": "3.6 lines across a tooth on the X1C" },
615
+ "teeth": { "value": 54, "rule": "The sun and two planets across: 18 + 2 × 18" },
616
+ "width": { "value": "x1c.layer * 30", "unit": "mm", "rule": "Face width, thirty layers: plenty for a spool's pull" }
617
+ }
618
+ }
619
+ ```
620
+
621
+ ```js projects/home/objects/winder-ring.js
622
+ // The ring gear, held to the case by two push pins: through-holes in its rim, counterbored at the top for the barbs.
623
+ import jscad from '@jscad/modeling'
624
+ const { cylinder } = jscad.primitives
625
+
626
+ export function main (v) {
627
+ const holes = [0, Math.PI].flatMap((a) => {
628
+ const x = v.snap_at * Math.cos(a), y = v.snap_at * Math.sin(a)
629
+ return [cylinder({ radius: v.snap / 2 + v.clear, height: v.width, center: [x, y, v.width / 2] }),
630
+ cylinder({ radius: v.barb, height: v.counterbore, center: [x, y, v.width - v.counterbore / 2] })]
631
+ })
632
+ return v.ops.subtract(v.gears.internal({ module: v.module, teeth: v.teeth, width: v.width, rim: v.rim }), ...holes)
633
+ }
634
+ ```
635
+
636
+ ```json projects/home/objects/winder-gear.json
637
+ {
638
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
639
+ "name": "winder-gear",
640
+ "title": "Winder planet",
641
+ "version": "0.1.0",
642
+ "uses": ["x1c"],
643
+ "anchors": { "axis": { "at": [0, 0, 0], "axis": [0, 0, 1] } },
644
+ "variables": {
645
+ "module": { "value": 1, "unit": "mm", "rule": "As the ring" },
646
+ "teeth": { "value": 18, "rule": "From planetary(): 18 for 4 : 1 with three planets" },
647
+ "width": { "value": "x1c.layer * 30", "unit": "mm", "rule": "As the ring" },
648
+ "bore": { "value": "3 + x1c.line / 2", "unit": "mm", "rule": "A 3 mm pin and half a line's clearance" }
649
+ }
650
+ }
651
+ ```
652
+
653
+ ```js projects/home/objects/winder-gear.js
654
+ export function main (v) {
655
+ return v.gears.spur({ module: v.module, teeth: v.teeth, width: v.width, bore: v.bore })
656
+ }
657
+ ```
658
+
659
+ The sun is a planet with the spool's shaft on top, bored through for its axle:
660
+
661
+ ```json projects/home/objects/winder-sun.json
662
+ {
663
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
664
+ "name": "winder-sun",
665
+ "title": "Winder sun and spool shaft",
666
+ "version": "0.1.0",
667
+ "uses": ["x1c"],
668
+ "engine": "manifold",
669
+ "anchors": { "axis": { "at": [0, 0, 0], "axis": [0, 0, 1] } },
670
+ "variables": {
671
+ "module": { "value": 1, "unit": "mm", "rule": "As the ring" },
672
+ "teeth": { "value": 18, "rule": "From planetary()" },
673
+ "width": { "value": "x1c.layer * 30", "unit": "mm", "rule": "As the ring" },
674
+ "bore": { "value": "3 + x1c.line / 2", "unit": "mm", "rule": "On the case's 3 mm axle" },
675
+ "shaft": { "value": 8, "unit": "mm", "rule": "The spool's shaft, inside the sun's roots" },
676
+ "shaft_height": { "value": 12, "unit": "mm", "rule": "Up through the carrier, and a spool's width over it" }
677
+ }
678
+ }
679
+ ```
680
+
681
+ ```js projects/home/objects/winder-sun.js
682
+ import jscad from '@jscad/modeling'
683
+ const { cylinder } = jscad.primitives
684
+
685
+ export function main (v) {
686
+ const gear = v.gears.spur({ module: v.module, teeth: v.teeth, width: v.width, bore: v.bore })
687
+ const shaft = cylinder({ radius: v.shaft / 2, height: v.shaft_height, center: [0, 0, v.width + v.shaft_height / 2] })
688
+ const hole = cylinder({ radius: v.bore / 2, height: v.shaft_height, center: [0, 0, v.width + v.shaft_height / 2] })
689
+ return v.ops.union(gear, v.ops.subtract(shaft, hole))
690
+ }
691
+ ```
692
+
693
+ The carrier is drawn as it prints: a flat plate on the bed (the disc over the gears, inside the ring's tips, and the
694
+ crank arm in the same plane, reaching out over the ring), with a pin standing up from it for each planet. The assembly
695
+ turns it over, so its pins hang down into the planets. The planets turn every 120° at the sun-to-planet distance
696
+ (m (S + P) / 2 = 18 mm). The handle is a part of its own, printed upright and pressed into the arm's end, as a crank
697
+ handle usually is.
698
+
699
+ ```json projects/home/objects/winder-carrier.json
700
+ {
701
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
702
+ "name": "winder-carrier",
703
+ "title": "Winder carrier and crank arm",
704
+ "version": "0.1.0",
705
+ "uses": ["x1c"],
706
+ "engine": "manifold",
707
+ "anchors": {
708
+ "axis": { "at": [0, 0, 0], "axis": [0, 0, -1] },
709
+ "grip": { "at": ["arm", 0, 0], "axis": [0, 0, -1] },
710
+ "p0": { "at": ["a", 0, "t + drop"], "axis": [0, 0, -1] },
711
+ "p1": { "at": ["0 - a / 2", "a * 0.8660254", "t + drop"], "axis": [0, 0, -1] },
712
+ "p2": { "at": ["0 - a / 2", "0 - a * 0.8660254", "t + drop"], "axis": [0, 0, -1] }
713
+ },
714
+ "variables": {
715
+ "a": { "value": 18, "unit": "mm", "rule": "Sun to planet: m (S + P) / 2" },
716
+ "drop": { "value": "6 + x1c.layer * 2", "unit": "mm", "rule": "A planet's width and two layers' gap above it" },
717
+ "radius": { "value": 25, "unit": "mm", "rule": "Inside the ring's tips (26 mm)" },
718
+ "t": { "value": "x1c.layer * 15", "unit": "mm", "rule": "Fifteen layers" },
719
+ "hole": { "value": 9, "unit": "mm", "rule": "Round the sun's 8 mm shaft" },
720
+ "pin": { "value": 3, "unit": "mm", "rule": "The planets' axles" },
721
+ "arm": { "value": 45, "unit": "mm", "rule": "The crank's reach, out over the ring" },
722
+ "bar": { "value": 10, "unit": "mm", "rule": "The crank arm's width" },
723
+ "peg": { "value": 4, "unit": "mm", "rule": "The handle's peg" },
724
+ "fit": { "value": "x1c.line / 4", "unit": "mm", "rule": "A press fit for the handle's peg: a quarter line" },
725
+ "planets": { "value": 3, "rule": "From planetary(): three planets" }
726
+ }
727
+ }
728
+ ```
729
+
730
+ ```js projects/home/objects/winder-carrier.js
731
+ // The carrier as it prints: a flat plate (the disc and the crank arm) on the bed, the planets' pins standing up from it.
732
+ import jscad from '@jscad/modeling'
733
+ const { cylinder, cuboid } = jscad.primitives
734
+
735
+ export function main (v) {
736
+ const plate = v.ops.union(cylinder({ radius: v.radius, height: v.t, center: [0, 0, v.t / 2] }),
737
+ cuboid({ size: [v.arm, v.bar, v.t], center: [v.arm / 2, 0, v.t / 2] }), cylinder({ radius: v.bar / 2, height: v.t, center: [v.arm, 0, v.t / 2] }))
738
+ const third = (2 * Math.PI) / v.planets
739
+ const pins = [0, 1, 2].map((k) => cylinder({ radius: v.pin / 2, height: v.drop, center: [v.a * Math.cos(k * third), v.a * Math.sin(k * third), v.t + v.drop / 2] }))
740
+ const hole = cylinder({ radius: v.hole / 2, height: v.t, center: [0, 0, v.t / 2] })
741
+ const socket = cylinder({ radius: v.peg / 2 - v.fit, height: v.t, center: [v.arm, 0, v.t / 2] })
742
+ return v.ops.subtract(v.ops.union(plate, ...pins), hole, socket)
743
+ }
744
+ ```
745
+
746
+ ```json projects/home/objects/winder-handle.json
747
+ {
748
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
749
+ "name": "winder-handle",
750
+ "title": "Winder handle",
751
+ "version": "0.1.0",
752
+ "uses": ["x1c"],
753
+ "anchors": { "peg": { "at": [0, 0, "grip_height"], "axis": [0, 0, -1] } },
754
+ "variables": {
755
+ "grip": { "value": 9, "unit": "mm", "rule": "A finger round it" },
756
+ "grip_height": { "value": 22, "unit": "mm", "rule": "A finger's width and a little" },
757
+ "peg": { "value": 4, "unit": "mm", "rule": "Into the arm's socket" },
758
+ "peg_height": { "value": "x1c.layer * 15", "unit": "mm", "rule": "Through the arm" }
759
+ }
760
+ }
761
+ ```
762
+
763
+ ```js projects/home/objects/winder-handle.js
764
+ // The handle as it prints: the grip on the bed, its peg standing on top.
765
+ import jscad from '@jscad/modeling'
766
+ const { cylinder } = jscad.primitives
767
+
768
+ export function main (v) {
769
+ return v.ops.union(cylinder({ radius: v.grip / 2, height: v.grip_height, center: [0, 0, v.grip_height / 2] }),
770
+ cylinder({ radius: v.peg / 2, height: v.peg_height, center: [0, 0, v.grip_height + v.peg_height / 2] }))
771
+ }
772
+ ```
773
+
774
+ The assembly holds the ring on the case, by two push pins up from the case's rim into counterbored holes in the
775
+ ring's (the fit that says so is what the check reads as holding it), and turns the carrier on the crank; the `planetary` turns the sun and the
776
+ planets with it, in phase. The gears sit two layers off the case, so nothing rubs as it turns. The case, the sun and the carrier
777
+ are built with Manifold's booleans (`"engine": "manifold"`): closed solids, so the check measures them quickly.
778
+
779
+ ```json projects/home/assemblies/winder.json
780
+ {
781
+ "title": "Spool winder",
782
+ "kind": "fit",
783
+ "items": [
784
+ { "id": "case", "object": "winder-case" },
785
+ { "id": "ring", "object": "winder-ring", "at": [0, 0, "case.t"] },
786
+ { "id": "sun", "object": "winder-sun" },
787
+ { "id": "carrier", "object": "winder-carrier" },
788
+ { "id": "handle", "object": "winder-handle" },
789
+ { "id": "p0", "object": "winder-gear" },
790
+ { "id": "p1", "object": "winder-gear" },
791
+ { "id": "p2", "object": "winder-gear" }
792
+ ],
793
+ "joints": [
794
+ { "id": "sun", "type": "revolute", "parent": { "item": "case", "at": [0, 0, "case.t + 0.4"], "axis": [0, 0, 1] }, "child": "sun.axis", "min": -3000, "max": 3000 },
795
+ { "id": "crank", "type": "revolute", "parent": { "item": "case", "at": [0, 0, "case.t + 0.8 + ring.width + carrier.t"], "axis": [0, 0, 1] }, "child": "carrier.axis", "min": -180, "max": 180, "label": "Crank" },
796
+ { "id": "handle", "type": "fixed", "parent": "carrier.grip", "child": "handle.peg" },
797
+ { "id": "p0", "type": "revolute", "parent": "carrier.p0", "child": "p0.axis", "min": -3000, "max": 3000 },
798
+ { "id": "p1", "type": "revolute", "parent": "carrier.p1", "child": "p1.axis", "min": -3000, "max": 3000 },
799
+ { "id": "p2", "type": "revolute", "parent": "carrier.p2", "child": "p2.axis", "min": -3000, "max": 3000 }
800
+ ],
801
+ "planetary": [
802
+ { "sun": "sun", "carrier": "carrier", "ring": "ring", "planets": ["p0", "p1", "p2"], "drive": "carrier",
803
+ "module": "ring.module", "teeth": ["sun.teeth", "p0.teeth", "ring.teeth"] }
804
+ ],
805
+ "fits": [{ "a": "handle", "b": "carrier", "min": "0 - carrier.fit * 2", "note": "The handle's peg pressed into the arm" },
806
+ { "a": "ring", "b": "case", "fastens": true, "note": "The ring held still on the case by its two push pins" }],
807
+ "poses": { "rest": { "crank": 0 }, "quarter": { "crank": 90 } }
808
+ }
809
+ ```
810
+
811
+ ```sh
812
+ npx cad check home/winder
813
+ npx cad check home/winder --sweep --steps 24
814
+ ```
815
+
816
+ The check says `the carrier drives the sun and the planets (the ring held): 4 turns of the sun for each turn of the
817
+ carrier, the same way`, and each planet's centre distance and contact ratio. The sweep turns the crank from −180° to
818
+ 180°, the sun four times as far, and looks for anything that touches. Move a planet's anchor off its 120° and the
819
+ check fails it: it can't mesh with the sun and the ring at once there.
package/README.md CHANGED
@@ -366,9 +366,25 @@ then y, then z, as `rotate` does.
366
366
  true` makes it a ring gear round its pinion. `shift` ([the driver's, this one's]), `pressureAngle` and `backlash` are
367
367
  as `@rulecad/gears` takes them. Each gear is drawn as `v.gears` draws it (axis up its z, first tooth on +x; a rack
368
368
  along its x, teeth up +y) and its joint is anchored at its centre, along its axis. The check gives the ratio, the
369
- contact ratio and the centre distance (`mesh.centre`: closer than the gears need jams them, further adds backlash),
370
- each placed between the two axes; `--sweep` turns the train and looks for teeth that touch. Both gears' axes sit on
371
- one part, or on parts held still: a planet on a turning carrier is not yet a mesh.
369
+ contact ratio and the centre distance (`mesh.centre`: closer than the gears need eats their backlash, and past it they jam; further adds backlash),
370
+ each placed between the two axes, and measures the pair from its drawn teeth (`mesh.backlash`, `mesh.interference`,
371
+ kept in `.cache/gears/`); `--sweep` turns the train and looks for teeth that touch. Both gears' axes sit on
372
+ one part, or on parts held still; planets on a carrier are a `planetary`.
373
+ - **Worms and bevels:** `"worm": true` (or `{ "diameter", "hand" }`) in a mesh makes the driving joint a worm and
374
+ this one its wheel, `teeth` [starts, the wheel's], the axes crossed at right angles; the check says the ratio,
375
+ whether it locks, and the centre distance. `"bevel": true` makes the two bevel gears, their axes meeting at the
376
+ shaft angle; the cones must share their apex (`mesh.bevel`). Both follow in phase, so `--sweep` turns them clean.
377
+ - **Planetary gearboxes:** `"planetary": [{ "sun": "sun", "carrier": "carrier", "ring": "ring", "planets": ["p0", "p1",
378
+ "p2"], "drive": "carrier", "module": 1, "teeth": ["sun.teeth", "p0.teeth", "ring.teeth"] }]` names the items. One of
379
+ the sun, carrier and ring is held (no joint, or a fixed one); the one `drive` names turns on its revolute, and the
380
+ third, and each planet on its revolute on the carrier, follow it, in phase. The check says the ratio, each planet's
381
+ centre distance and contact ratio, and fails a planet that can't mesh with the sun and the ring where it is
382
+ (`planetary.phase`: planets go every 360° / n, and (S + R) / n is whole). `planetary()` in `@rulecad/gears` finds
383
+ teeth for a ratio.
384
+ - **What holds each part:** in an assembly that moves, every part but the first turns or slides on a joint, or is
385
+ fastened to the first through fits with `"fastens": true` (the pins, screws or press that do it, named in the fit's
386
+ note): `{ "a": "ring", "b": "case", "fastens": true, "note": "Two push pins" }`. A part only placed somewhere is
387
+ said (`assembly.loose`): a ring gear resting on its case would turn with its planets.
372
388
  - **Loops:** each item has one joint to its parent. Where parts join in a ring (two links between the same two
373
389
  parts), let joints place every part, then name the meeting that closes the ring in `loops`. The check measures it
374
390
  in every pose: `"loops": [{ "a": "link_l.top", "b": "mount_l.axis", "label": "Left pivot lines up" }]`. Its anchors
package/lib/assembly.mjs CHANGED
@@ -20,16 +20,18 @@ import { host, readJson } from './host.mjs';
20
20
  import fs from 'node:fs';
21
21
  import crypto from 'node:crypto';
22
22
  import path from 'node:path';
23
+ import { fileURLToPath } from 'node:url';
23
24
  import { evaluate, loadRuleSet } from './rules.mjs';
24
25
  import { paths, printerOf } from './workspace.mjs';
25
26
  import { locate, build, readObject, jscad } from './design.mjs';
26
27
  import { materialise } from './versions.mjs';
27
28
  import { satisfies } from '@rulecad/versions';
28
29
  import { bounds } from '@rulecad/printcheck';
29
- import { closest, closestAt, inside, distanceToFace } from '@rulecad/fit';
30
+ import { closest, closestAt, inside, distanceToFace, overlapAt } from '@rulecad/fit';
30
31
  import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
31
32
  import { DOFS, frame, turn, mul, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
32
- import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase } from '@rulecad/gears';
33
+ import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase, contact, wormModel, wormMesh, bevelModel, bevelMesh } from '@rulecad/gears';
34
+ import { ops as booleans } from '@rulecad/shapes';
33
35
 
34
36
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
35
37
  export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
@@ -57,6 +59,7 @@ export { satisfies }; // from @rulecad/versions
57
59
  // overrides: { itemId: { variable: value } }, set on this assembly's items by the assembly that uses it.
58
60
  // opts: { mirror: true } builds each object with its mirror settings (cad show).
59
61
  export async function buildAssembly(ref, stack = [], overrides = {}, opts = {}) {
62
+ await measurer();
60
63
  const outer = overrides;
61
64
  const [project, name] = ref.split('/');
62
65
  if (stack.includes(ref)) throw new Error(`assembly ${ref} contains itself (${[...stack, ref].join(' → ')})`);
@@ -349,7 +352,7 @@ function motionOf(a, placed, num, ref) {
349
352
  // A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
350
353
  return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
351
354
  });
352
- const meshes = gearMeshes(joints, items, num);
355
+ const meshes = [...gearMeshes(joints, items, num), ...planetaries(a.planetary || [], joints, items, num)];
353
356
  const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).filter(([id]) => !id.includes('.')).map(([id, v]) => {
354
357
  if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
355
358
  return [id, Array.isArray(v) ? v.map(num) : num(v)];
@@ -364,6 +367,169 @@ function motionOf(a, placed, num, ref) {
364
367
  return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes };
365
368
  }
366
369
 
370
+ // A pair measured from its drawn teeth (@rulecad/gears contact: backlash, transmission error, interference), kept in
371
+ // .cache/gears/ by the pair, the centre distance and the gears package's code, as it takes half a second
372
+ let gearsCode = null;
373
+ function measured(a, b, centre) {
374
+ gearsCode ||= (() => { const dir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))); return fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs').sort().map((f) => fs.readFileSync(path.join(dir, f), 'utf8')).join(''); })();
375
+ const file = paths.cache('gears', `${crypto.createHash('sha256').update(JSON.stringify([gearsCode, a, b, +centre.toFixed(6)])).digest('hex')}.json`);
376
+ if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
377
+ const r = contact(a, b, { centre, steps: 12 }), keep = { findings: r.findings, backlash: r.backlash, error: r.error };
378
+ try { host.writeText(file, JSON.stringify(keep)); } catch {} // (only slower without it)
379
+ return keep;
380
+ }
381
+
382
+ // A planetary gearbox: "planetary": [{ "sun", "carrier", "ring", "planets": [items], "drive": "sun" | "carrier" | "ring",
383
+ // "module", "teeth": [sun, planet, ring] }]. One of the sun, carrier and ring is held (no joint, or a fixed one); the
384
+ // one named by drive turns on its joint, and every other moving part (the third, and each planet on the carrier)
385
+ // follows it. With one held, each turns in proportion to the driver (Willis), so each is a follow: its ratio from the
386
+ // teeth, its offset from where the parts are with their joints at 0, so a tooth sits in a gap everywhere.
387
+ function planetaries(list, joints, items, num) {
388
+ const out = [], DEG = Math.PI / 180;
389
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
390
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
391
+ const crossP = (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]];
392
+ const flat = (v, z) => sub(v, z.map((x) => x * dot(v, z))), len = (v) => Math.hypot(...v);
393
+ const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v)); // radians
394
+ list.forEach((g, n) => {
395
+ const what = `planetary ${n + 1}`, index = (id, role) => { const k = items.findIndex((x) => x[0] === id); if (k < 0) throw new Error(`${what}: ${role} "${id}" isn't an item (${items.map((x) => x[0]).join(', ')})`); return k; };
396
+ const idx = { sun: index(g.sun, 'sun'), carrier: index(g.carrier, 'carrier'), ring: index(g.ring, 'ring') };
397
+ const planets = [].concat(g.planets || []).map((id) => index(id, 'planet'));
398
+ if (!planets.length) throw new Error(`${what}: planets names the planet items`);
399
+ const jointOf = (k) => joints.find((j) => j.child === k), moving = (k) => { const j = jointOf(k); return j && j.type !== 'fixed' ? j : null; };
400
+ const held = ['sun', 'carrier', 'ring'].filter((m) => !moving(idx[m]));
401
+ if (held.length !== 1) throw new Error(`${what}: hold one of the sun, carrier and ring (no joint, or a fixed one), and turn the other two on revolutes (held now: ${held.join(', ') || 'none'})`);
402
+ const drive = g.drive ?? ['carrier', 'sun', 'ring'].find((m) => m !== held[0]);
403
+ if (!['sun', 'carrier', 'ring'].includes(drive) || drive === held[0]) throw new Error(`${what}: drive is the sun, the carrier or the ring, and not the one held (${held[0]})`);
404
+ const third = ['sun', 'carrier', 'ring'].find((m) => m !== held[0] && m !== drive), lead = moving(idx[drive]), follower = moving(idx[third]);
405
+ for (const [m, j] of [[drive, lead], [third, follower]]) if (j.type !== 'revolute') throw new Error(`${what}: the ${m} turns on a revolute (its joint ${j.id} is a ${j.type})`);
406
+ if (follower.follow || follower.meshSpec) throw new Error(`${what}: ${follower.id} turns the ${third}, which follows the ${drive} here: give it no follow or mesh of its own`);
407
+ const planetJoints = planets.map((k) => { const j = jointOf(k); if (!j || j.type !== 'revolute' || j.parent !== idx.carrier) throw new Error(`${what}: planet ${items[k][0]} turns on a revolute on the carrier (${items[idx.carrier][0]})`); return j; });
408
+ const teeth = [].concat(g.teeth || []).map(num);
409
+ if (teeth.length !== 3) throw new Error(`${what}: teeth is [sun, planet, ring] (got ${JSON.stringify(g.teeth)})`);
410
+ const [S, P, R] = teeth, common = { module: num(g.module), ...(g.pressureAngle != null ? { pressureAngle: num(g.pressureAngle) } : {}), ...(g.backlash != null ? { backlash: num(g.backlash) } : {}) };
411
+ let sun, planet, ring;
412
+ try { sun = gearModel({ ...common, teeth: S }); planet = gearModel({ ...common, teeth: P }); ring = internalModel({ ...common, teeth: R }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
413
+ if (R !== S + 2 * P) throw new Error(`${what}: a ring of ${R} isn't the sun and two planets across (${S} + 2 × ${P} = ${S + 2 * P})`);
414
+ // Every part where it is with these joints at 0
415
+ const v = jointValues({ joints, poses: {} }, {});
416
+ for (const j of [lead, follower, ...planetJoints]) v[j.id] = [0];
417
+ const worlds = placeItems({ items, joints }, v), W = (k) => worlds[k];
418
+ const O = org(W(idx.sun)), Z = col(W(idx.sun), 2), X0 = col(W(idx.sun), 0);
419
+ const sign = (j) => Math.sign(dot(mul(j.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[j.parent], j.a).filter((_, i) => [2, 6, 10].includes(i)), Z));
420
+ for (const m of ['carrier', 'ring']) { const c = org(W(idx[m])), z = col(W(idx[m]), 2); if (len(flat(sub(c, O), Z)) > 1e-4 || Math.abs(Math.abs(dot(z, Z)) - 1) > 1e-6) throw new Error(`${what}: the ${m} turns about the sun's axis: centre it there`); }
421
+ const gr = ang(flat(col(W(idx.ring), 0), Z), X0, Z) * (dot(col(W(idx.ring), 2), Z) > 0 ? 1 : -1);
422
+ // planet k: where it sits (its centre's angle round the sun) and which way its first tooth points
423
+ const pl = planets.map((k, i) => { const c = flat(sub(org(W(k)), O), Z); return { id: items[k][0], joint: planetJoints[i], r: len(c), beta: ang(c, X0, Z), gamma: ang(flat(col(W(k), 0), Z), X0, Z), s: sign(planetJoints[i]) }; });
424
+ // One configuration that meshes, everything at its zero: planet 0 in phase with the ring, the sun with planet 0
425
+ const b0 = pl[0].beta, pi0 = (R / P) * (gr - b0 * (1 - P / R) + Math.PI / R), sigma0 = (P / S) * (b0 * (1 + S / P) + Math.PI - Math.PI / P - pi0);
426
+ // Willis on rotations from the zero (sun σ, carrier κ, ring ρ): σ − κ + (R/S)(ρ − κ) = σ0
427
+ const coef = { sun: 1, carrier: -(1 + R / S), ring: R / S };
428
+ const sg = { [drive]: sign(lead), [third]: sign(follower) };
429
+ // the third's rotation for the driver's: from the relation, with the held one still
430
+ const rot = (d) => { const r = { [held[0]]: 0, [drive]: sg[drive] * d }; r[third] = (sigma0 - coef[drive] * r[drive]) / coef[third]; return r; };
431
+ // 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]; };
433
+ const [k3, o3] = lin((d) => sg[third] * rot(d * DEG)[third]);
434
+ follower.follow = [lead.id, k3, o3];
435
+ const findings = [], f = (level, text, code, between) => findings.push({ level, text, code, ...(between ? { between } : {}) });
436
+ pl.forEach((p, i) => {
437
+ // the planet's first tooth from the sun's mesh: π = −(S/P) σ + β (1 + S/P) + π − π/P, β the planet's place
438
+ 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
+ const [kp, op] = lin((d) => p.s * (tooth(d) - p.gamma - rot(d * DEG).carrier));
440
+ p.joint.follow = [lead.id, kp, op];
441
+ // and with the ring: in phase with it too, or it can't go there
442
+ const ringTooth = (P / R) * tooth(0) + p.beta * (1 - P / R) - Math.PI / R, pitch = (2 * Math.PI) / R;
443
+ const miss = (((ringTooth - gr) % pitch) + pitch * 1.5) % pitch - pitch / 2;
444
+ const centre = org(W(planets[i]));
445
+ if (Math.abs(miss) > 1e-6) f('fail', `planet ${p.id} can't mesh with the sun and the ring at once where it is (${(p.beta / DEG).toFixed(2)}° round the sun): planets go every ${(360 / planets.length).toFixed(2)}°, and (S + R) / planets must be whole (${S + R} / ${planets.length})`, 'planetary.phase', [O, centre]);
446
+ const m = meshOf(sun, planet, { centre: p.r });
447
+ for (const x of m.findings) f(x.level, `sun and ${p.id}: ${x.text}`, x.code, [O, centre]);
448
+ if (i === 0) {
449
+ for (const x of measured({ ...common, teeth: S }, { ...common, teeth: P }, p.r).findings) f(x.level, `sun and ${p.id}: ${x.text}`, x.code, [O, centre]);
450
+ for (const x of measured({ ...common, teeth: P }, { ...common, teeth: R, kind: 'internal' }, p.r).findings) f(x.level, `${p.id} and the ring: ${x.text}`, x.code, [O, centre]);
451
+ }
452
+ });
453
+ 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 });
455
+ });
456
+ return out;
457
+ }
458
+
459
+ // Bevel gears: "mesh": { "with": <the other's joint>, "module", "teeth": [its, this one's], "bevel": true } on revolutes
460
+ // whose axes meet at the shaft angle, each gear drawn as @rulecad/gears draws one (back end at z = 0, apex up z). The
461
+ // cones must share their apex. The ratio is the surface speeds' where the pitch cones touch; the phase puts a tooth
462
+ // of one against a space of the other along that line.
463
+ function bevelDrive(j, lead, spec, teeth, common, joints, items, num) {
464
+ const what = `joint ${j.id}: mesh`, DEG = Math.PI / 180;
465
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
466
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], add = (a, b) => a.map((x, i) => x + b[i]), times = (a, k) => a.map((x) => x * k);
467
+ const crossP = (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]], len = (v) => Math.hypot(...v), unit = (v) => times(v, 1 / len(v));
468
+ const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v));
469
+ const v = jointValues({ joints, poses: {} }, {}); v[lead.id] = [0]; v[j.id] = [0];
470
+ const worlds = placeItems({ items, joints }, v), W1 = worlds[lead.child], W2 = worlds[j.child];
471
+ const O1 = org(W1), Z1 = col(W1, 2), X1 = col(W1, 0), O2 = org(W2), Z2 = col(W2, 2), X2 = col(W2, 0);
472
+ const shaft = Math.acos(Math.max(-1, Math.min(1, dot(Z1, Z2)))) / DEG;
473
+ let g1, g2;
474
+ try { g1 = bevelModel({ ...common, teeth: teeth[0], mate: teeth[1], shaftAngle: shaft }); g2 = bevelModel({ ...common, teeth: teeth[1], mate: teeth[0], shaftAngle: shaft }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
475
+ // each cone's apex: along its axis, its cone distance × cos δ from its back end
476
+ const A1 = add(O1, times(Z1, g1.coneDistance * Math.cos(g1.pitchAngle * DEG))), A2 = add(O2, times(Z2, g2.coneDistance * Math.cos(g2.pitchAngle * DEG)));
477
+ const findings = [];
478
+ const apart = len(sub(A1, A2));
479
+ if (apart > 0.01) findings.push({ level: 'fail', text: `the cones' apexes are ${Number(apart.toFixed(3))} mm apart: bevel gears mesh only when their cones meet at one point (move one along its axis)`, code: 'mesh.bevel' });
480
+ // where the pitch cones touch: from the apex, δ1 from the first's axis toward the second's (both pointing away)
481
+ const out1 = times(Z1, -1), out2 = times(Z2, -1), across = unit(sub(out2, times(out1, dot(out1, out2))));
482
+ const g = add(times(out1, Math.cos(g1.pitchAngle * DEG)), times(across, Math.sin(g1.pitchAngle * DEG))), P = add(A1, times(g, g1.coneDistance));
483
+ const radial = (Z, X) => { const r = sub(g, times(Z, dot(g, Z))); return ang(r, X, Z); };
484
+ const b1 = radial(Z1, X1), b2 = radial(Z2, X2);
485
+ // the second turns so the surface speeds match where they touch: ω2 = ω1 (Z1 × P)·(Z2 × P) / |Z2 × P|², P from the apex
486
+ const p = sub(P, A1), r = dot(crossP(Z1, p), crossP(Z2, p)) / dot(crossP(Z2, p), crossP(Z2, p));
487
+ const sgn = (jt, Z) => Math.sign(dot(col(mul(jt.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[jt.parent], jt.a), 2), Z));
488
+ const s1 = sgn(lead, Z1), s2 = sgn(j, Z2), z2 = teeth[1];
489
+ const phi = b2 - Math.PI / z2 - r * b1;
490
+ j.follow = [lead.id, s2 * r * s1, (s2 * phi) / DEG];
491
+ const m = bevelMesh({ ...common, teeth: teeth[0], shaftAngle: shaft }, { ...common, teeth: teeth[1], shaftAngle: shaft });
492
+ findings.push(...m.findings);
493
+ return { joint: j.id, with: lead.id, kind: 'bevel', findings, between: [O1, O2], text: `bevel gears at ${Number(shaft.toFixed(2))}°, ${Number((teeth[0] / teeth[1]).toFixed(4))} turns of the second for each of the first (cones of ${Number(g1.pitchAngle.toFixed(2))}° and ${Number(g2.pitchAngle.toFixed(2))}°)` };
494
+ }
495
+
496
+ // A worm and its wheel: "mesh": { "with": <the worm's joint>, "module", "teeth": [starts, wheel's teeth], "worm": {
497
+ // "diameter"?, "hand"? } } on the wheel's revolute, the axes crossed. In the wheel's middle plane the worm's thread is a
498
+ // rack along the worm's axis, moving a lead a turn: the wheel follows it as a pinion does a rack, its helix's turn at
499
+ // that plane taken into account. The worm is drawn as @rulecad/gears draws it (axis up its z, from z = 0).
500
+ function wormDrive(j, lead, spec, teeth, common, joints, items, num) {
501
+ const what = `joint ${j.id}: mesh`, DEG = Math.PI / 180;
502
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
503
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
504
+ const crossP = (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]], len = (v) => Math.hypot(...v);
505
+ const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v));
506
+ const ws = spec.worm === true ? {} : spec.worm;
507
+ let w, wheel;
508
+ try {
509
+ w = wormModel({ ...common, starts: teeth[0], ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}), ...(ws.hand ? { hand: ws.hand } : {}) });
510
+ wheel = gearModel({ ...common, teeth: teeth[1], helix: w.leadAngle, hand: w.hand });
511
+ } catch (e) { throw new Error(`${what}: ${e.message}`); }
512
+ const v = jointValues({ joints, poses: {} }, {}); v[lead.id] = [0]; v[j.id] = [0];
513
+ const worlds = placeItems({ items, joints }, v), Ww = worlds[lead.child], W2 = worlds[j.child];
514
+ const Ow = org(Ww), U = col(Ww, 2), Xw = col(Ww, 0), O2 = org(W2), Z2 = col(W2, 2), X2 = col(W2, 0);
515
+ if (Math.abs(dot(U, Z2)) > 1e-6) throw new Error(`${what}: a worm's axis and its wheel's cross at right angles`);
516
+ // the line between the axes: across both (the worm's along U, the wheel's along Z2)
517
+ const rel = sub(O2, Ow), at = dot(rel, U), toWheel = sub(sub(rel, U.map((x) => x * at)), Z2.map((x) => x * dot(rel, Z2))), dist = len(toWheel), Y = toWheel.map((x) => x / dist), Zr = crossP(U, Y);
518
+ const sense = w.hand === 'left' ? -1 : 1, sw = Math.sign(dot(col(mul(lead.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[lead.parent], lead.a), 2), U));
519
+ const s2 = Math.sign(dot(Z2, Zr)), tw = ang(Y, Xw, U), g2 = ang(X2, U, Zr) * 1, r2 = wheel.pitch / 2;
520
+ // the wheel's helix: its tooth 0 at the worm's plane is turned by k z there
521
+ const zMid = dot(sub(Ow, O2), Z2), k = (sense * Math.tan(w.leadAngle * DEG)) / r2;
522
+ const phr = rackPhase(wheel, at), L = w.lead;
523
+ // space centres of the thread, at the wheel, sit at z0 = sense L (tw − θw) / 2π along the worm; the wheel turns as on a rack
524
+ const theta = (dw) => { const z0 = (sense * L * (tw - sw * dw * DEG)) / (2 * Math.PI); return s2 * ((z0 - phr) / r2 - g2) - k * zMid; };
525
+ const a0 = theta(0), a1 = theta(1);
526
+ j.follow = [lead.id, (a1 - a0) / DEG, a0 / DEG];
527
+ const m = wormMesh({ ...common, starts: teeth[0], ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}), ...(ws.hand ? { hand: ws.hand } : {}) }, { teeth: teeth[1] });
528
+ const c = meshOf(wheel, rackModel({ ...common, teeth: 4 }), { centre: dist - w.pitch / 2 });
529
+ 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` };
531
+ }
532
+
367
533
  // Gears that mesh: "mesh": { "with": <the driving joint>, "module", "teeth": [its, this one's], "shift"?, "ring"? } on
368
534
  // a revolute (a gear, or a ring with "ring": true) or a prismatic (a rack). It becomes a follow: the ratio from the
369
535
  // teeth, and the offset that puts a tooth in a gap, read from where the two gears are with their joints at 0. Each
@@ -389,11 +555,13 @@ function gearMeshes(joints, items, num) {
389
555
  if (!lead) throw new Error(`${what}: "with" names the driving joint (${joints.filter((x) => x !== j).map((x) => x.id).join(', ')}; got ${JSON.stringify(spec.with)})`);
390
556
  if (lead.type !== 'revolute') throw new Error(`${what}: ${lead.id} is a ${lead.type}; the driver is a gear turning on a revolute`);
391
557
  if (j.type !== 'revolute' && j.type !== 'prismatic') throw new Error(`${what}: a gear turns on a revolute, a rack slides on a prismatic (this is a ${j.type})`);
392
- const kind = j.type === 'prismatic' ? 'rack' : spec.ring ? 'internal' : 'external';
558
+ const kind = spec.bevel ? 'bevel' : spec.worm ? 'worm' : j.type === 'prismatic' ? 'rack' : spec.ring ? 'internal' : 'external';
393
559
  if (!(lead.parent === j.parent || (still(lead.parent) && still(j.parent)))) throw new Error(`${what}: ${lead.id} and ${j.id} turn on parts that move apart (a planet on a carrier): a mesh needs both on one part, or both on parts held still`);
394
560
  const teeth = list(spec.teeth).map(num), shift = list(spec.shift ?? [0, 0]).map(num);
395
561
  if (teeth.length !== 2) throw new Error(`${what}: teeth is [the driver's, this one's] (got ${JSON.stringify(spec.teeth)})`);
396
562
  const common = { module: num(spec.module), ...(spec.pressureAngle != null ? { pressureAngle: num(spec.pressureAngle) } : {}), ...(spec.backlash != null ? { backlash: num(spec.backlash) } : {}) };
563
+ if (kind === 'worm') { out.push(wormDrive(j, lead, spec, teeth, common, joints, items, num)); continue; }
564
+ if (kind === 'bevel') { out.push(bevelDrive(j, lead, spec, teeth, common, joints, items, num)); continue; }
397
565
  let A, B;
398
566
  try {
399
567
  A = gearModel({ ...common, teeth: teeth[0], shift: shift[0] });
@@ -417,13 +585,14 @@ function gearMeshes(joints, items, num) {
417
585
  const k = (Math.PI * A.pitch) / 360, g1 = angleIn(along(X1, Zr), U, Zr);
418
586
  j.follow = [lead.id, sTravel * s1 * k, sTravel * (k * g1 + rackPhase(A, at))];
419
587
  const m = meshOf(A, B, { centre: height });
420
- result.findings = m.findings; result.between = [O1, [R0[0] + at * U[0], R0[1] + at * U[1], R0[2] + at * U[2]]]; result.text = m.text;
588
+ result.findings = [...m.findings, ...measured({ ...common, teeth: teeth[0], shift: shift[0] }, { ...common, teeth: teeth[1], kind: 'rack' }, height).findings]; result.between = [O1, [R0[0] + at * U[0], R0[1] + at * U[1], R0[2] + at * U[2]]]; result.text = m.text;
421
589
  } else {
422
590
  const O2 = org(W2), X2 = col(W2, 0), Z2 = col(W2, 2), ax2 = axisOf(j);
423
591
  if (Math.abs(Math.abs(dot(ax2.dir, Z2)) - 1) > 1e-6 || len(along(sub(O2, ax2.at), ax2.dir)) > 1e-4) throw new Error(`${what}: ${j.id} doesn't turn its gear about the gear's own centre and axis: anchor the gear's joint at its centre, along its axis`);
424
592
  if (Math.abs(Math.abs(dot(Z1, Z2)) - 1) > 1e-6) throw new Error(`${what}: ${lead.id} and ${j.id} turn about axes that aren't parallel (spur gears need parallel axes)`);
425
593
  const s = Math.sign(dot(Z1, Z2)), d = along(sub(O2, O1), Z1), beta = angleIn(d, X1, Z1), g2 = angleIn(along(X2, Z1), X1, Z1);
426
594
  const m = meshOf(A, B, { centre: len(d) });
595
+ m.findings.push(...measured({ ...common, teeth: teeth[0], shift: shift[0] }, { ...common, teeth: teeth[1], shift: shift[1] ?? 0, kind }, len(d)).findings);
427
596
  // b's angle in the driver's frame is ratio × a's + phase; its joint measures about its own z (the other way when flipped)
428
597
  j.follow = [lead.id, s * m.ratio, s * (phase(A, B, beta) - g2)];
429
598
  result.findings = m.findings; result.between = [O1, O2]; result.text = m.text;
@@ -447,8 +616,22 @@ export { closest };
447
616
 
448
617
  // How much two parts overlap (mm³), from JSCAD's intersection.
449
618
  export function overlap(ga, gb) {
450
- const v = jscad.measurements.measureVolume(jscad.booleans.intersect(ga, gb));
451
- return Math.abs(v) < 1e-6 ? 0 : Math.abs(v);
619
+ const fell = solid?.stats.fallbacks ?? 0;
620
+ const v = Math.abs(jscad.measurements.measureVolume((solid ? solid.intersect : jscad.booleans.intersect)(ga, gb)));
621
+ if (v < 1e-6) return 0;
622
+ // JSCAD's answer (no Manifold, or a shape Manifold couldn't read): only if their surfaces really cross, which fit
623
+ // says exactly (slower, so only here)
624
+ if (!solid || solid.stats.fallbacks > fell) { const faces = (g) => jscad.geometries.geom3.toPolygons(g).map((q) => q.vertices); if (!overlapAt(faces(ga), faces(gb))) return 0; }
625
+ return v;
626
+ }
627
+ // How overlaps are measured: whether the surfaces cross, exactly (fit), and then how much, with Manifold where it's
628
+ // installed. JSCAD's intersection misreads faces that come near without touching: two gears 0.07 mm apart (their
629
+ // backlash) read as 2.7 mm³ into each other at one angle in twenty, and a planet 0.4 mm over a case as 1.3 mm³.
630
+ // Manifold is exact; a shape it can't read as a closed solid falls back to JSCAD's for that pair.
631
+ let solid = null, tried = false;
632
+ async function measurer() {
633
+ if (tried) return; tried = true;
634
+ try { solid = await booleans('manifold'); } catch { solid = null; } // (without manifold-3d, JSCAD's, as before)
452
635
  }
453
636
 
454
637
  // Overlaps between placed parts, remembered across runs (.cache/overlaps.json): a part is its build (the build cache's
@@ -459,7 +642,7 @@ function pairOverlap(pa, pb) {
459
642
  if (!pa.hash || !pb.hash) return overlap(pa.geometry, pb.geometry);
460
643
  remembered ||= (() => { try { return JSON.parse(host.readText(OVERLAPS)); } catch { return {}; } })();
461
644
  const at = (p) => `${p.hash}@${Array.from(p.m || []).map((x) => Math.round(x * 1e6) / 1e6).join(',')}`;
462
- const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`${x}|${y}`).digest('hex');
645
+ const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`crossing+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
463
646
  if (!(k in remembered)) { remembered[k] = overlap(pa.geometry, pb.geometry); fresh++; }
464
647
  return remembered[k];
465
648
  }
@@ -578,12 +761,24 @@ export function checkAssembly(s) {
578
761
  }
579
762
  if (outside.length) f('fail', `joints out of range: ${outside.join(', ')}`, `${outside.length} joints out of range`, { code: 'joint.range', refs: { joints: outside } });
580
763
  for (const l of loopGaps(s)) f(l.ok ? 'pass' : 'fail', `${l.label}: ${l.ok ? 'closed' : 'apart'} (${mm(l.gap)} mm, axes ${mm(l.angle)}° apart)`, `${l.label}: ${l.ok ? 'closed' : 'apart'}`, { code: 'loop', values: { gap: l.gap, angle: l.angle }, refs: { label: l.label } });
764
+ // Held by something: in a mechanism, every part but the first either turns or slides on a joint, or is fastened,
765
+ // through a chain of fits with "fastens", to the first. A part only placed somewhere stays there in the model and
766
+ // nowhere else: a ring gear resting on its case turns with the planets; a pawl resting on its post walks off it.
767
+ if (s.motion.joints.some((j) => j.type !== 'fixed')) {
768
+ const ids = s.motion.items.map((x) => x[0]), top = (n) => String(n).split(/[.@]/)[0];
769
+ const held = new Set([ids[0], ...s.motion.joints.map((j) => ids[j.child])]), links = s.fits.filter((x) => x.fastens).map((x) => [top(x.a), top(x.b)]);
770
+ for (let grew = true; grew;) { grew = false; for (const [a, b] of links) { if (held.has(a) && !held.has(b)) { held.add(b); grew = true; } if (held.has(b) && !held.has(a)) { held.add(a); grew = true; } } }
771
+ const placed = new Set(s.objects.filter((o) => !o.unplaced && o.role !== 'reference').map((o) => top(o.id)));
772
+ const loose = ids.filter((id) => !held.has(id) && placed.has(id));
773
+ if (loose.length) f('warn', `${loose.join(', ')} ${loose.length > 1 ? 'are' : 'is'} placed, but nothing holds ${loose.length > 1 ? 'them' : 'it'}: give ${loose.length > 1 ? 'each' : 'it'} a joint, or fasten it to what it sits on (pins, screws, a press) and say so with a fit that "fastens"`, `${loose.length} loose`, { code: 'assembly.loose', refs: { items: loose } });
774
+ else f('pass', `every part turns or slides on a joint, or is fastened to the ${ids[0]}`, null, { code: 'assembly.held' });
775
+ }
581
776
  // Gears: each mesh's centre distance and contact ratio, said between the two axes (the rest by --sweep)
582
777
  for (const g of s.motion.meshes || []) {
583
- f('info', `${g.with} drives ${g.joint}: ${g.text}`, null, { code: 'mesh.ratio', refs: { joints: [g.with, g.joint] } });
778
+ f('info', g.planetary ? g.text : `${g.with} drives ${g.joint}: ${g.text}`, null, { code: 'mesh.ratio', refs: { joints: [g.with, g.joint] } });
584
779
  for (const x of g.findings) {
585
- const mid = g.between[0].map((v, k) => (v + g.between[1][k]) / 2);
586
- f(x.level, `${g.with} and ${g.joint}: ${x.text}`, x.level === 'pass' ? null : `${g.joint}: ${x.code.split('.')[1]}`, { code: x.code, at: mid, between: g.between, ...(x.values ? { values: x.values } : {}), refs: { joints: [g.with, g.joint] } });
780
+ const between = x.between || g.between, mid = between[0].map((v, k) => (v + between[1][k]) / 2);
781
+ f(x.level, g.planetary ? x.text : `${g.with} and ${g.joint}: ${x.text}`, x.level === 'pass' ? null : `${g.joint}: ${x.code.split('.')[1]}`, { code: x.code, at: mid, between, ...(x.values ? { values: x.values } : {}), refs: { joints: [g.with, g.joint] } });
587
782
  }
588
783
  }
589
784
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.34",
3
+ "version": "0.7.36",
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,7 @@
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.1.0"
73
+ "@rulecad/gears": "^0.3.0"
74
74
  },
75
75
  "peerDependencies": {
76
76
  "@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0 || ^0.4.0 || ^0.5.0"
@@ -18,6 +18,7 @@
18
18
  "fits": { "type": "array", "items": { "$ref": "#/$defs/fit" } },
19
19
  "joints": { "type": "array", "items": { "$ref": "#/$defs/joint" } },
20
20
  "loops": { "type": "array", "items": { "$ref": "#/$defs/loop" } },
21
+ "planetary": { "type": "array", "items": { "$ref": "#/$defs/planetary" } },
21
22
  "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" } } },
22
23
  "pose": { "type": "string" }
23
24
  },
@@ -63,6 +64,7 @@
63
64
  "properties": {
64
65
  "a": { "$ref": "#/$defs/names" },
65
66
  "b": { "$ref": "#/$defs/names" },
67
+ "fastens": { "type": "boolean", "description": "a and b are fastened together (pins, screws, a press): what holds a part that has no joint" },
66
68
  "min": { "$ref": "#/$defs/expr" },
67
69
  "max": { "$ref": "#/$defs/expr" },
68
70
  "note": { "type": "string" },
@@ -113,11 +115,29 @@
113
115
  "shift": { "type": "array", "minItems": 2, "maxItems": 2, "items": { "$ref": "#/$defs/expr" } },
114
116
  "pressureAngle": { "$ref": "#/$defs/expr" },
115
117
  "backlash": { "$ref": "#/$defs/expr" },
116
- "ring": { "type": "boolean" }
118
+ "ring": { "type": "boolean" },
119
+ "bevel": { "type": "boolean" },
120
+ "worm": { "anyOf": [{ "type": "boolean" }, { "type": "object", "additionalProperties": false, "properties": { "diameter": { "$ref": "#/$defs/expr" }, "hand": { "enum": ["right", "left"] } } }] }
117
121
  }
118
122
  }
119
123
  }
120
124
  },
125
+ "planetary": {
126
+ "type": "object",
127
+ "description": "A planetary gearbox: one of sun, carrier and ring held, the one named by drive turning, the rest following it in phase",
128
+ "required": ["sun", "carrier", "ring", "planets", "module", "teeth"],
129
+ "additionalProperties": false,
130
+ "properties": {
131
+ "sun": { "type": "string" }, "carrier": { "type": "string" }, "ring": { "type": "string" },
132
+ "planets": { "type": "array", "minItems": 1, "items": { "type": "string" } },
133
+ "drive": { "enum": ["sun", "carrier", "ring"] },
134
+ "module": { "$ref": "#/$defs/expr" },
135
+ "teeth": { "type": "array", "minItems": 3, "maxItems": 3, "items": { "$ref": "#/$defs/expr" } },
136
+ "pressureAngle": { "$ref": "#/$defs/expr" },
137
+ "backlash": { "$ref": "#/$defs/expr" },
138
+ "note": { "type": "string" }
139
+ }
140
+ },
121
141
  "loop": {
122
142
  "type": "object",
123
143
  "required": ["a", "b"],