@rulecad/cad 0.7.34 → 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, 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
@@ -519,3 +519,213 @@ carries the knob as a slider, with the rack moving with it: `npx cad link home/s
519
519
 
520
520
  To see the gears' geometry, `@rulecad/gears/diagram` draws a pair the way a textbook does: pitch and base circles,
521
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
@@ -368,7 +368,14 @@ then y, then z, as `rotate` does.
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
369
  contact ratio and the centre distance (`mesh.centre`: closer than the gears need jams them, further adds backlash),
370
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.
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.
372
379
  - **Loops:** each item has one joint to its parent. Where parts join in a ring (two links between the same two
373
380
  parts), let joints place every part, then name the meeting that closes the ring in `loops`. The check measures it
374
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,10 +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
32
  import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase } from '@rulecad/gears';
33
+ import { ops as booleans } from '@rulecad/shapes';
33
34
 
34
35
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
35
36
  export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
@@ -57,6 +58,7 @@ export { satisfies }; // from @rulecad/versions
57
58
  // overrides: { itemId: { variable: value } }, set on this assembly's items by the assembly that uses it.
58
59
  // opts: { mirror: true } builds each object with its mirror settings (cad show).
59
60
  export async function buildAssembly(ref, stack = [], overrides = {}, opts = {}) {
61
+ await measurer();
60
62
  const outer = overrides;
61
63
  const [project, name] = ref.split('/');
62
64
  if (stack.includes(ref)) throw new Error(`assembly ${ref} contains itself (${[...stack, ref].join(' → ')})`);
@@ -349,7 +351,7 @@ function motionOf(a, placed, num, ref) {
349
351
  // A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
350
352
  return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
351
353
  });
352
- const meshes = gearMeshes(joints, items, num);
354
+ const meshes = [...gearMeshes(joints, items, num), ...planetaries(a.planetary || [], joints, items, num)];
353
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]) => {
354
356
  if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
355
357
  return [id, Array.isArray(v) ? v.map(num) : num(v)];
@@ -364,6 +366,79 @@ function motionOf(a, placed, num, ref) {
364
366
  return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes };
365
367
  }
366
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
+
367
442
  // Gears that mesh: "mesh": { "with": <the driving joint>, "module", "teeth": [its, this one's], "shift"?, "ring"? } on
368
443
  // a revolute (a gear, or a ring with "ring": true) or a prismatic (a rack). It becomes a follow: the ratio from the
369
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
@@ -447,8 +522,22 @@ export { closest };
447
522
 
448
523
  // How much two parts overlap (mm³), from JSCAD's intersection.
449
524
  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);
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)
452
541
  }
453
542
 
454
543
  // Overlaps between placed parts, remembered across runs (.cache/overlaps.json): a part is its build (the build cache's
@@ -459,7 +548,7 @@ function pairOverlap(pa, pb) {
459
548
  if (!pa.hash || !pb.hash) return overlap(pa.geometry, pb.geometry);
460
549
  remembered ||= (() => { try { return JSON.parse(host.readText(OVERLAPS)); } catch { return {}; } })();
461
550
  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');
551
+ const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`crossing+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
463
552
  if (!(k in remembered)) { remembered[k] = overlap(pa.geometry, pb.geometry); fresh++; }
464
553
  return remembered[k];
465
554
  }
@@ -580,10 +669,10 @@ export function checkAssembly(s) {
580
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 } });
581
670
  // Gears: each mesh's centre distance and contact ratio, said between the two axes (the rest by --sweep)
582
671
  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] } });
672
+ f('info', g.planetary ? g.text : `${g.with} drives ${g.joint}: ${g.text}`, null, { code: 'mesh.ratio', refs: { joints: [g.with, g.joint] } });
584
673
  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] } });
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] } });
587
676
  }
588
677
  }
589
678
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.34",
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": {
@@ -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.2.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
  },
@@ -118,6 +119,22 @@
118
119
  }
119
120
  }
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" }
136
+ }
137
+ },
121
138
  "loop": {
122
139
  "type": "object",
123
140
  "required": ["a", "b"],