@rulecad/cad 0.7.33 → 0.7.35

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, and a mechanism printed flat. 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
@@ -384,3 +384,348 @@ npx cad animate home/flick
384
384
  `animate` writes the sequence as an animated SVG in `.preview/`, the leaf drawn bent, and a page that plays it with
385
385
  the force on each step. The launcher in `examples/bench/projects/launcher` is the same idea at full size: a flooded
386
386
  frame, catches, a trigger, and a shot.
387
+
388
+ ## 8. Gears: a focus slider on a rack and pinion
389
+
390
+ A slide for a phone or a small camera, moved by a knob: a pinion turns, and a rack carries the slide along. The gears
391
+ come from `v.gears` (`@rulecad/gears`), drawn from their module and teeth; the assembly says which gear drives which,
392
+ and the check works out the rest.
393
+
394
+ The pinion has 14 teeth. Fewer than 17 at the standard 20° are undercut, so it is drawn with a profile shift of 0.2,
395
+ which `@rulecad/gears` names when it refuses one without (`give a profile shift of at least 0.19`). One turn of the knob
396
+ moves the slide π × 14 × 1 = 43.98 mm.
397
+
398
+ ```json projects/home/objects/pinion.json
399
+ {
400
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
401
+ "name": "pinion",
402
+ "title": "Focus knob and pinion",
403
+ "version": "0.1.0",
404
+ "uses": ["x1c"],
405
+ "anchors": { "axis": { "at": [0, 0, 0], "axis": [0, 0, 1] } },
406
+ "variables": {
407
+ "module": { "value": 1, "unit": "mm", "rule": "Tooth size: 3.6 lines across a tooth at the pitch circle on the X1C" },
408
+ "teeth": { "value": 14, "rule": "Few teeth for a fine travel a turn" },
409
+ "shift": { "value": 0.2, "rule": "Profile shift: 14 teeth at 20° need at least 0.19, or they are undercut" },
410
+ "width": { "value": "x1c.layer * 30", "unit": "mm", "rule": "Face width, thirty layers" },
411
+ "bore": { "value": 3.2, "unit": "mm", "rule": "An M3 screw as its axle, 0.2 mm clear" },
412
+ "knob": { "value": 5.5, "unit": "mm", "rule": "The knob's radius, inside the teeth's roots" },
413
+ "grip": { "value": "x1c.layer * 40", "unit": "mm", "rule": "The knob's height, forty layers" }
414
+ }
415
+ }
416
+ ```
417
+
418
+ ```js projects/home/objects/pinion.js
419
+ // A pinion with a knob on top: the gear's face on the bed, the knob printed on it.
420
+ import jscad from '@jscad/modeling'
421
+ const { cylinder } = jscad.primitives
422
+ const { union, subtract } = jscad.booleans
423
+
424
+ export function main (v) {
425
+ const gear = v.gears.spur({ module: v.module, teeth: v.teeth, shift: v.shift, width: v.width, bore: v.bore })
426
+ const knob = cylinder({ radius: v.knob, height: v.grip, center: [0, 0, v.width + v.grip / 2] })
427
+ const hole = cylinder({ radius: v.bore / 2, height: v.grip, center: [0, 0, v.width + v.grip / 2] })
428
+ return union(gear, subtract(knob, hole))
429
+ }
430
+ ```
431
+
432
+ ```json projects/home/objects/rack.json
433
+ {
434
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
435
+ "name": "rack",
436
+ "title": "Slide rack",
437
+ "version": "0.1.0",
438
+ "uses": ["x1c"],
439
+ "anchors": { "slide": { "at": [0, 0, 0], "axis": [1, 0, 0] } },
440
+ "variables": {
441
+ "module": { "value": 1, "unit": "mm", "rule": "The pinion's module: gears that mesh share it" },
442
+ "teeth": { "value": 24, "rule": "Long enough for 60 mm of travel" },
443
+ "width": { "value": "x1c.layer * 30", "unit": "mm", "rule": "The pinion's face width" },
444
+ "back": { "value": "x1c.line * 10", "unit": "mm", "rule": "Bar under the teeth: ten lines" }
445
+ }
446
+ }
447
+ ```
448
+
449
+ ```js projects/home/objects/rack.js
450
+ // The rack: along x, its teeth up +y, its pitch line on y = 0.
451
+ export function main (v) {
452
+ return v.gears.rack({ module: v.module, teeth: v.teeth, width: v.width, height: v.back })
453
+ }
454
+ ```
455
+
456
+ ```json projects/home/objects/rail.json
457
+ {
458
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
459
+ "name": "rail",
460
+ "title": "Slide base",
461
+ "version": "0.1.0",
462
+ "uses": ["x1c"],
463
+ "anchors": {
464
+ "axle": { "at": [0, "centre", "thick"], "axis": [0, 0, 1] },
465
+ "track": { "at": ["start", 0, "thick"], "axis": [1, 0, 0] }
466
+ },
467
+ "variables": {
468
+ "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
+ "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" }
473
+ }
474
+ }
475
+ ```
476
+
477
+ ```js projects/home/objects/rail.js
478
+ // The base: a plate under the rack's travel and the knob, the axle above the rack.
479
+ import jscad from '@jscad/modeling'
480
+
481
+ export function main (v) {
482
+ return jscad.primitives.cuboid({ size: [v.length, v.wide, v.thick], center: [0, v.wide / 4, v.thick / 2] })
483
+ }
484
+ ```
485
+
486
+ The assembly: the knob turns on the base's axle, and the rack slides along its track, its middle under the knob at
487
+ rest, so half a turn either way (±22 mm) keeps the pinion on its teeth. The slide's joint doesn't say
488
+ 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
+ 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
490
+ gap, and says whether the axle is where the gears need it.
491
+
492
+ ```json projects/home/assemblies/slider.json
493
+ {
494
+ "title": "Focus slider",
495
+ "kind": "fit",
496
+ "items": [
497
+ { "id": "rail", "object": "rail" },
498
+ { "id": "pinion", "object": "pinion" },
499
+ { "id": "rack", "object": "rack" }
500
+ ],
501
+ "joints": [
502
+ { "id": "knob", "type": "revolute", "parent": "rail.axle", "child": "pinion.axis", "min": -180, "max": 180, "label": "Knob" },
503
+ { "id": "slide", "type": "prismatic", "parent": "rail.track", "child": "rack.slide", "min": -100, "max": 100,
504
+ "mesh": { "with": "knob", "module": "pinion.module", "teeth": ["pinion.teeth", "rack.teeth"], "shift": ["pinion.shift", 0] } }
505
+ ],
506
+ "poses": { "home": { "knob": 0 }, "out": { "knob": 150 } }
507
+ }
508
+ ```
509
+
510
+ ```sh
511
+ npx cad check home/slider
512
+ npx cad check home/slider --sweep --steps 12
513
+ ```
514
+
515
+ 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
517
+ sweep turns the knob from −180° to 180° with the rack following, and names any teeth that touch on the way. The link
518
+ carries the knob as a slider, with the rack moving with it: `npx cad link home/slider --md`.
519
+
520
+ To see the gears' geometry, `@rulecad/gears/diagram` draws a pair the way a textbook does: pitch and base circles,
521
+ the line of action and the path of contact.
522
+
523
+ ## 9. A gearbox: a spool winder through a planetary
524
+
525
+ A crank that winds a spool four times for each turn: a planetary gearbox, the crank on the carrier, the spool on the
526
+ sun, the ring held in the case. `planetary()` in `@rulecad/gears` finds the teeth for the ratio and checks that they
527
+ put together:
528
+
529
+ ```js
530
+ planetary({ module: 1, ratio: 0.25, planets: 3, held: 'ring', input: 'carrier', output: 'sun' })
531
+ // 0.25 : 1 (carrier to sun, ring held), as asked: sun 18, planets 18 × 3, ring 54
532
+ ```
533
+
534
+ 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
535
+ 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
536
+ planets, and the carrier with the planets' pins and the crank.
537
+
538
+ ```json projects/home/objects/winder-case.json
539
+ {
540
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
541
+ "name": "winder-case",
542
+ "title": "Winder case",
543
+ "version": "0.1.0",
544
+ "uses": ["x1c"],
545
+ "engine": "manifold",
546
+ "variables": {
547
+ "radius": { "value": 34, "unit": "mm", "rule": "Round the ring's rim (62.5 mm across)" },
548
+ "t": { "value": "x1c.layer * 15", "unit": "mm", "rule": "Base, fifteen layers" },
549
+ "pin": { "value": 3, "unit": "mm", "rule": "The sun's axle" },
550
+ "pin_height": { "value": 24, "unit": "mm", "rule": "Up through the sun and its shaft" }
551
+ }
552
+ }
553
+ ```
554
+
555
+ ```js projects/home/objects/winder-case.js
556
+ // The case: a base with the sun's axle standing in the middle. The ring sits on it.
557
+ import jscad from '@jscad/modeling'
558
+ const { cylinder } = jscad.primitives
559
+
560
+ export function main (v) {
561
+ return v.ops.union(cylinder({ radius: v.radius, height: v.t, center: [0, 0, v.t / 2] }),
562
+ cylinder({ radius: v.pin / 2, height: v.pin_height, center: [0, 0, v.t + v.pin_height / 2] }))
563
+ }
564
+ ```
565
+
566
+ ```json projects/home/objects/winder-ring.json
567
+ {
568
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
569
+ "name": "winder-ring",
570
+ "title": "Winder ring gear",
571
+ "version": "0.1.0",
572
+ "uses": ["x1c"],
573
+ "variables": {
574
+ "module": { "value": 1, "unit": "mm", "rule": "3.6 lines across a tooth on the X1C" },
575
+ "teeth": { "value": 54, "rule": "The sun and two planets across: 18 + 2 × 18" },
576
+ "width": { "value": "x1c.layer * 40", "unit": "mm", "rule": "Face width, forty layers" }
577
+ }
578
+ }
579
+ ```
580
+
581
+ ```js projects/home/objects/winder-ring.js
582
+ export function main (v) {
583
+ return v.gears.internal({ module: v.module, teeth: v.teeth, width: v.width })
584
+ }
585
+ ```
586
+
587
+ ```json projects/home/objects/winder-gear.json
588
+ {
589
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
590
+ "name": "winder-gear",
591
+ "title": "Winder planet",
592
+ "version": "0.1.0",
593
+ "uses": ["x1c"],
594
+ "anchors": { "axis": { "at": [0, 0, 0], "axis": [0, 0, 1] } },
595
+ "variables": {
596
+ "module": { "value": 1, "unit": "mm", "rule": "As the ring" },
597
+ "teeth": { "value": 18, "rule": "From planetary(): 18 for 4 : 1 with three planets" },
598
+ "width": { "value": "x1c.layer * 40", "unit": "mm", "rule": "As the ring" },
599
+ "bore": { "value": "3 + x1c.line / 2", "unit": "mm", "rule": "A 3 mm pin and half a line's clearance" }
600
+ }
601
+ }
602
+ ```
603
+
604
+ ```js projects/home/objects/winder-gear.js
605
+ export function main (v) {
606
+ return v.gears.spur({ module: v.module, teeth: v.teeth, width: v.width, bore: v.bore })
607
+ }
608
+ ```
609
+
610
+ The sun is a planet with the spool's shaft on top, bored through for its axle:
611
+
612
+ ```json projects/home/objects/winder-sun.json
613
+ {
614
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
615
+ "name": "winder-sun",
616
+ "title": "Winder sun and spool shaft",
617
+ "version": "0.1.0",
618
+ "uses": ["x1c"],
619
+ "engine": "manifold",
620
+ "anchors": { "axis": { "at": [0, 0, 0], "axis": [0, 0, 1] } },
621
+ "variables": {
622
+ "module": { "value": 1, "unit": "mm", "rule": "As the ring" },
623
+ "teeth": { "value": 18, "rule": "From planetary()" },
624
+ "width": { "value": "x1c.layer * 40", "unit": "mm", "rule": "As the ring" },
625
+ "bore": { "value": "3 + x1c.line / 2", "unit": "mm", "rule": "On the case's 3 mm axle" },
626
+ "shaft": { "value": 8, "unit": "mm", "rule": "The spool's shaft, inside the sun's roots" },
627
+ "shaft_height": { "value": 12, "unit": "mm", "rule": "Up through the carrier, and a spool's width over it" }
628
+ }
629
+ }
630
+ ```
631
+
632
+ ```js projects/home/objects/winder-sun.js
633
+ import jscad from '@jscad/modeling'
634
+ const { cylinder } = jscad.primitives
635
+
636
+ export function main (v) {
637
+ const gear = v.gears.spur({ module: v.module, teeth: v.teeth, width: v.width, bore: v.bore })
638
+ const shaft = cylinder({ radius: v.shaft / 2, height: v.shaft_height, center: [0, 0, v.width + v.shaft_height / 2] })
639
+ const hole = cylinder({ radius: v.bore / 2, height: v.shaft_height, center: [0, 0, v.width + v.shaft_height / 2] })
640
+ return v.ops.union(gear, v.ops.subtract(shaft, hole))
641
+ }
642
+ ```
643
+
644
+ The carrier: a disc over the gears, inside the ring's tips, with a pin down into each planet and the crank on top. Its
645
+ anchors are where the planets turn, every 120° at the sun-to-planet distance (m (S + P) / 2 = 18 mm).
646
+
647
+ ```json projects/home/objects/winder-carrier.json
648
+ {
649
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
650
+ "name": "winder-carrier",
651
+ "title": "Winder carrier and crank",
652
+ "version": "0.1.0",
653
+ "uses": ["x1c"],
654
+ "engine": "manifold",
655
+ "anchors": {
656
+ "axis": { "at": [0, 0, 0], "axis": [0, 0, 1] },
657
+ "p0": { "at": ["a", 0, "0 - drop"], "axis": [0, 0, 1] },
658
+ "p1": { "at": ["0 - a / 2", "a * 0.8660254", "0 - drop"], "axis": [0, 0, 1] },
659
+ "p2": { "at": ["0 - a / 2", "0 - a * 0.8660254", "0 - drop"], "axis": [0, 0, 1] }
660
+ },
661
+ "variables": {
662
+ "a": { "value": 18, "unit": "mm", "rule": "Sun to planet: m (S + P) / 2" },
663
+ "drop": { "value": "8 + x1c.layer * 2", "unit": "mm", "rule": "A planet's width and two layers' gap above it" },
664
+ "radius": { "value": 25, "unit": "mm", "rule": "Inside the ring's tips (26 mm)" },
665
+ "t": { "value": "x1c.layer * 15", "unit": "mm", "rule": "Fifteen layers" },
666
+ "hole": { "value": 9, "unit": "mm", "rule": "Round the sun's 8 mm shaft" },
667
+ "pin": { "value": 3, "unit": "mm", "rule": "The planets' axles" },
668
+ "arm": { "value": 45, "unit": "mm", "rule": "The crank's reach" },
669
+ "bar": { "value": 10, "unit": "mm", "rule": "The crank arm's width" },
670
+ "handle": { "value": 20, "unit": "mm", "rule": "The handle's height" },
671
+ "grip": { "value": 8, "unit": "mm", "rule": "The handle's diameter" }
672
+ }
673
+ }
674
+ ```
675
+
676
+ ```js projects/home/objects/winder-carrier.js
677
+ import jscad from '@jscad/modeling'
678
+ const { cylinder, cuboid } = jscad.primitives
679
+
680
+ export function main (v) {
681
+ const disc = cylinder({ radius: v.radius, height: v.t, center: [0, 0, v.t / 2] })
682
+ const arm = cuboid({ size: [v.arm, v.bar, v.t], center: [v.arm / 2, 0, v.t + v.t / 2] })
683
+ const handle = cylinder({ radius: v.grip / 2, height: v.handle, center: [v.arm - v.grip / 2, 0, v.t * 2 + v.handle / 2] })
684
+ const third = (2 * Math.PI) / 3
685
+ 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), 0 - v.drop / 2] }))
686
+ const hole = cylinder({ radius: v.hole / 2, height: v.t * 2, center: [0, 0, v.t] })
687
+ return v.ops.subtract(v.ops.union(disc, arm, handle, ...pins), hole)
688
+ }
689
+ ```
690
+
691
+ The assembly holds the ring in the case and turns the carrier on the crank; the `planetary` turns the sun and the
692
+ 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
693
+ are built with Manifold's booleans (`"engine": "manifold"`): closed solids, so the check measures them quickly.
694
+
695
+ ```json projects/home/assemblies/winder.json
696
+ {
697
+ "title": "Spool winder",
698
+ "kind": "fit",
699
+ "items": [
700
+ { "id": "case", "object": "winder-case" },
701
+ { "id": "ring", "object": "winder-ring", "at": [0, 0, "case.t"] },
702
+ { "id": "sun", "object": "winder-sun" },
703
+ { "id": "carrier", "object": "winder-carrier" },
704
+ { "id": "p0", "object": "winder-gear" },
705
+ { "id": "p1", "object": "winder-gear" },
706
+ { "id": "p2", "object": "winder-gear" }
707
+ ],
708
+ "joints": [
709
+ { "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 },
710
+ { "id": "crank", "type": "revolute", "parent": { "item": "case", "at": [0, 0, "case.t + 0.8 + ring.width"], "axis": [0, 0, 1] }, "child": "carrier.axis", "min": -180, "max": 180, "label": "Crank" },
711
+ { "id": "p0", "type": "revolute", "parent": "carrier.p0", "child": "p0.axis", "min": -3000, "max": 3000 },
712
+ { "id": "p1", "type": "revolute", "parent": "carrier.p1", "child": "p1.axis", "min": -3000, "max": 3000 },
713
+ { "id": "p2", "type": "revolute", "parent": "carrier.p2", "child": "p2.axis", "min": -3000, "max": 3000 }
714
+ ],
715
+ "planetary": [
716
+ { "sun": "sun", "carrier": "carrier", "ring": "ring", "planets": ["p0", "p1", "p2"], "drive": "carrier",
717
+ "module": "ring.module", "teeth": ["sun.teeth", "p0.teeth", "ring.teeth"] }
718
+ ],
719
+ "poses": { "rest": { "crank": 0 }, "quarter": { "crank": 90 } }
720
+ }
721
+ ```
722
+
723
+ ```sh
724
+ npx cad check home/winder
725
+ npx cad check home/winder --sweep --steps 24
726
+ ```
727
+
728
+ The check says `the carrier drives the sun and the planets (the ring held): 4 turns of the sun for each turn of the
729
+ carrier, the same way`, and each planet's centre distance and contact ratio. The sweep turns the crank from −180° to
730
+ 180°, the sun four times as far, and looks for anything that touches. Move a planet's anchor off its 120° and the
731
+ check fails it: it can't mesh with the sun and the ring at once there.
package/README.md CHANGED
@@ -153,6 +153,9 @@ 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.gears`: gears (`@rulecad/gears`): `spur`, `rack` and `internal` as shapes, from a module and teeth, each with its
157
+ model (`gearModel`, `rackModel`, `internalModel`) and `printable(model, printer, width)`. Drawn flat: the axis up z,
158
+ the first tooth on +x, the face on the bed. Two gears in an assembly mesh with a joint's `mesh` (see Joints).
156
159
  - A rule set can also carry `"footprints"` (pad data from @rulecad/pcb's `fromKicad`, with its source), which a
157
160
  board's code reads as `v.parts.footprints.usb_c`.
158
161
  - `cad clone` writes a rule set with a `"circuit"`: a published board's parts, pads, nets, planes and outline, read
@@ -267,7 +270,7 @@ other items' variables, so a keycap can sit exactly where its slot meets the swi
267
270
  can't write or delete files, start programs or workers, or load addons, and it reads only the workspace and the
268
271
  packages designs use, by their real paths (a `node_modules` link spelled through another link, as macOS spells its
269
272
  temporary folders through `/tmp` and `/var`, is refused by name: make the link with the real path). To keep it to making shapes it may import only `@jscad/modeling`, `@rulecad/shapes`,
270
- `@rulecad/flexures` and files in its own project (no `node:` modules), `fetch` and its kin are gone, and it is
273
+ `@rulecad/flexures`, `@rulecad/gears` and files in its own project (no `node:` modules), `fetch` and its kin are gone, and it is
271
274
  started with none of your environment (no tokens). Those shut the ordinary roads to the network, not every one:
272
275
  before Node 25 the permission model doesn't cover the network, so a design written to get round them might still
273
276
  reach it. Run only designs you trust. It gets its values as data and returns its parts; what it prints
@@ -357,6 +360,22 @@ then y, then z, as `rotate` does.
357
360
  from 0 to its length.
358
361
  - **Followers:** `"follow": "lid"` gives a joint another joint's values, times `ratio` (default 1), plus `offset`. Use
359
362
  it for the second hinge of a pair, or for gears.
363
+ - **Gears:** `"mesh": { "with": "drive", "module": "pinion.module", "teeth": ["pinion.teeth", "wheel.teeth"] }` on a
364
+ revolute makes its gear follow the gear on the joint `with` names, at the ratio of their teeth and in phase: a tooth
365
+ of one sits in a gap of the other at every angle. On a prismatic it is a rack under a pinion (mm a turn); `"ring":
366
+ true` makes it a ring gear round its pinion. `shift` ([the driver's, this one's]), `pressureAngle` and `backlash` are
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
+ 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; planets on a carrier are a `planetary`.
372
+ - **Planetary gearboxes:** `"planetary": [{ "sun": "sun", "carrier": "carrier", "ring": "ring", "planets": ["p0", "p1",
373
+ "p2"], "drive": "carrier", "module": 1, "teeth": ["sun.teeth", "p0.teeth", "ring.teeth"] }]` names the items. One of
374
+ the sun, carrier and ring is held (no joint, or a fixed one); the one `drive` names turns on its revolute, and the
375
+ third, and each planet on its revolute on the carrier, follow it, in phase. The check says the ratio, each planet's
376
+ centre distance and contact ratio, and fails a planet that can't mesh with the sun and the ring where it is
377
+ (`planetary.phase`: planets go every 360° / n, and (S + R) / n is whole). `planetary()` in `@rulecad/gears` finds
378
+ teeth for a ratio.
360
379
  - **Loops:** each item has one joint to its parent. Where parts join in a ring (two links between the same two
361
380
  parts), let joints place every part, then name the meeting that closes the ring in `loops`. The check measures it
362
381
  in every pose: `"loops": [{ "a": "link_l.top", "b": "mount_l.axis", "label": "Left pivot lines up" }]`. Its anchors
package/lib/assembly.mjs CHANGED
@@ -26,9 +26,11 @@ import { locate, build, readObject, jscad } from './design.mjs';
26
26
  import { materialise } from './versions.mjs';
27
27
  import { satisfies } from '@rulecad/versions';
28
28
  import { bounds } from '@rulecad/printcheck';
29
- import { closest, closestAt, inside, distanceToFace } from '@rulecad/fit';
29
+ import { closest, closestAt, inside, distanceToFace, overlapAt } from '@rulecad/fit';
30
30
  import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
31
31
  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 { ops as booleans } from '@rulecad/shapes';
32
34
 
33
35
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
34
36
  export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
@@ -56,6 +58,7 @@ export { satisfies }; // from @rulecad/versions
56
58
  // overrides: { itemId: { variable: value } }, set on this assembly's items by the assembly that uses it.
57
59
  // opts: { mirror: true } builds each object with its mirror settings (cad show).
58
60
  export async function buildAssembly(ref, stack = [], overrides = {}, opts = {}) {
61
+ await measurer();
59
62
  const outer = overrides;
60
63
  const [project, name] = ref.split('/');
61
64
  if (stack.includes(ref)) throw new Error(`assembly ${ref} contains itself (${[...stack, ref].join(' → ')})`);
@@ -334,7 +337,8 @@ function motionOf(a, placed, num, ref) {
334
337
  });
335
338
  joints.push({ id: j.id, type: j.type, parent: p.item, child: c.item, a: p.frame, b: c.frame, dofs,
336
339
  ...(j.label ? { label: j.label } : {}), ...(path ? { path } : {}), ...(j.cone != null ? { cone: num(j.cone) } : {}),
337
- ...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}) });
340
+ ...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}),
341
+ ...(j.mesh ? { meshSpec: j.mesh } : {}) });
338
342
  }
339
343
  for (const j of joints) if (j.follow) {
340
344
  const l = joints.find((x) => x.id === j.follow[0]);
@@ -347,6 +351,7 @@ function motionOf(a, placed, num, ref) {
347
351
  // A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
348
352
  return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
349
353
  });
354
+ const meshes = [...gearMeshes(joints, items, num), ...planetaries(a.planetary || [], joints, items, num)];
350
355
  const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).filter(([id]) => !id.includes('.')).map(([id, v]) => {
351
356
  if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
352
357
  return [id, Array.isArray(v) ? v.map(num) : num(v)];
@@ -358,7 +363,149 @@ function motionOf(a, placed, num, ref) {
358
363
  const marks = placed.flatMap(([, c], k) => Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
359
364
  try { return { item: k, id: c.id, name, frame: frameOf(spec, evalIn(c.src.b.values, `${c.src.objName} anchor ${name}`)) }; } catch { return null; }
360
365
  })).filter(Boolean);
361
- return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks };
366
+ return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes };
367
+ }
368
+
369
+ // A planetary gearbox: "planetary": [{ "sun", "carrier", "ring", "planets": [items], "drive": "sun" | "carrier" | "ring",
370
+ // "module", "teeth": [sun, planet, ring] }]. One of the sun, carrier and ring is held (no joint, or a fixed one); the
371
+ // one named by drive turns on its joint, and every other moving part (the third, and each planet on the carrier)
372
+ // follows it. With one held, each turns in proportion to the driver (Willis), so each is a follow: its ratio from the
373
+ // teeth, its offset from where the parts are with their joints at 0, so a tooth sits in a gap everywhere.
374
+ function planetaries(list, joints, items, num) {
375
+ const out = [], DEG = Math.PI / 180;
376
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
377
+ 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]];
378
+ 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]];
379
+ const flat = (v, z) => sub(v, z.map((x) => x * dot(v, z))), len = (v) => Math.hypot(...v);
380
+ const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v)); // radians
381
+ list.forEach((g, n) => {
382
+ 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; };
383
+ const idx = { sun: index(g.sun, 'sun'), carrier: index(g.carrier, 'carrier'), ring: index(g.ring, 'ring') };
384
+ const planets = [].concat(g.planets || []).map((id) => index(id, 'planet'));
385
+ if (!planets.length) throw new Error(`${what}: planets names the planet items`);
386
+ const jointOf = (k) => joints.find((j) => j.child === k), moving = (k) => { const j = jointOf(k); return j && j.type !== 'fixed' ? j : null; };
387
+ const held = ['sun', 'carrier', 'ring'].filter((m) => !moving(idx[m]));
388
+ 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'})`);
389
+ const drive = g.drive ?? ['carrier', 'sun', 'ring'].find((m) => m !== held[0]);
390
+ 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]})`);
391
+ const third = ['sun', 'carrier', 'ring'].find((m) => m !== held[0] && m !== drive), lead = moving(idx[drive]), follower = moving(idx[third]);
392
+ 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})`);
393
+ 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`);
394
+ 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; });
395
+ const teeth = [].concat(g.teeth || []).map(num);
396
+ if (teeth.length !== 3) throw new Error(`${what}: teeth is [sun, planet, ring] (got ${JSON.stringify(g.teeth)})`);
397
+ const [S, P, R] = teeth, common = { module: num(g.module), ...(g.pressureAngle != null ? { pressureAngle: num(g.pressureAngle) } : {}), ...(g.backlash != null ? { backlash: num(g.backlash) } : {}) };
398
+ let sun, planet, ring;
399
+ try { sun = gearModel({ ...common, teeth: S }); planet = gearModel({ ...common, teeth: P }); ring = internalModel({ ...common, teeth: R }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
400
+ 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})`);
401
+ // Every part where it is with these joints at 0
402
+ const v = jointValues({ joints, poses: {} }, {});
403
+ for (const j of [lead, follower, ...planetJoints]) v[j.id] = [0];
404
+ const worlds = placeItems({ items, joints }, v), W = (k) => worlds[k];
405
+ const O = org(W(idx.sun)), Z = col(W(idx.sun), 2), X0 = col(W(idx.sun), 0);
406
+ 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));
407
+ 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`); }
408
+ const gr = ang(flat(col(W(idx.ring), 0), Z), X0, Z) * (dot(col(W(idx.ring), 2), Z) > 0 ? 1 : -1);
409
+ // planet k: where it sits (its centre's angle round the sun) and which way its first tooth points
410
+ 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]) }; });
411
+ // One configuration that meshes, everything at its zero: planet 0 in phase with the ring, the sun with planet 0
412
+ 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);
413
+ // Willis on rotations from the zero (sun σ, carrier κ, ring ρ): σ − κ + (R/S)(ρ − κ) = σ0
414
+ const coef = { sun: 1, carrier: -(1 + R / S), ring: R / S };
415
+ const sg = { [drive]: sign(lead), [third]: sign(follower) };
416
+ // the third's rotation for the driver's: from the relation, with the held one still
417
+ const rot = (d) => { const r = { [held[0]]: 0, [drive]: sg[drive] * d }; r[third] = (sigma0 - coef[drive] * r[drive]) / coef[third]; return r; };
418
+ // a straight line in the driver's value (f: degrees in, radians out): [ratio, offset in degrees]
419
+ const lin = (f) => { const a = f(0), b = f(1); return [(b - a) / DEG, a / DEG]; };
420
+ const [k3, o3] = lin((d) => sg[third] * rot(d * DEG)[third]);
421
+ follower.follow = [lead.id, k3, o3];
422
+ const findings = [], f = (level, text, code, between) => findings.push({ level, text, code, ...(between ? { between } : {}) });
423
+ pl.forEach((p, i) => {
424
+ // the planet's first tooth from the sun's mesh: π = −(S/P) σ + β (1 + S/P) + π − π/P, β the planet's place
425
+ 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; };
426
+ const [kp, op] = lin((d) => p.s * (tooth(d) - p.gamma - rot(d * DEG).carrier));
427
+ p.joint.follow = [lead.id, kp, op];
428
+ // and with the ring: in phase with it too, or it can't go there
429
+ const ringTooth = (P / R) * tooth(0) + p.beta * (1 - P / R) - Math.PI / R, pitch = (2 * Math.PI) / R;
430
+ const miss = (((ringTooth - gr) % pitch) + pitch * 1.5) % pitch - pitch / 2;
431
+ const centre = org(W(planets[i]));
432
+ 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]);
433
+ const m = meshOf(sun, planet, { centre: p.r });
434
+ for (const x of m.findings) f(x.level, `sun and ${p.id}: ${x.text}`, x.code, [O, centre]);
435
+ });
436
+ 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'}`;
437
+ out.push({ joint: follower.id, with: lead.id, kind: 'planetary', text: ratioText, findings, between: [O, O], planetary: true });
438
+ });
439
+ return out;
440
+ }
441
+
442
+ // Gears that mesh: "mesh": { "with": <the driving joint>, "module", "teeth": [its, this one's], "shift"?, "ring"? } on
443
+ // a revolute (a gear, or a ring with "ring": true) or a prismatic (a rack). It becomes a follow: the ratio from the
444
+ // teeth, and the offset that puts a tooth in a gap, read from where the two gears are with their joints at 0. Each
445
+ // gear is drawn as @rulecad/gears draws it (its axis up its own z, its first tooth on +x; a rack along its x, teeth up
446
+ // +y, its first space at x = 0), and its joint turns it about its own axis. The centre distance is checked here, the
447
+ // rest of the meshing by --sweep.
448
+ function gearMeshes(joints, items, num) {
449
+ const out = [], list = (x) => (x == null ? [] : [].concat(x));
450
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
451
+ 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]];
452
+ 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]];
453
+ const along = (v, axis) => sub(v, axis.map((x) => x * dot(v, axis))), len = (v) => Math.hypot(...v);
454
+ const angleIn = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v)) / (Math.PI / 180); // v's angle from x0 about z, degrees
455
+ // Is an item held still relative to another: every joint between it and the world fixed (or no joint at all)?
456
+ const byChild = new Map(joints.map((j) => [j.child, j]));
457
+ const still = (i) => { for (let k = i, n = 0; k >= 0 && n < 99; n++) { const j = byChild.get(k); if (!j) return true; if (j.type !== 'fixed') return false; k = j.parent; } return true; };
458
+ for (const j of joints) {
459
+ if (!j.meshSpec) continue;
460
+ const spec = j.meshSpec, what = `joint ${j.id}: mesh`;
461
+ delete j.meshSpec;
462
+ if (j.follow) throw new Error(`${what}: a meshed joint follows its mate already: give mesh or follow, not both`);
463
+ const lead = joints.find((x) => x.id === spec.with);
464
+ 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)})`);
465
+ if (lead.type !== 'revolute') throw new Error(`${what}: ${lead.id} is a ${lead.type}; the driver is a gear turning on a revolute`);
466
+ 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})`);
467
+ const kind = j.type === 'prismatic' ? 'rack' : spec.ring ? 'internal' : 'external';
468
+ 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`);
469
+ const teeth = list(spec.teeth).map(num), shift = list(spec.shift ?? [0, 0]).map(num);
470
+ if (teeth.length !== 2) throw new Error(`${what}: teeth is [the driver's, this one's] (got ${JSON.stringify(spec.teeth)})`);
471
+ const common = { module: num(spec.module), ...(spec.pressureAngle != null ? { pressureAngle: num(spec.pressureAngle) } : {}), ...(spec.backlash != null ? { backlash: num(spec.backlash) } : {}) };
472
+ let A, B;
473
+ try {
474
+ A = gearModel({ ...common, teeth: teeth[0], shift: shift[0] });
475
+ B = kind === 'rack' ? rackModel({ ...common, teeth: teeth[1] }) : (kind === 'internal' ? internalModel : gearModel)({ ...common, teeth: teeth[1], shift: shift[1] ?? 0 });
476
+ } catch (e) { throw new Error(`${what}: ${e.message}`); }
477
+ // Where the two gears are with their own joints at 0 (everything else as it stands by default)
478
+ const v = jointValues({ joints: joints.map((x) => (x.meshSpec ? { ...x, meshSpec: undefined } : x)), poses: {} }, {});
479
+ v[lead.id] = [0]; v[j.id] = [0];
480
+ const worlds = placeItems({ items, joints }, v), W1 = worlds[lead.child], W2 = worlds[j.child];
481
+ const axisOf = (jt) => { const P = mul(jt.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[jt.parent], jt.a); return { at: org(P), dir: col(P, 2) }; };
482
+ const O1 = org(W1), X1 = col(W1, 0), Z1 = col(W1, 2), ax1 = axisOf(lead);
483
+ // the driver turns about its own centre and axis, or its teeth wander
484
+ if (Math.abs(Math.abs(dot(ax1.dir, Z1)) - 1) > 1e-6 || len(along(sub(O1, ax1.at), ax1.dir)) > 1e-4) throw new Error(`${what}: ${lead.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`);
485
+ const result = { joint: j.id, with: lead.id, kind, findings: [], between: null };
486
+ if (kind === 'rack') {
487
+ const R0 = org(W2), U = col(W2, 0), Y = col(W2, 1), Zr = col(W2, 2), ax2 = axisOf(j);
488
+ const sTravel = Math.sign(dot(ax2.dir, U));
489
+ if (Math.abs(Math.abs(dot(ax2.dir, U)) - 1) > 1e-6) throw new Error(`${what}: ${j.id} doesn't slide the rack along its length (the rack's x)`);
490
+ if (Math.abs(Math.abs(dot(Z1, Zr)) - 1) > 1e-6) throw new Error(`${what}: the pinion's axis isn't across the rack (along the rack's z)`);
491
+ const s1 = Math.sign(dot(Z1, Zr)), rel = sub(O1, R0), at = dot(rel, U), height = dot(rel, Y);
492
+ const k = (Math.PI * A.pitch) / 360, g1 = angleIn(along(X1, Zr), U, Zr);
493
+ j.follow = [lead.id, sTravel * s1 * k, sTravel * (k * g1 + rackPhase(A, at))];
494
+ const m = meshOf(A, B, { centre: height });
495
+ 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;
496
+ } else {
497
+ const O2 = org(W2), X2 = col(W2, 0), Z2 = col(W2, 2), ax2 = axisOf(j);
498
+ 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`);
499
+ 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)`);
500
+ 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);
501
+ const m = meshOf(A, B, { centre: len(d) });
502
+ // 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)
503
+ j.follow = [lead.id, s * m.ratio, s * (phase(A, B, beta) - g2)];
504
+ result.findings = m.findings; result.between = [O1, O2]; result.text = m.text;
505
+ }
506
+ out.push(result);
507
+ }
508
+ return out;
362
509
  }
363
510
 
364
511
  // Where each item's anchors are in a pose: [{ id: 'keyboard@pivot', item, at: [x, y, z] }]
@@ -375,8 +522,22 @@ export { closest };
375
522
 
376
523
  // How much two parts overlap (mm³), from JSCAD's intersection.
377
524
  export function overlap(ga, gb) {
378
- const v = jscad.measurements.measureVolume(jscad.booleans.intersect(ga, gb));
379
- return Math.abs(v) < 1e-6 ? 0 : Math.abs(v);
525
+ const fell = solid?.stats.fallbacks ?? 0;
526
+ const v = Math.abs(jscad.measurements.measureVolume((solid ? solid.intersect : jscad.booleans.intersect)(ga, gb)));
527
+ if (v < 1e-6) return 0;
528
+ // JSCAD's answer (no Manifold, or a shape Manifold couldn't read): only if their surfaces really cross, which fit
529
+ // says exactly (slower, so only here)
530
+ 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; }
531
+ return v;
532
+ }
533
+ // How overlaps are measured: whether the surfaces cross, exactly (fit), and then how much, with Manifold where it's
534
+ // installed. JSCAD's intersection misreads faces that come near without touching: two gears 0.07 mm apart (their
535
+ // 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³.
536
+ // Manifold is exact; a shape it can't read as a closed solid falls back to JSCAD's for that pair.
537
+ let solid = null, tried = false;
538
+ async function measurer() {
539
+ if (tried) return; tried = true;
540
+ try { solid = await booleans('manifold'); } catch { solid = null; } // (without manifold-3d, JSCAD's, as before)
380
541
  }
381
542
 
382
543
  // Overlaps between placed parts, remembered across runs (.cache/overlaps.json): a part is its build (the build cache's
@@ -387,7 +548,7 @@ function pairOverlap(pa, pb) {
387
548
  if (!pa.hash || !pb.hash) return overlap(pa.geometry, pb.geometry);
388
549
  remembered ||= (() => { try { return JSON.parse(host.readText(OVERLAPS)); } catch { return {}; } })();
389
550
  const at = (p) => `${p.hash}@${Array.from(p.m || []).map((x) => Math.round(x * 1e6) / 1e6).join(',')}`;
390
- const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`${x}|${y}`).digest('hex');
551
+ const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`crossing+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
391
552
  if (!(k in remembered)) { remembered[k] = overlap(pa.geometry, pb.geometry); fresh++; }
392
553
  return remembered[k];
393
554
  }
@@ -506,6 +667,14 @@ export function checkAssembly(s) {
506
667
  }
507
668
  if (outside.length) f('fail', `joints out of range: ${outside.join(', ')}`, `${outside.length} joints out of range`, { code: 'joint.range', refs: { joints: outside } });
508
669
  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 } });
670
+ // Gears: each mesh's centre distance and contact ratio, said between the two axes (the rest by --sweep)
671
+ for (const g of s.motion.meshes || []) {
672
+ f('info', g.planetary ? g.text : `${g.with} drives ${g.joint}: ${g.text}`, null, { code: 'mesh.ratio', refs: { joints: [g.with, g.joint] } });
673
+ for (const x of g.findings) {
674
+ const between = x.between || g.between, mid = between[0].map((v, k) => (v + between[1][k]) / 2);
675
+ 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] } });
676
+ }
677
+ }
509
678
  }
510
679
  // Plates print everything: no references
511
680
  if (s.a.kind === 'plate') {
package/lib/design.mjs CHANGED
@@ -32,6 +32,7 @@ import { readLayout, hasLayout, keys, width, depth } from './layout.mjs';
32
32
  import { optimised, forDesign } from './optimise.mjs';
33
33
  import * as shapes from '@rulecad/shapes';
34
34
  import * as flexures from '@rulecad/flexures';
35
+ import * as gears from '@rulecad/gears';
35
36
  import { engineId, packageVersion, materialise } from './versions.mjs';
36
37
  import { satisfies } from '@rulecad/versions';
37
38
 
@@ -125,11 +126,11 @@ const CACHE = paths.cache('builds'), CACHE_VERSION = 3;
125
126
  const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
126
127
  // What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
127
128
  // boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
128
- const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures')));
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')));
129
130
  // (every module of a helper package but its tests: they change nothing a design builds)
130
131
  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('');
131
132
  const feaDir = path.dirname(createRequire(pathToFileURL(path.join(flexuresDir, 'package.json')).href).resolve('@rulecad/fea')); // (flexures' own, wherever npm put it)
132
- const own = source(import.meta.url) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(feaDir) + packageVersion('@jscad/modeling'); // every shapes module, not just its entry
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
133
134
  // A lamina's slow stages (the physics, the flood's probe) are kept apart from the builds, keyed by the library's code
134
135
  // and their own inputs, so a build that changes only what comes after them (a strap, a check, a rule's words) has them
135
136
  // at once: .cache/stages/. A design in the sandbox can't write them, so the sandbox hands them back and the tool writes them
@@ -219,7 +220,7 @@ export async function build(d, set = {}, { mirror = false } = {}) {
219
220
  throw syntaxAt(located(e, d.js, 'design.run'), d);
220
221
  });
221
222
  if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
222
- const w = watch(values, { shapes, flexures, ops: await shapes.ops(booleans(object)), ...(pcb ? { pcb } : {}) }, optional);
223
+ const w = watch(values, { shapes, flexures, gears, ops: await shapes.ops(booleans(object)), ...(pcb ? { pcb } : {}) }, optional);
223
224
  read = w.read;
224
225
  let made;
225
226
  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 }); }
@@ -1,11 +1,11 @@
1
- // The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures 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 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'];
8
+ const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears'];
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)
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import * as shapes from '@rulecad/shapes';
6
6
  import * as flexures from '@rulecad/flexures';
7
+ import * as gears from '@rulecad/gears';
7
8
  import { named, faces, unpack, watch } from './parts.mjs';
8
9
  import { lineOf } from './errors.mjs';
9
10
 
@@ -27,7 +28,7 @@ console.log = console.info = console.debug = (...a) => console.error(...a);
27
28
  try {
28
29
  const mod = await import(js);
29
30
  if (typeof mod.main !== 'function') throw Object.assign(new Error('the design has no exported main(v)'), { code: 'design.main' });
30
- const { v, read } = watch(values, { shapes, flexures, ops: await shapes.ops(engine || 'jscad') }, optional);
31
+ const { v, read } = watch(values, { shapes, flexures, gears, ops: await shapes.ops(engine || 'jscad') }, optional);
31
32
  const { shapes: made, mechanism } = unpack(await mod.main(v));
32
33
  const parts = named(made, meta).map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) }));
33
34
  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/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
43
+ ...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@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.33",
3
+ "version": "0.7.35",
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": {
@@ -69,7 +69,8 @@
69
69
  "three": "^0.186.1",
70
70
  "@rulecad/fea": "^0.2.1",
71
71
  "@rulecad/topopt": "^0.3.0",
72
- "@rulecad/flexures": "^0.5.0"
72
+ "@rulecad/flexures": "^0.5.0",
73
+ "@rulecad/gears": "^0.2.0"
73
74
  },
74
75
  "peerDependencies": {
75
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
  },
@@ -100,7 +101,38 @@
100
101
  "ratio": { "$ref": "#/$defs/expr" },
101
102
  "offset": { "$ref": "#/$defs/values" },
102
103
  "path": { "type": "array", "items": { "$ref": "#/$defs/vec3" } },
103
- "cone": { "$ref": "#/$defs/expr" }
104
+ "cone": { "$ref": "#/$defs/expr" },
105
+ "mesh": {
106
+ "type": "object",
107
+ "description": "Gears: this joint's gear meshes with the gear on the joint named by with, which drives it",
108
+ "required": ["with", "module", "teeth"],
109
+ "additionalProperties": false,
110
+ "properties": {
111
+ "with": { "type": "string" },
112
+ "module": { "$ref": "#/$defs/expr" },
113
+ "teeth": { "type": "array", "minItems": 2, "maxItems": 2, "items": { "$ref": "#/$defs/expr" } },
114
+ "shift": { "type": "array", "minItems": 2, "maxItems": 2, "items": { "$ref": "#/$defs/expr" } },
115
+ "pressureAngle": { "$ref": "#/$defs/expr" },
116
+ "backlash": { "$ref": "#/$defs/expr" },
117
+ "ring": { "type": "boolean" }
118
+ }
119
+ }
120
+ }
121
+ },
122
+ "planetary": {
123
+ "type": "object",
124
+ "description": "A planetary gearbox: one of sun, carrier and ring held, the one named by drive turning, the rest following it in phase",
125
+ "required": ["sun", "carrier", "ring", "planets", "module", "teeth"],
126
+ "additionalProperties": false,
127
+ "properties": {
128
+ "sun": { "type": "string" }, "carrier": { "type": "string" }, "ring": { "type": "string" },
129
+ "planets": { "type": "array", "minItems": 1, "items": { "type": "string" } },
130
+ "drive": { "enum": ["sun", "carrier", "ring"] },
131
+ "module": { "$ref": "#/$defs/expr" },
132
+ "teeth": { "type": "array", "minItems": 3, "maxItems": 3, "items": { "$ref": "#/$defs/expr" } },
133
+ "pressureAngle": { "$ref": "#/$defs/expr" },
134
+ "backlash": { "$ref": "#/$defs/expr" },
135
+ "note": { "type": "string" }
104
136
  }
105
137
  },
106
138
  "loop": {