@rulecad/cad 0.7.67 → 0.7.68

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/CHANGELOG.md CHANGED
@@ -5,6 +5,45 @@ print (a hole's diameter, a seat's depth, a part's outline). Each release lists
5
5
  its reason. A **fasten** is an entry in an assembly's `"fasten"` list: one screwed joint, naming the screw by thread
6
6
  and head, the parts it passes through and the part it ends in.
7
7
 
8
+ ## 0.7.68: the actuator printed in place (#162)
9
+
10
+ ### Added
11
+
12
+ - `"printInPlace": true` on an object (#162): its parts print together in the pose they are drawn in and move apart
13
+ once freed. `cad check` (and the check before `cad release`) adds `inplace.bed` (each part has a face of its own on
14
+ the bed), `inplace.gap` (every two parts stand the printer's `print_gap` apart, measured by Manifold through
15
+ @rulecad/shapes' new `ops.gap`) and `inplace.support` (a bridge wider than the printer's `bridge`, an underside in
16
+ mid-air or printed onto another part, a ledge or an island fails, since no support can come out from between the
17
+ parts). This is the bridge-span finding #133 asked for. `inplace.first-layer` holds every two parts on the bed
18
+ to `print_gap` and twice the printer's `foot` half a layer up, where the first layer spreads (printcheck's first-layer
19
+ check looks inside one part at a time, so it never saw two parts printed in place side by side).
20
+ - `"printInPlace": [items]` on an assembly: the items printed together as one object printed in place. The assembly
21
+ order never takes them apart from each other (before, a planet enclosed by the rings it was printed inside was
22
+ `assembly.order`'s "can't be reached in any order"). A name that isn't an item is refused by name. `cad order`
23
+ gives them as one step ("printed together in place (one print)") and `cad list` as one printed row, their grams and
24
+ print minutes added, where each was a step and a print of its own.
25
+ - A motor item's `"screw"` may name a whole screw, thread, length and head (`"M3x8 hex"`): `cad list` buys that screw
26
+ and `cad order` names the tool its head takes (a 5.5 mm socket or spanner on an M3 hexagon head, ISO 4017), where
27
+ every motor's screws were cap screws turned with a hex key.
28
+ - A `"shaft": "slide"` fit holds the bore to a slide fit as printed (`shaft.slide`): the drawn gap less half the
29
+ printer's `hole_comp` must clear the shaft. A slide fit is never pressed on, so it has no hoop check. The shaft fits
30
+ now read `hole_comp` from the assembly's printer rules (0.1 mm on the X1C, as before).
31
+
32
+ ### Fixed
33
+
34
+ - A compound planetary whose planets mesh the output ring only a tooth of their first step on (sun 18, planets 21/18,
35
+ rings 60 and 57) failed `planetary.phase` for every planet but the first, and drew them into the output ring. Each
36
+ planet now takes the first tooth of its first step that meshes the output ring as well as the sun and the held ring.
37
+ Chapter 11's planets take the tooth they always did.
38
+ - The assembly order ran out of stack on a part of a few hundred thousand faces (the middle of its box was found by
39
+ spreading every corner into `Math.min`).
40
+
41
+ ### The print-in-place actuator (examples/bench/projects/benchmarks)
42
+
43
+ - `shoulder-pip`, the bench shoulder printed in one piece on a 17HS4401 (44.3:1), its parts drawn by
44
+ `shoulder-pip-parts.js` from the numbers in `pip`, and `shoulder-pip-drive`, the assembly that turns it, beside
45
+ `shoulder-test`, the assembled 38:1. New objects only: no printed size of an existing part moved.
46
+
8
47
  ## 0.7.67: the leg on the parts its builder has
9
48
 
10
49
  ### Changed
package/README.md CHANGED
@@ -631,9 +631,9 @@ An item can be a motor instead of a printed object: `{ "id": "drive", "motor": {
631
631
  - A stepper's torque at speed is worked out at its driver's supply: the volts of the assembly's bought supply item (`supply-12v`, `supply-24v`), or 24 V where it has none. A stepper's torque is flat to its corner speed, 60 V / (2 L I × full steps a turn), and falls as one over the speed past it, so a 17HS4401 at 300 rpm gives 0.269 N m at full current on 12 V against 0.283 on 24 V. `motor.torque` says the volts and the rpm it read (`values.supply`, `values.rpm`).
632
632
  - `"have": true` on a motor or bought item marks it as in hand: `cad list` lists it under `Bought, in hand`, apart from what is to buy (and leaves it out of the bought cost), the kit's `buy.csv` gives it the kind `in hand`, and its build page a table of its own. A printed item is refused.
633
633
  - `motor.holds`: with the power on (holding torque, or stall torque) and off (detent torque, a built-in gearbox's friction, a worm that locks, gears under 50% efficient, or `"brake": "a ratchet and pawl"` on the joint). Dropping with the power off is a warning: it may be what you want.
634
- - `motor.mount`: the part a motor is fastened to (a `fasten` into the motor, or a fit that `fastens`), read as drawn: how thick it is at the screw holes against the screws' size, the screws' engagement in the motor's tapped holes (the screws as bought: their length past the plate, held to the motor's `mount_hole_depth`, at least one diameter, `engagement.steel`, or it fails; a motor item's `"screw"` may name a whole screw, `"M3x8 cap"`, to check that one), and the screws' bearing on the plastic under the motor's full torque. Its screws are counted in `cad list` and `cad order` (at the length sold that stays in the motor's thread, with the key that turns them). Then the whole part bent, by FE on the part as drawn (cubes, two across the plate at the screws): the motor's weight at its centre, along `gravity` in the pose it's checked in, and its full torque (the larger of its working and holding torque), both carried into the plate where the screws clamp it. The part is held at the joint that carries it, if one does; else where it meets the printed parts it's fastened to that sit below it; failing both, on its lowest face. It reports how far the shaft's tip moves (against the driven joint's seat, where that is on the same part, since the two move together), against the printer's `fit` clearance (or the motor's `"deflection"` in mm), and the peak stress against the material's `strength`; under 2 times either fails, and says what fixes it: the plate thickness that would do (bending goes with its cube), ribs, or how much stiffer a material would have to be. Cells this coarse read a plate 10 to 20% stiff, and a cell's stress is read at its centre, so the peak is scaled up to the surface; it's an estimate, said as one. Kept in `.cache/mount`.
634
+ - `motor.mount`: the part a motor is fastened to (a `fasten` into the motor, or a fit that `fastens`), read as drawn: how thick it is at the screw holes against the screws' size, the screws' engagement in the motor's tapped holes (the screws as bought: their length past the plate, held to the motor's `mount_hole_depth`, at least one diameter, `engagement.steel`, or it fails; a motor item's `"screw"` may name a whole screw, `"M3x8 cap"`, to check that one), and the screws' bearing on the plastic under the motor's full torque. Its screws are counted in `cad list` and `cad order` (at the length sold that stays in the motor's thread, with the tool that turns them: a hex key in a cap screw, a socket or spanner on a hexagon head, `"M3x8 hex"`). Then the whole part bent, by FE on the part as drawn (cubes, two across the plate at the screws): the motor's weight at its centre, along `gravity` in the pose it's checked in, and its full torque (the larger of its working and holding torque), both carried into the plate where the screws clamp it. The part is held at the joint that carries it, if one does; else where it meets the printed parts it's fastened to that sit below it; failing both, on its lowest face. It reports how far the shaft's tip moves (against the driven joint's seat, where that is on the same part, since the two move together), against the printer's `fit` clearance (or the motor's `"deflection"` in mm), and the peak stress against the material's `strength`; under 2 times either fails, and says what fixes it: the plate thickness that would do (bending goes with its cube), ribs, or how much stiffer a material would have to be. Cells this coarse read a plate 10 to 20% stiff, and a cell's stress is read at its centre, so the peak is scaled up to the surface; it's an estimate, said as one. Kept in `.cache/mount`.
635
635
  - `motor.heat`: the motor's case against the softening point of the material the project prints in. Too hot says the current to set the driver to; the motor item's `current` set to it is read (the maker's rise at rated current, scaled by the current squared, as the heat is), so the check then passes.
636
- - A `"shaft": true` fit (or `"press"`) between a motor and what it drives reads the bore from the part as drawn: that it's on the shaft (`shaft.seat`), that its flat is there (`shaft.flat`; the shaft turns to meet it, so where the flat faces doesn't matter), how much of the flat it grips (`shaft.grip`), and, pressed on, the hoop stress in the hub (`shaft.hoop`).
636
+ - A `"shaft": true` fit (or `"press"`) between a motor and what it drives reads the bore from the part as drawn: that it's on the shaft (`shaft.seat`), that its flat is there (`shaft.flat`; the shaft turns to meet it, so where the flat faces doesn't matter), how much of the flat it grips (`shaft.grip`), and, pressed on, the hoop stress in the hub (`shaft.hoop`). `"slide"` holds the bore to a slide fit as printed (`shaft.slide`): the drawn gap less half the printer's `hole_comp` must leave the shaft clear, as a part printed in place needs, since it can't be pressed on.
637
637
  - `cad preview --check` of an assembly with a motor writes `<assembly>-check.png`: the same six views, with a label at each joint the motor's torque passes through (what reaches it, and at the loaded joint the margin and whether it holds unpowered). The rest view never carries them.
638
638
  - `cad preview` of an assembly with a motor draws each one at work beside the picture, as SVG: `<assembly>-<motor>-curve.svg`, its torque against speed at the output with the load and the working speed marked, and `<assembly>-<motor>-train.svg`, the torque from its shaft through each stage to the joint with the load, against what the load needs there, and whether it holds with the power on and off. The numbers are the check's.
639
639
 
@@ -1660,6 +1660,30 @@ nothing jams, that its catches hold, and that every flexure has a hard stop befo
1660
1660
  moving bodies in blue and the flexures in orange, drawn bent, holding a moment at each state. Under it, each driven step's force against its travel, with a marker that follows the frames; a mechanism that fires adds the shot in slow motion. The printer's
1661
1661
  `print_gap` is the gap the checks hold it to.
1662
1662
 
1663
+ ## Parts printed in place
1664
+
1665
+ An object with `"printInPlace": true` is printed as one, its parts in the pose they're drawn in, and they move apart
1666
+ once freed with a turn by hand (a gearbox printed whole: @rulecad/gears' `compoundPlanetary({ printInPlace: true })`
1667
+ draws its teeth for it). Its parts are named (`return { housing, sun, planet_a, output }`), and `cad check` adds three
1668
+ checks to the print checks:
1669
+
1670
+ - `inplace.bed`: each part has a face of its own on the bed, 1 mm² or more. A part that starts on another is printed
1671
+ onto it and fuses.
1672
+ - `inplace.gap`: every two parts stand the printer's `print_gap` apart or more, measured by Manifold (the nearest pair
1673
+ and its gap on a pass, each pair too near on a fail). The first layer, where the plastic spreads by the printer's
1674
+ `foot`, is printcheck's `print.first-layer`.
1675
+ - `inplace.first-layer`: on the bed, every two parts stand `print_gap` and twice the printer's `foot` apart, measured
1676
+ half a layer up, where the first layer spreads as it is squashed on.
1677
+ - `inplace.support`: nothing needs a support, since none can come out from between parts that enclose each other. A
1678
+ bridge wider than the printer's `bridge`, an underside in mid-air or printed onto the part below, a ledge or an
1679
+ island fails here, where a part printed alone gets a warning.
1680
+
1681
+ The gaps need `manifold-3d` in the workspace (`"engine": "manifold"` objects have it already). To move the parts in
1682
+ an assembly, draw each as an object of its own from the same numbers (the bench's `shoulder-pip-*` objects share a
1683
+ module and read `pip`'s variables) and name them in the assembly's `"printInPlace": [items]`: they came off the bed
1684
+ together, so the assembly order never takes them apart from each other. `cad order` fits them as one step and
1685
+ `cad list` gives them one printed row, the one print's grams and minutes.
1686
+
1663
1687
  An assembly with a `gait` (EXAMPLES chapter 14) plays too: `cad animate <project>/<assembly>` writes the cycle as an animated SVG in `.preview/` (a side view of the legs and a plan of the feet and what they stand on) and its data as JSON. The model page plays the same cycle in its Motion panel.
1664
1688
 
1665
1689
  An assembly with a motor, or with gears that follow a joint, plays its drive: `cad animate <project>/<assembly>` writes `<assembly>-drive.svg`, the gears cut across their shafts through their teeth (up to three cuts side by side, a compound planetary's two rings each in its own), each part turning and moving as it does, the part with the load picked out. It turns the drive until the slowest part has moved about 60° (one to six turns; `--turns n` to choose). Each part's outline is drawn once and moved, so a gearbox stays a few hundred kilobytes.
package/bin/cad.mjs CHANGED
@@ -562,7 +562,7 @@ async function main() {
562
562
  : { level: 'pass', text: 'every measurement is a variable', code: 'lint.numbers', refs: { file } },
563
563
  ...(b.object.role === 'reference'
564
564
  ? [{ level: 'pass', text: `a reference (${(await import('@rulecad/printcheck')).bounds(b.triangles).size.map(fmt).join(' × ')} mm), not printed: no print checks`, code: 'print.reference' }]
565
- : check(b.triangles, printer(b, d), { parts: b.parts })),
565
+ : await printChecks(b, d)),
566
566
  ...(b.mechanism?.findings || []), // a lamina mechanism's own: it prints free, stops, holds, clears in every state
567
567
  ...(b.fixings || []), // what v.fixings drew: each hole and seat, what it was drawn to and the rule it rests on
568
568
  ...(await analyses(b, d, tag)),
@@ -968,12 +968,18 @@ function changelog(dir, heading, message, reasons) {
968
968
  return path.relative(WS, f).split(path.sep).join('/'); // (git's terms: forward slashes)
969
969
  }
970
970
 
971
+ // An object's print checks: printcheck's, and for parts printed in place, theirs (lib/inplace.mjs)
972
+ async function printChecks(b, d) {
973
+ const pr = printer(b, d), printed = check(b.triangles, pr, { parts: b.parts });
974
+ return b.object.printInPlace ? [...printed, ...(await (await import('../lib/inplace.mjs')).inPlaceChecks(b, pr, printed))] : printed;
975
+ }
976
+
971
977
  async function releaseObject(d, { batch = false } = {}) {
972
978
  const message = opt('m');
973
979
  if (!message || message === true) throw new Error('say what changed: -m "Wider slot for a looser fit"');
974
980
  const object = readObject(d), b = await build(d);
975
981
  const raw = lint(fs.readFileSync(d.js, 'utf8')), fails = (b.circuit ? await (await pcbEngine()).checks(b.circuit, b.values, b.matrix, b.source) // boards: the board's checks
976
- : b.object.role === 'reference' ? [] : [...check(b.triangles, printer(b, d), { parts: b.parts }), ...(b.mechanism?.findings || [])]).filter((r) => r.level === 'fail'); // references aren't printed; a mechanism's own checks count
982
+ : b.object.role === 'reference' ? [] : [...(await printChecks(b, d)), ...(b.mechanism?.findings || [])]).filter((r) => r.level === 'fail'); // references aren't printed; a mechanism's own checks count
977
983
  if (raw.length || fails.length) throw new Error(`fix the check first: ${[...raw.map((r) => `raw number ${r.text} on line ${r.line}`), ...fails.map((f) => f.text)].join('; ')}`);
978
984
  let { last, kind, reasons } = await since(d);
979
985
  if (!kind) throw new Error(`nothing has changed since ${last.version}`);
package/lib/assembly.mjs CHANGED
@@ -37,7 +37,7 @@ import { DOFS, frame, turn, mul, inv, pathLength, jointValues, placeItems, joint
37
37
  import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase, contact, wormModel, wormMesh, bevelModel, bevelMesh, compoundEfficiency } from '@rulecad/gears';
38
38
  import { ops as booleans } from '@rulecad/shapes';
39
39
  import { motorBuilt, motorDrives, shaftFits, loadsOf, motorChecks, shaftFit, axisOf } from './motors.mjs';
40
- import { runningChecks, seatFit } from './seats.mjs';
40
+ import { runningChecks, seatFit, printerRules } from './seats.mjs';
41
41
  import { seatSize } from '@rulecad/shapes';
42
42
  import { wiresOf, wireChecks } from './wires.mjs';
43
43
  import { printedParts } from './list.mjs';
@@ -242,6 +242,8 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
242
242
  for (const c of copies) { placed.push([it, c]); ids.push(c.id); }
243
243
  }
244
244
  const motion = motionOf(a, placed, num, ref), wires = wiresOf(a, placed, motion.joints), task = taskOf(a, motion, num), gait = gaitOf(a, motion, num);
245
+ // (items printed together in place, which the assembly order never takes apart: each by its id)
246
+ for (const id of a.printInPlace || []) if (!motion.items.some((x) => x[0] === id)) throw new Error(`printInPlace names "${id}", which isn't an item (${motion.items.map((x) => x[0]).join(', ')})`);
245
247
  fits.push(...shaftFits(motion.drives, motion.joints, placed.map(([, c]) => c.id)).map((x) => ({ ...x, num })));
246
248
  for (const [it, c] of placed) {
247
249
  const src = c.src, id = c.id;
@@ -577,7 +579,15 @@ function planetaries(list, joints, items, num) {
577
579
  j2.follow = [lead.id, k, o]; free(j2);
578
580
  const eff = compoundEfficiency({ planet: P, planet2: P2, ring: R, ring2: R2 }), fails = [], ff = (level, text, code) => fails.push({ level, text, code, between: [O, O] });
579
581
  for (const x of meshOf(p2, r2, { centre: pl[0].r }).findings) ff(x.level, `${pl[0].id} and the output ring: ${x.text}`, x.code);
580
- pl.forEach((p, i) => { const t2 = (P2 / R2) * ((-(S / P) * sigma0 + p.beta * (1 + S / P) + Math.PI - Math.PI / P)) + p.beta * (1 - P2 / R2) - ps, pitch2 = (2 * Math.PI) / R2, miss = (((t2 - (P2 / R2) * ((-(S / P) * sigma0 + p0.beta * (1 + S / P) + Math.PI - Math.PI / P)) - p0.beta * (1 - P2 / R2) + ps) % pitch2) + pitch2 * 1.5) % pitch2 - pitch2 / 2; if (Math.abs(miss) > 1e-6) ff('fail', `planet ${p.id} can't mesh with the output ring where it is: every tooth count a multiple of the planets puts them all in phase`, 'planetary.phase'); });
582
+ // Each planet's second step in phase with the output ring. A planet meshes the sun as well a whole tooth of its
583
+ // first step on (2π/P), and that turns its second step too: the first of those turns that puts it in phase with
584
+ // the ring is the one it takes (none, where every planet is in phase as it stands, as chapter 11's are)
585
+ pl.forEach((p, i) => {
586
+ const pitch2 = (2 * Math.PI) / R2, missAt = (m) => { const t2 = (P2 / R2) * ((-(S / P) * sigma0 + p.beta * (1 + S / P) + Math.PI - Math.PI / P + (2 * Math.PI * m) / P)) + p.beta * (1 - P2 / R2) - ps; return (((t2 - (P2 / R2) * ((-(S / P) * sigma0 + p0.beta * (1 + S / P) + Math.PI - Math.PI / P)) - p0.beta * (1 - P2 / R2) + ps) % pitch2) + pitch2 * 1.5) % pitch2 - pitch2 / 2; };
587
+ const m = i === 0 ? 0 : Array.from({ length: P }, (_, k) => k).find((k) => Math.abs(missAt(k)) <= 1e-6);
588
+ if (m == null) ff('fail', `planet ${p.id} can't mesh with the output ring where it is, whichever tooth of its first step meets the sun: every tooth count a multiple of the planets puts them all in phase`, 'planetary.phase');
589
+ else if (m) p.joint.follow = [p.joint.follow[0], p.joint.follow[1], (((p.joint.follow[2] + (p.s * 360 * m) / P + 180) % 360) + 360) % 360 - 180];
590
+ });
581
591
  out.push({ joint: j2.id, with: lead.id, kind: 'planetary', efficiency: eff, text: `the second ring turns ${Number(Math.abs(k).toFixed(5))} of the ${drive}'s turn, ${k * s2 * sg[drive] < 0 ? 'the other way' : 'the same way'} (${Number((1 / Math.abs(k)).toFixed(2))}:1, about ${Math.round(eff * 100)}% efficient, an estimate)`, findings: fails, between: [O, O], planetary: true });
582
592
  }
583
593
  });
@@ -857,7 +867,7 @@ export function checkAssembly(s) {
857
867
  if (x.seat != null) { seatFit(x, s, f, { placeItems, jointValues, mul, seatSize }); continue; }
858
868
  if (x.pin && pinning) pinFit(x); // (and its gap, as any fit's)
859
869
  if (x.magnet && pinning) magnetFit(x);
860
- if (x.shaft != null) { shaftFit(x, s, f, { placeItems, jointValues, mul, materialName: materialOf(s.project) }); continue; }
870
+ if (x.shaft != null) { shaftFit(x, s, f, { placeItems, jointValues, mul, materialName: materialOf(s.project), holeComp: printerRules(s).hole_comp ?? 0.1 }); continue; }
861
871
  const A = pickIn(x.a, x), key = x.note || `${x.a} / ${x.b}`;
862
872
  const lo = x.min != null ? x.num(x.min) : -Infinity, hi = x.max != null ? x.num(x.max) : Infinity;
863
873
  const reach = Math.max(2, ...[lo, hi].filter(Number.isFinite)) + 1; // look past the range, so a gap near it is measured
@@ -0,0 +1,111 @@
1
+ // Parts printed in place: an object ("printInPlace": true) whose parts come off the bed together, in the pose they
2
+ // print in, and move apart once freed with a turn by hand (a gearbox printed whole, a hinge with its pin). What has to
3
+ // hold for that, checked here on the parts as drawn:
4
+ // - each part stands on the bed itself (inplace.bed): a part that starts on another is printed onto it and fuses;
5
+ // - every two parts stand at least the printer's print_gap apart (inplace.gap), measured exactly by Manifold's
6
+ // minGap, and on the first layer, where the plastic spreads by the printer's foot each side as it is squashed on,
7
+ // print_gap and twice the foot (inplace.first-layer: the parts cut at half a layer up, where the spread is);
8
+ // - nothing needs a support (inplace.support): none can come out from between parts that enclose each other, so a
9
+ // bridge wider than the printer spans, an underside in mid-air or on another part, a ledge or an island fails here,
10
+ // where for a part printed alone printcheck only warns.
11
+ import { bounds } from '@rulecad/printcheck';
12
+ import { ops as booleans } from '@rulecad/shapes';
13
+ import jscad from '@jscad/modeling';
14
+
15
+ const mm = (n, d = 2) => `${Number(n.toFixed(d))}`;
16
+ const BED = 1e-3; // mm: a face this near z = 0 is on the bed
17
+ const LEAST_BED = 1; // mm²: a part's footprint on the bed, at least: a point or an edge on it holds nothing
18
+
19
+ // The area of a part's faces lying flat on the bed, facing down
20
+ function onBed(tris) {
21
+ let area = 0;
22
+ for (const t of tris) {
23
+ if (t.some((p) => Math.abs(p[2]) > BED)) continue;
24
+ for (let i = 1; i < t.length - 1; i++) {
25
+ const [a, b, c] = [t[0], t[i], t[i + 1]], z = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
26
+ if (z < 0) area += -z / 2; // (wound clockwise seen from above: facing down)
27
+ }
28
+ }
29
+ return area;
30
+ }
31
+
32
+ // How far apart two boxes are, 0 if they overlap; and the box they share, grown to touch, as where to look
33
+ const boxGap = (a, b) => Math.hypot(...[0, 1, 2].map((k) => Math.max(0, a.lo[k] - b.hi[k], b.lo[k] - a.hi[k])));
34
+ const between = (a, b) => { const lo = [0, 1, 2].map((k) => Math.min(Math.max(a.lo[k], b.lo[k]), Math.min(a.hi[k], b.hi[k]))), hi = [0, 1, 2].map((k) => Math.max(Math.max(a.lo[k], b.lo[k]), Math.min(a.hi[k], b.hi[k]))); return { lo, hi }; };
35
+
36
+ // What printcheck only warns of for a part printed alone, and why each can't be printed in place
37
+ const SUPPORTS = {
38
+ 'print.bridge': 'a bridge wider than the printer spans',
39
+ 'print.mid-air': 'an underside starting in mid-air',
40
+ 'print.ledge': 'a ledge held on one side only',
41
+ 'print.islands': 'a layer with nothing under it',
42
+ 'print.island': 'a point starting in mid-air',
43
+ 'print.overhang.sliced': 'layers out past the overhang limit',
44
+ 'print.breakaway': 'an underside printed onto the part below it',
45
+ };
46
+
47
+ /**
48
+ * The checks for an object printed in place, in the kit's one shape.
49
+ * @param {{ parts: { name: string, role?: string, label?: string, geometry: object, triangles: number[][][] }[] }} b the built object
50
+ * @param {{ print_gap?: number, foot?: number }} printer the printer's rules, as numbers
51
+ * @param {object[]} printed what printcheck found of the object as a whole
52
+ * @param {{ ops?: object }} [o] the booleans to measure with (Manifold's; found if not given)
53
+ * @returns {Promise<object[]>}
54
+ */
55
+ export async function inPlaceChecks(b, printer, printed = [], o = {}) {
56
+ const out = [], f = (level, text, code, extra = {}) => out.push({ level, text, code, ...extra });
57
+ const parts = b.parts.filter((p) => p.role !== 'support'), need = printer.print_gap;
58
+ if (!(typeof need === 'number' && need > 0)) throw new Error(`printInPlace: the printer's print_gap is the gap each side that prints apart, a number above 0 (got ${JSON.stringify(need)}): add it to the printer's rule set`);
59
+ if (parts.length < 2) { f('fail', `printed in place, but ${parts.length ? `only one part (${parts[0].name})` : 'no parts'}: return the parts that move apart as named parts ({ housing, sun, ... }), each described in the .json's parts`, 'inplace.parts'); return out; }
60
+
61
+ // Each on the bed
62
+ const boxes = new Map(parts.map((p) => [p.name, bounds(p.triangles)]));
63
+ const off = [];
64
+ for (const p of parts) { const area = onBed(p.triangles), box = boxes.get(p.name); if (area < LEAST_BED) off.push({ p, area, box }); }
65
+ for (const { p, area, box } of off) f('fail', `${p.name} has ${area > 0 ? `only ${mm(area)} mm²` : 'nothing'} on the bed${box.lo[2] > BED ? ` (its lowest point is ${mm(box.lo[2])} mm up)` : ''}: printed in place, a part that starts on another part is printed onto it and fuses. Give it a face of its own on the bed, slanting at 45° up to the rest of it`, 'inplace.bed', { values: { area, least: LEAST_BED }, at: [(box.lo[0] + box.hi[0]) / 2, (box.lo[1] + box.hi[1]) / 2, box.lo[2]], box, refs: { part: p.name } });
66
+ if (!off.length) f('pass', `each of the ${parts.length} parts stands on the bed (${parts.map((p) => `${p.name} ${mm(onBed(p.triangles), 0)} mm²`).join(', ')})`, 'inplace.bed', { values: { parts: Object.fromEntries(parts.map((p) => [p.name, onBed(p.triangles)])) } });
67
+
68
+ // Every two apart by the print gap, measured by Manifold
69
+ let ops = o.ops;
70
+ if (!ops) { try { ops = await booleans('manifold'); } catch { ops = null; } }
71
+ if (!ops) { f('warn', 'the gaps between the parts are not measured: they need manifold-3d (npm install manifold-3d in the workspace)', 'inplace.gap'); }
72
+ else {
73
+ const within = need + 1, gaps = []; // (looking a millimetre past the gap: a pair further apart reads as that)
74
+ for (let i = 0; i < parts.length; i++) for (let j = i + 1; j < parts.length; j++) {
75
+ const a = parts[i], c = parts[j], ba = boxes.get(a.name), bc = boxes.get(c.name);
76
+ if (boxGap(ba, bc) >= within) continue;
77
+ let gap;
78
+ try { gap = ops.gap(a.geometry, c.geometry, within); } catch (e) { f('warn', `${a.name} and ${c.name}: the gap between them is not measured (${e.message})`, 'inplace.gap', { refs: { parts: [a.name, c.name] } }); continue; }
79
+ gaps.push({ a: a.name, b: c.name, gap, box: between(ba, bc) });
80
+ }
81
+ const near = gaps.filter((g) => g.gap < need - 1e-3).sort((x, y) => x.gap - y.gap);
82
+ for (const g of near) f('fail', `${g.a} and ${g.b} are ${g.gap > 0 ? `${mm(g.gap, 3)} mm apart at their nearest` : 'touching'}, under the ${mm(need)} mm that prints apart (print_gap): printed in place they fuse there. Move them apart, or widen the gap in the design`, 'inplace.gap', { values: { gap: g.gap, need }, at: g.box.lo.map((x, k) => (x + g.box.hi[k]) / 2), box: g.box, refs: { parts: [g.a, g.b] } });
83
+ if (!near.length) {
84
+ const least = gaps.reduce((m, g) => (!m || g.gap < m.gap ? g : m), null);
85
+ f('pass', least ? `every two parts stand ${mm(need)} mm (print_gap) apart or more: the nearest, ${least.a} and ${least.b}, ${mm(least.gap, 3)} mm` : `no two parts come within ${mm(within)} mm of each other`, 'inplace.gap', { values: { gap: least ? least.gap : within, need, pairs: gaps.map(({ a, b: c, gap }) => ({ a, b: c, gap })) }, ...(least ? { refs: { parts: [least.a, least.b] } } : {}) });
86
+ }
87
+ }
88
+
89
+ // On the first layer: the parts as cut half a layer up, apart by the print gap and the spread each side
90
+ const layer = printer.layer ?? 0.2, foot = printer.foot ?? 0, firstNeed = need + 2 * foot;
91
+ if (ops && foot > 0) {
92
+ const slab = (p) => { const bx = boxes.get(p.name); return ops.intersect(p.geometry, jscad.primitives.cuboid({ size: [bx.hi[0] - bx.lo[0] + 2, bx.hi[1] - bx.lo[1] + 2, layer / 2], center: [(bx.lo[0] + bx.hi[0]) / 2, (bx.lo[1] + bx.hi[1]) / 2, layer / 4] })); };
93
+ const low = parts.filter((p) => boxes.get(p.name).lo[2] <= BED).map((p) => ({ name: p.name, g: slab(p), box: boxes.get(p.name) })), near = [];
94
+ let least = null;
95
+ for (let i = 0; i < low.length; i++) for (let j = i + 1; j < low.length; j++) {
96
+ const a = low[i], c = low[j];
97
+ if (boxGap(a.box, c.box) >= firstNeed + 1) continue;
98
+ let gap; try { gap = ops.gap(a.g, c.g, firstNeed + 1); } catch { continue; }
99
+ if (!least || gap < least.gap) least = { a: a.name, b: c.name, gap };
100
+ if (gap < firstNeed - 1e-3) near.push({ a: a.name, b: c.name, gap, box: between(a.box, c.box) });
101
+ }
102
+ for (const g of near) f('fail', `on the first layer, ${g.a} and ${g.b} are ${mm(g.gap, 3)} mm apart half a layer up, under the ${mm(firstNeed)} mm they need there (print_gap and the first layer's ${mm(foot)} mm spread each side): they print as one. Chamfer their bed edges, or move them apart`, 'inplace.first-layer', { values: { gap: g.gap, need: firstNeed }, at: [(g.box.lo[0] + g.box.hi[0]) / 2, (g.box.lo[1] + g.box.hi[1]) / 2, 0], box: { lo: [g.box.lo[0], g.box.lo[1], 0], hi: [g.box.hi[0], g.box.hi[1], layer] }, refs: { parts: [g.a, g.b] } });
103
+ if (!near.length && least) f('pass', `on the first layer, every two parts stand ${mm(firstNeed)} mm apart or more half a layer up (print_gap and the ${mm(foot)} mm spread each side): the nearest, ${least.a} and ${least.b}, ${mm(least.gap, 3)} mm`, 'inplace.first-layer', { values: { gap: least.gap, need: firstNeed }, refs: { parts: [least.a, least.b] } });
104
+ }
105
+
106
+ // Nothing that needs a support
107
+ const needs = printed.filter((x) => SUPPORTS[x.code] && (x.code === 'print.breakaway' ? x.level === 'pass' && x.values?.area > 0 : x.level === 'warn'));
108
+ for (const x of needs) f('fail', `${SUPPORTS[x.code]} (${x.text}): printed in place, no support can come out from between the parts, so it can't be printed. ${x.code === 'print.bridge' ? `Narrow the span to the printer's ${mm(x.values?.max ?? 5)} mm, or slant the underside at 45°` : 'Slant the underside at 45° down to the bed, or give that part a face of its own there'}`, 'inplace.support', { values: { was: x.code, ...(x.values || {}) }, ...(x.at ? { at: x.at } : {}), ...(x.box ? { box: x.box } : {}) });
109
+ if (!needs.length) f('pass', 'nothing needs a support: every bridge within what the printer spans, no underside in mid-air or on another part', 'inplace.support');
110
+ return out;
111
+ }
package/lib/list.mjs CHANGED
@@ -40,9 +40,21 @@ export function printedParts(s) {
40
40
  return [...by.values()].map((o) => ({ ...o, volume: n(o.volume, 0), grams: n((o.volume / 1000) * mat.density), minutes: n(o.volume / flow / 60, 0) }));
41
41
  }
42
42
 
43
+ // The items printed together in place (the assembly's printInPlace) as the one print they are: one row, their grams and
44
+ // the minutes of the whole, in the place of the first of them
45
+ function inPlaceRow(s, printed) {
46
+ const ids = Array.isArray(s.a?.printInPlace) ? s.a.printInPlace : [], members = printed.filter((p) => ids.includes(p.id));
47
+ if (members.length < 2) return printed;
48
+ const mat = materialOf(s.project); let flow = 12;
49
+ try { flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow; } catch {}
50
+ const volume = members.reduce((t, p) => t + p.volume, 0), row = { id: members.map((p) => p.id).join(', '), object: null, volume: n(volume, 0), grams: n((volume / 1000) * mat.density), minutes: n(volume / flow / 60, 0), inPlace: members.map((p) => p.id) };
51
+ const at = printed.indexOf(members[0]);
52
+ return [...printed.slice(0, at), row, ...printed.slice(at).filter((p) => !members.includes(p))];
53
+ }
54
+
43
55
  /** The whole list. @returns {{ bought: object[], fasteners: object[], wires: object[], printed: object[], cut: object | null, totals: object }} */
44
56
  export function shoppingList(s) {
45
- const mat = materialOf(s.project), printed = printedParts(s), bought = new Map(), fasteners = new Map();
57
+ const mat = materialOf(s.project), printed = inPlaceRow(s, printedParts(s)), bought = new Map(), fasteners = new Map();
46
58
  for (const o of s.objects) if (o.bought && !o.unplaced) {
47
59
  // (a beam by its profile and length: one line for each length cut, lib/beams.mjs)
48
60
  // (a panel by its sheet and size: lib/panels.mjs)
@@ -109,7 +121,7 @@ export function listText(ref, l) {
109
121
  if (l.totals.pack) out.push(` (packs of ${l.totals.pack.size}: ${l.totals.pack.rule}, ${/^[aeiou]/.test(l.totals.pack.kind) ? 'an' : 'a'} ${l.totals.pack.kind}; masses are estimates from each piece's outline)`);
110
122
  }
111
123
  if (l.wires.length) { out.push('', 'Wire'); for (const w of l.wires) row([` ${w.length} mm of`, w.gauge ?? 'gauge not given', `in ${w.runs.join(', ')}`]); }
112
- if (l.printed.length) { out.push('', `Printed (${l.totals.material})`); for (const p of l.printed) row([` ${String(p.grams).padStart(7)} g`, `about ${p.minutes} min`, `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}${p.with ? ` (comes with ${p.with}: printed beside it, screwed into it by hand)` : ''}${p.bolt ? ` (${p.count} printed bolt${p.count > 1 ? 's' : ''}, standing on ${p.count > 1 ? 'their heads' : 'its head'}: ${p.from.join('; ')})` : ''}`]); }
124
+ if (l.printed.length) { out.push('', `Printed (${l.totals.material})`); for (const p of l.printed) row([` ${String(p.grams).padStart(7)} g`, `about ${p.minutes} min`, `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}${p.inPlace ? ' (printed together in place: one print)' : ''}${p.with ? ` (comes with ${p.with}: printed beside it, screwed into it by hand)` : ''}${p.bolt ? ` (${p.count} printed bolt${p.count > 1 ? 's' : ''}, standing on ${p.count > 1 ? 'their heads' : 'its head'}: ${p.from.join('; ')})` : ''}`]); }
113
125
  out.push('', `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.fixingsGrams ? `${l.totals.fixingsGrams} g of fixings, ` : ''}${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`);
114
126
  if (l.cost) {
115
127
  const c = l.cost, parts = [];
package/lib/motors.mjs CHANGED
@@ -276,7 +276,8 @@ function screwsFor(d, plate, t = plate) {
276
276
  * at the length mountModel works out for the plate as drawn taken to a length sold (the longest that does not pass it
277
277
  * into the motor's own thread; through plain holes, the shortest that reaches), or the length the motor item names.
278
278
  * @param {object} s a built assembly @param {{ placeItems: Function, jointValues: Function }} helpers
279
- * @returns {{ item: string, other: string, fit: object, thread: string, head: string, name: string, key: number | null, length: number, wanted: number, count: number }[]}
279
+ * @returns {{ item: string, other: string, fit: object, thread: string, head: string, name: string, key: number | null, tool: string | null, length: number, wanted: number, count: number }[]}
280
+ * tool: what turns them, as the order says it: a hex key in a socket head, a socket or spanner on a hexagon head
280
281
  */
281
282
  export function motorScrews(s, { placeItems, jointValues }) {
282
283
  const drives = s.motion?.drives || [], top = (n) => String(n).split(/[.@]/)[0];
@@ -288,7 +289,8 @@ export function motorScrews(s, { placeItems, jointValues }) {
288
289
  const p = mountPlate(s, d, worlds[d.item]); if (!p || p.t === Infinity) continue;
289
290
  const { fx, length, wanted, name } = screwsFor(d, +p.plate.toFixed(2), +p.t.toFixed(2));
290
291
  if (!(wanted > 0)) continue;
291
- out.push({ item: d.id, other: p.other, fit: p.fit, thread: fx.thread, head: fx.head.form, name, key: fx.head.key ?? null, length, wanted, count: d.model.mount.holes.length });
292
+ const tool = fx.head.form === 'hex' && fx.head.flats ? `${+fx.head.flats.toFixed(3)} mm socket or spanner` : fx.head.key != null ? `${+fx.head.key.toFixed(3)} mm hex key` : null;
293
+ out.push({ item: d.id, other: p.other, fit: p.fit, thread: fx.thread, head: fx.head.form, name, key: fx.head.key ?? null, tool, length, wanted, count: d.model.mount.holes.length });
292
294
  }
293
295
  return out;
294
296
  }
@@ -461,11 +463,18 @@ export function shaftFit(x, s, f, { placeItems, jointValues, mul, materialName,
461
463
  const gapAt = (psi) => Math.min(...inner.map(([a, h]) => h - section(a, psi)));
462
464
  let gap = S.flats ? -Infinity : gapAt(0);
463
465
  if (S.flats) for (let k = 0; k < N; k++) gap = Math.max(gap, gapAt((2 * Math.PI * k) / N));
464
- const code = (c) => ({ code: c, refs: { item: d.id, part: other } }), press = x.shaft === 'press' || gap < 0;
466
+ const code = (c) => ({ code: c, refs: { item: d.id, part: other } }), press = x.shaft === 'press' || (x.shaft !== 'slide' && gap < 0);
465
467
  if (S.flats) {
466
468
  const radial = inner.map(([, h]) => h);
467
469
  if (Math.max(...radial) - Math.min(...radial) < 0.2) return f('fail', `${label}: the bore is round and the shaft has a flat: nothing turns the part but friction. Cut the flat in the bore (bore() in @rulecad/motors), or add a grub screw`, `${label}: round bore`, { ...code('shaft.flat') });
468
470
  }
471
+ // A slide fit, as a part printed in place needs (it can't be pressed on: the push would go through its teeth, or
472
+ // whatever holds it in place): the bore as printed, hole_comp smaller across than drawn, still clear of the shaft
473
+ if (x.shaft === 'slide') {
474
+ const printed = gap - holeComp / 2;
475
+ if (printed < 0) f('fail', `${label}: a slide fit, but printed the bore comes out ${n3(holeComp, 2)} mm smaller across than drawn, ${n3(-printed, 3)} mm a side tighter than the shaft: it won't slide on, and it can't be pressed on. Draw the bore as bore() in @rulecad/motors does for a slide (the shaft, its fit each side and hole_comp)`, `${label}: no slide`, { ...code('shaft.slide'), values: { drawn: gap, printed, holeComp } });
476
+ else f('pass', `${label}: slides on by hand, ${n3(printed, 3)} mm a side as printed (${n3(gap, 3)} mm drawn, less half of hole_comp's ${n3(holeComp, 2)} mm)`, null, { ...code('shaft.slide'), values: { drawn: gap, printed, holeComp } });
477
+ }
469
478
  if (gap > 0.5) f('fail', `${label}: the bore is ${n3(gap, 2)} mm clear of the shaft at its closest: too slack to hold`, `${label}: slack`, code('shaft.bore'));
470
479
  if (gap < -0.2) f('fail', `${label}: the bore is ${n3(-gap, 2)} mm tighter than the shaft: it won't go on`, `${label}: too tight`, code('shaft.bore'));
471
480
  const grip = S.flats ? Math.min(flatOn, on) : on, want = S.flats ? Math.min(1.5 * S.diameter, 0.8 * S.flatLength) : 1.5 * S.diameter;
package/lib/order.mjs CHANGED
@@ -77,7 +77,9 @@ function blockers(p, q, d, h, rasterOf) {
77
77
 
78
78
  // A pair meant to overlap (a press fit) tells nothing about what stands in whose way
79
79
  const names = (x) => [x].flat().map(top);
80
- const allowedPair = (s, a, b) => s.fits.some((x) => x.min != null && x.num(x.min) < 0 && ((names(x.a).includes(a.id) && names(x.b).includes(b.id)) || (names(x.a).includes(b.id) && names(x.b).includes(a.id))));
80
+ // (items printed together in place come off the bed together: nothing takes them apart from each other)
81
+ const together = (s, a, b) => Array.isArray(s.a?.printInPlace) && s.a.printInPlace.includes(a.id) && s.a.printInPlace.includes(b.id);
82
+ const allowedPair = (s, a, b) => together(s, a, b) || s.fits.some((x) => x.min != null && x.num(x.min) < 0 && ((names(x.a).includes(a.id) && names(x.b).includes(b.id)) || (names(x.a).includes(b.id) && names(x.b).includes(a.id))));
81
83
 
82
84
  function hitsAlong(origin, dir, tris) {
83
85
  for (const t of tris) {
@@ -104,6 +106,8 @@ export function assemblyOrder(s) {
104
106
  if (!all.length) return { steps: [], stuck: null };
105
107
  const by = new Map(all.map((g) => [g.id, g])), ids = all.map((g) => g.id), joints = s.motion.joints, items = s.motion.items.map((x) => x[0]);
106
108
  const bearing = (id) => by.get(id)?.bought?.part === 'bearing';
109
+ // Items printed together in place (the assembly's printInPlace) come off the bed as one: one step, never taken apart
110
+ const printSet = new Set(Array.isArray(s.a?.printInPlace) ? s.a.printInPlace.filter((id) => by.has(id)) : []);
107
111
  // How far each part is from the base along joints and fastenings: nearer goes first
108
112
  const links = new Map(ids.map((id) => [id, new Set()])), tie = (a, b) => { if (links.has(a) && links.has(b) && a !== b) { links.get(a).add(b); links.get(b).add(a); } };
109
113
  const fastening = s.fits.filter((x) => x.fastens || x.seat != null || x.shaft != null || x.engage != null);
@@ -148,7 +152,8 @@ export function assemblyOrder(s) {
148
152
  if (first.length) { if (acc.tilt == null) bad.push({ fit: { note: rel.label }, wall: first[0], at: acc.top, later, fasten: rel.index, screw: sc.index, member: screwed.includes(first[0]), fixed: !by.has(first[0]) }); continue; }
149
153
  for (const q of walls) { add(later, q, `${q} covers the screws of ${rel.label}`); covers.push({ fasten: rel.index, fit: rel.label, screwed, wall: q }); }
150
154
  }
151
- const box = (g) => { const p = g.tris.flat(); return [0, 1, 2].map((k) => { const v = p.map((x) => x[k]); return (Math.min(...v) + Math.max(...v)) / 2; }); };
155
+ // (the middle of a part's box, by a loop: spreading a big part's hundreds of thousands of corners into Math.min runs out of stack)
156
+ const box = (g) => { const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; for (const t of g.tris) for (const x of t) for (let k = 0; k < 3; k++) { if (x[k] < lo[k]) lo[k] = x[k]; if (x[k] > hi[k]) hi[k] = x[k]; } return [0, 1, 2].map((k) => (lo[k] + hi[k]) / 2); };
152
157
  if (bad.length) {
153
158
  const b = bad[0], label = b.fit.note || `${b.fit.a} to ${b.fit.b}`, why = b.member ? 'it is one of the parts the screw joins' : b.fixed ? 'it is in place before anything is fitted' : `goes on first (${[...before.get(b.wall)].slice(0, 1).map(([, w]) => w)})`;
154
159
  return { steps: [], stuck: { item: b.later, screw: label, wall: b.wall, at: b.at, ...(b.fasten != null ? { fasten: b.fasten, screws: bad.filter((x) => x.fasten === b.fasten).map((x) => x.screw) } : {}),
@@ -175,6 +180,14 @@ export function assemblyOrder(s) {
175
180
  while (rest.length) {
176
181
  let pick = null;
177
182
  for (const p of rest) {
183
+ if (printSet.has(p.id) && printSet.size > 1) { // (the whole print, or nothing of it)
184
+ const group = [...printSet].map((id) => rest.find((q) => q.id === id)).filter(Boolean), others = rest.filter((q) => !printSet.has(q.id));
185
+ if (group.some((q) => waits(q, others))) continue;
186
+ if (!others.length) { pick = { group, d: [0, 0, 1], sub: { off: [] }, print: true }; break; }
187
+ const d = dirsFor(p).find((x) => group.every((q) => others.every((o) => allowedPair(s, q, o) || !blockers(q, o, x, h, rasterOf))));
188
+ if (d) { pick = { group, d, sub: { off: [] }, print: true }; break; }
189
+ continue;
190
+ }
178
191
  if (waits(p, rest)) continue;
179
192
  if (rest.length === 1) { pick = { p, d: [0, 0, 1] }; break; }
180
193
  const d = dirsFor(p).find((x) => free(p, rest, x));
@@ -202,14 +215,14 @@ export function assemblyOrder(s) {
202
215
  const apart = takeApart(all);
203
216
  if (apart.stuck) return { steps: [], stuck: apart.stuck };
204
217
  // Put together: last off is first on, a set built up on its own and then fitted as one
205
- const seq = [], lay = (off) => { for (const x of [...off].reverse()) { if (x.group) { lay(x.sub.off); seq.push({ group: x.group, d: x.d }); } else seq.push(x); } };
218
+ const seq = [], lay = (off) => { for (const x of [...off].reverse()) { if (x.group) { lay(x.sub.off); seq.push({ group: x.group, d: x.d, ...(x.print ? { print: true } : {}) }); } else seq.push(x); } };
206
219
  lay(apart.off);
207
220
  const at = new Map(), steps = [];
208
- // a motor's mounting screws, on the fit that fastens it (motorScrews): counted, with the key that turns them
209
- const motorFits = new Map(motorScrews(s, { placeItems, jointValues }).map((m) => [m.fit, { fastener: m.name, count: m.count, ...(m.key != null ? { key: `${+m.key.toFixed(3)} mm hex key` } : {}) }]));
221
+ // a motor's mounting screws, on the fit that fastens it (motorScrews): counted, with the tool that turns them
222
+ const motorFits = new Map(motorScrews(s, { placeItems, jointValues }).map((m) => [m.fit, { fastener: m.name, count: m.count, ...(m.tool ? { key: m.tool } : {}) }]));
210
223
  seq.forEach((x, i) => { for (const g of x.group ?? [x.p]) at.set(g.id, i); });
211
224
  for (const [i, x] of seq.entries()) {
212
- if (x.group) { steps.push({ items: x.group.map((g) => g.id), object: null, dir: round(x.d), fasteners: [], together: true }); continue; }
225
+ if (x.group) { steps.push({ items: x.group.map((g) => g.id), object: null, dir: round(x.d), fasteners: [], together: true, ...(x.print ? { printed: true } : {}) }); continue; }
213
226
  const { p, d } = x, list = [...new Set(s.fits.filter((f) => [...names(f.a), ...names(f.b)].includes(p.id) && (f.fastens || f.seat != null || f.fastener) && [...names(f.a), ...names(f.b)].every((n) => (at.get(n) ?? 0) <= i)))];
214
227
  steps.push({ items: [p.id], object: p.object, dir: round(d), fasteners: list.map((f) => ({ fit: f.note || f.label || `${f.a} to ${f.b}`, ...(f.fastener ? { fastener: f.fastener } : {}), ...(f.count != null ? { count: f.num(f.count) } : {}), ...(f.key ? { key: f.key } : {}), ...(f.tighten ? { tighten: f.tighten } : {}), ...(!f.fastener ? motorFits.get(f) : {}) })) });
215
228
  }
@@ -218,18 +231,19 @@ export function assemblyOrder(s) {
218
231
  for (const st of steps) {
219
232
  const last = merged.at(-1);
220
233
  if (last && st.object && !st.together && last.object === st.object && last.dir.join() === st.dir.join() && JSON.stringify(last.fasteners.map((f) => f.fit)) === JSON.stringify(st.fasteners.map((f) => f.fit))) last.items.push(...st.items);
221
- else merged.push({ items: [...st.items], object: st.object, dir: st.dir, fasteners: st.fasteners, ...(st.together ? { together: true } : {}) });
234
+ else merged.push({ items: [...st.items], object: st.object, dir: st.dir, fasteners: st.fasteners, ...(st.together ? { together: true } : {}), ...(st.printed ? { printed: true } : {}) });
222
235
  }
223
- merged.forEach((st, i) => { st.n = i + 1; st.text = `${st.items.join(', ')}${st.object && !st.items.includes(st.object) ? ` (${st.object})` : ''}${st.together ? ' go on as one' : i ? ` goes on${st.items.length > 1 ? ', one by one' : ''}` : ' first'}${st.fasteners.length ? `: ${st.fasteners.map(fastenerText).join('; ')}` : ''}`; });
236
+ merged.forEach((st, i) => { st.n = i + 1; st.text = `${st.items.join(', ')}${st.object && !st.items.includes(st.object) ? ` (${st.object})` : ''}${st.printed ? `, printed together in place (one print)${i ? ', go on as one' : ', first'}` : st.together ? ' go on as one' : i ? ` goes on${st.items.length > 1 ? ', one by one' : ''}` : ' first'}${st.fasteners.length ? `: ${st.fasteners.map(fastenerText).join('; ')}` : ''}`; });
224
237
  return { steps: merged, stuck: null, covers };
225
238
  }
226
239
 
227
240
  /** One fastening of a step as the order and the build page say it: the fit, its screws by count and name, the key and how tight. */
228
241
  export const fastenerText = (f) => `${f.fit}${f.fastener ? ` (${f.count != null ? `${f.count} × ` : ''}${f.fastener})` : ''}${f.key ? ` with ${/^[aeiou8]/i.test(f.key) ? 'an' : 'a'} ${f.key}` : ''}${f.tighten ? `, ${f.tighten.given ? `to ${f.tighten.torque} N m` : f.tighten.load ? `to ${f.tighten.torque} N m (what the joint's load leaves the thread)` : `to ${f.tighten.torque} N m at most (what the seat takes)`}` : ''}`;
229
242
 
230
- // Cached by what the parts are and where they are, with everything else that changes the answer
243
+ // Cached by what the parts are and where they are, with everything else that changes the answer (a motor's screw
244
+ // names the tool its step gives)
231
245
  function orderFile(s) {
232
- const key = crypto.createHash('sha256').update(JSON.stringify([8, s.parts.map((p) => [p.item, p.hash ?? p.shape, Array.from(p.m ?? []).map((x) => +x.toFixed(4))]), s.fits.map(({ num, ...x }) => x), s.motion.joints.map((j) => [j.id, j.child, j.parent])])).digest('hex');
246
+ const key = crypto.createHash('sha256').update(JSON.stringify([9, s.a?.printInPlace ?? null, (s.a?.items || []).filter((x) => x.motor).map((x) => [x.id, x.motor.screw ?? null]), s.parts.map((p) => [p.item, p.hash ?? p.shape, Array.from(p.m ?? []).map((x) => +x.toFixed(4))]), s.fits.map(({ num, ...x }) => x), s.motion.joints.map((j) => [j.id, j.child, j.parent])])).digest('hex');
233
247
  return paths.cache('order', `${key}.json`);
234
248
  }
235
249
  export function orderOf(s) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.67",
3
+ "version": "0.7.68",
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": {
@@ -60,18 +60,18 @@
60
60
  "dependencies": {
61
61
  "@rulecad/variables": "^0.3.5",
62
62
  "@rulecad/keyboard-layout": "^0.1.2",
63
- "@rulecad/printcheck": "^0.3.0",
63
+ "@rulecad/printcheck": "^0.3.3",
64
64
  "@rulecad/fit": "^0.4.0",
65
65
  "@rulecad/model-link": "^0.3.2",
66
66
  "@rulecad/versions": "^0.1.6",
67
- "@rulecad/shapes": "^0.4.5",
67
+ "@rulecad/shapes": "^0.4.6",
68
68
  "@rulecad/rules": "^0.3.19",
69
69
  "@jscad/modeling": "^2.12.0",
70
70
  "three": "^0.186.1",
71
71
  "@rulecad/fea": "^0.2.11",
72
72
  "@rulecad/topopt": "^0.3.0",
73
73
  "@rulecad/flexures": "^0.5.4",
74
- "@rulecad/gears": "^0.3.3",
74
+ "@rulecad/gears": "^0.3.4",
75
75
  "@rulecad/motors": "^0.1.6",
76
76
  "@rulecad/fixings": "^0.1.5",
77
77
  "@rulecad/robots": "^0.1.3",
@@ -32,6 +32,7 @@
32
32
  "frame": { "type": "object", "additionalProperties": false, "description": "The frame: what it is (a generator, kind with inside or outside, which expands into beams, joins and their ends before anything is built, as cad frame --expand writes out), and how its beams and joins are solved for frame.deflection, frame.stress, frame.buckling, frame.rack and frame.frequency, which beams could be printed (beam.printable), and how it is cut and heated for frame.square and frame.heat. Left out, it stands on its feet: the beam ends that carry a foot, a levelling foot, a castor plate or a stacking foot, or else the lowest beam ends, each held from moving (pinned)", "properties": {"kind": {"enum": ["box", "portal", "table", "gantry", "shelf"], "description": "A frame generated from a size: box (four posts and a ring of beams at the bottom and top), portal (two legs and a beam across: inside and outside are [width, height]; it lies in one plane and tips over on its feet alone, so it is refused until supports says its feet are held down, as z1.a and z2.a fixed), table (four legs and a ring at the top), gantry (a box without its top beams across, and a beam riding along the two top side beams on a sliding joint) or shelf (a box with rings between, shelves of them). Its beams are z1 .. (upright), x1 .. and y1 .. (along x and y, by ring from the bottom), g (a gantry's moving beam); its corner arrangement follows the join"}, "inside": {"type": "array", "minItems": 2, "maxItems": 3, "items": {"$ref": "#/$defs/expr"}, "description": "The clear volume the frame encloses, [width (x), depth (y), height (z)] in mm (a portal: [width, height]); the beams go round it. Give inside or outside"}, "outside": {"type": "array", "minItems": 2, "maxItems": 3, "items": {"$ref": "#/$defs/expr"}, "description": "The volume the whole frame must fit in, [width, depth, height] in mm (a portal: [width, height]); the beams go within it"}, "profile": {"type": "string", "description": "Every beam's profile, a square one (2020-misumi-hfs5, 3030-generic, 4040-item-8)"}, "join": {"description": "How the beams meet at each corner: a kind (blind, end-tap, bracket, gusset, hidden, anchor: the upright beams run through and the others butt against their faces, each shorter by the profile's width at each end; cube: every beam butts into a corner node, each as long as the inside), or { kind, fitting, screw } as a join takes them", "oneOf": [{"type": "string"},{"type": "object", "additionalProperties": false, "required": ["kind"], "properties": {"kind": {"type": "string"}, "fitting": {"type": "string"}, "screw": {"type": "string"}}}]}, "feet": {"type": ["string", "null"], "description": "What stands under the upright beams' lower ends: foot, levelling, castor or stacking (printed), or a bought foot's set by name (fitting-motedis-foot-m6-d19); left out, an end cap"}, "caps": {"type": ["string", "boolean"], "description": "The ends no join covers: printed end caps (true, the default), a bought end cap's set by name, or false for none (join.end then names them)"}, "braces": {"type": "array", "items": {"enum": ["front", "back", "left", "right"]}, "description": "The upright sides whose corners are stiffened against racking: each join in that side becomes a bracket join with a printed corner bracket in the corner, on drop-in nuts"}, "panels": {"type": "object", "additionalProperties": false, "required": ["sheet", "thickness"], "description": "Panels closing the upright sides, each cut to its bay with its clips (a box, a shelf, a gantry's two sides)", "properties": {"sheet": {"type": "string", "description": "The sheet's material: acrylic, polycarbonate, aluminium, plywood, mdf"}, "thickness": {"$ref": "#/$defs/expr", "description": "mm"}, "sides": {"type": "array", "items": {"enum": ["front", "back", "left", "right"]}, "description": "Which sides (default every side that has a bay)"}}}, "shelves": {"type": "integer", "minimum": 1, "maximum": 20, "description": "A shelf: how many rings stand between the bottom and the top, spacing its height into equal clear bays (default 1)"}, "supports": {"type": "object", "description": "Where the frame is held, by beam end (\"z1.a\") or a place on a beam (\"x1.bottom@50%\"): pinned holds it from moving and lets it turn, fixed holds it from turning too, resting holds it from moving and from twisting about the beam's own length (a beam lying across a round bar, as the beam coupon does; for a beam along x, y or z). Given, these are the only supports", "additionalProperties": {"enum": ["pinned", "fixed", "resting"]}}, "limit": {"$ref": "#/$defs/expr", "description": "The sag allowed in every frame.deflection finding, in mm: at each load's point, each named point and along each guide whose rail gives no parallelism of its own (default: the task's accuracy, else the span of the beam it is on over 360)"}, "points": {"type": "array", "description": "Places on beams to report the sag at, beside each load's point and every guide (\"x1.top@50%\")", "items": {"type": "string"}}, "cut": {"type": "object", "additionalProperties": false, "description": "How the beams are cut in this workshop, where it differs from the profile's set and the kit's defaults: frame.square, frame.cut and the cut list read it", "properties": {"tolerance": {"$ref": "#/$defs/expr", "description": "How far a cut length may be from the length asked, either way, in mm (default: the profile's cut_tolerance, else 0.5)"}}}, "heat": {"type": "object", "additionalProperties": false, "description": "frame.heat: the temperatures the frame works at. The beams grow with the air in the enclosure; each printed fitting is held to its plastic's softening point", "properties": {"air": {"$ref": "#/$defs/expr", "description": "The air round the frame when it runs, in degrees C (inside its enclosure)"}, "built": {"$ref": "#/$defs/expr", "description": "The air it was built and squared in, in degrees C (default 20)"}, "heaters": {"type": "array", "description": "Hot things near the frame: what is within reach of one is taken at its temperature", "items": {"type": "object", "required": ["at", "temperature", "reach"], "additionalProperties": false, "properties": {"name": {"type": "string"}, "at": {"$ref": "#/$defs/vec3", "description": "Its middle, in the assembly's frame, mm"}, "temperature": {"$ref": "#/$defs/expr", "description": "Degrees C at its surface"}, "reach": {"$ref": "#/$defs/expr", "description": "How far from its middle a part is taken at that temperature, mm"}}}}}}, "printed": {"description": "beam.printable: each beam tried printed in this plastic (the kit's printable profile of its size, lying down or standing up), the frame solved again and held to its own limits: its sags, stress, buckling, creep and lowest mode; the beams that can be printed are listed, and printed together solved once more. A plastic's set by name (\"petg\"), or how it prints", "oneOf": [{"type": "string"},{"type": "object", "additionalProperties": false, "required": ["material"], "properties": {"material": {"type": "string", "description": "The plastic's set: pla, petg"}, "walls": {"type": "integer", "minimum": 1, "description": "Walls round every outline, in lines (3)"}, "infill": {"type": "number", "minimum": 0, "maximum": 1, "description": "The share of the inside the infill fills (0.4)"}, "pose": {"enum": ["lying", "standing"], "description": "Only this way up (both are tried where left out)"}}}]}, "size": {"type": "object", "additionalProperties": false, "description": "frame.size: each group of beams that must match given the lightest profile from a list that meets the frame's own limits (the sag at each load, point and guide, each beam's stress and buckling with frame.margin to spare, and the lowest mode against the task's moves), solved in every pose; a table of each group's profile, the limit that set it and its margin, and cad frame --size --write writes the profiles in", "properties": {"profiles": {"type": "array", "minItems": 1, "items": {"type": "string"}, "description": "The profiles to choose from, by set (default MISUMI's HFS5, HFS6 and HFS8 series from 2020 to 4080). One that is not square is tried lying as drawn and turned a quarter. Choose one family whose joins fit each other: the join checks of the written frame say where they do not"}, "groups": {"type": "object", "description": "Beams that must take one profile, by group name (\"rails\": [\"x1\", \"x2\"]); the rest are grouped by themselves: one profile, one direction, lengths within 0.5 mm", "additionalProperties": {"type": "array", "minItems": 1, "items": {"type": "string"}}}, "limits": {"type": "object", "additionalProperties": false, "description": "Limits in place of the frame checks' own", "properties": {"deflection": {"$ref": "#/$defs/expr", "description": "The sag allowed at every load, named point and guide, mm"}, "stress": {"$ref": "#/$defs/expr", "description": "How many times under its alloy's strength each beam stays (default frame.margin, 2)"}, "buckling": {"$ref": "#/$defs/expr", "description": "How many times its load the frame, and each grouped beam by Euler's load, must carry before it buckles (default frame.margin, 2)"}, "frequency": {"$ref": "#/$defs/expr", "description": "The lowest mode's floor, Hz (default twice what the task's moves shake it at; none without a task)"}}}, "by": {"enum": ["mass", "cost"], "description": "What is made least (mass: no profile set in the kit gives a price per metre yet)"}}}, "rack": {"type": "object", "additionalProperties": false, "description": "frame.rack: the side push at the frame's top and the sway allowed", "properties": {"load": {"$ref": "#/$defs/expr", "description": "The side push in N, shared among the top corners (default 20, an estimate)"}, "limit": {"$ref": "#/$defs/expr", "description": "The sway allowed at the top, in mm (default: the task's accuracy, else the height over 400)"}}}} },
33
33
  "loads": { "type": "array", "description": "What the assembly has to do: a torque (N m) or force (N) on a joint, or a mass (kg) carried at an anchor", "items": { "type": "object", "additionalProperties": false, "properties": { "joint": { "type": "string" }, "torque": { "$ref": "#/$defs/expr" }, "force": { "$ref": "#/$defs/expr" }, "mass": { "$ref": "#/$defs/expr" }, "at": { "$ref": "#/$defs/anchorRef" }, "note": { "type": "string" } } } },
34
34
  "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" } } },
35
+ "printInPlace": { "type": "array", "minItems": 2, "items": { "type": "string" }, "description": "Items printed together as one object printed in place (\"printInPlace\": true on it): they come off the bed together, so the assembly order never takes them apart from each other" },
35
36
  "pose": { "type": "string" }
36
37
  },
37
38
  "$defs": {
@@ -47,7 +48,7 @@
47
48
  "id": { "type": "string" },
48
49
  "object": { "type": "string" },
49
50
  "assembly": { "type": "string" },
50
- "motor": { "type": "object", "required": ["model"], "additionalProperties": false, "description": "A motor from @rulecad/motors: bought, not printed; its shaft turns the joint it drives", "properties": { "model": { "type": "string" }, "drives": { "type": "string" }, "set": { "type": "object", "description": "Figures that differ from the catalogue's, by name" }, "speed": { "$ref": "#/$defs/expr", "description": "The motor's speed, rpm (default: what it does comfortably)" }, "margin": { "$ref": "#/$defs/expr", "description": "How many times over the torque must be (default 2)" }, "duty": { "$ref": "#/$defs/expr", "description": "The share of the time it runs, 0 to 1 (default 1), for its heat" }, "screw": { "type": "string", "description": "The screws through a motor's plain holes, if not the size they take: M3" }, "driver": { "type": "string", "description": "The bought driver item this motor plugs into" }, "leadscrew": { "type": "object", "additionalProperties": false, "required": ["lead"], "properties": { "lead": { "$ref": "#/$defs/expr" }, "diameter": { "$ref": "#/$defs/expr" }, "friction": { "$ref": "#/$defs/expr" } } }, "belt": { "type": "object", "additionalProperties": false, "required": ["teeth"], "properties": { "teeth": { "$ref": "#/$defs/expr" }, "pitch": { "$ref": "#/$defs/expr" }, "stiffness": { "$ref": "#/$defs/expr", "description": "N per mm of strain, per mm of belt width" }, "width": { "$ref": "#/$defs/expr" }, "length": { "$ref": "#/$defs/expr" }, "load": { "$ref": "#/$defs/expr" } } }, "current": { "type": "number", "description": "A per coil, as set on the driver (default its rated current)" }, "cooled": { "type": "boolean", "description": "The driver has a heat sink and moving air" }, "microsteps": { "type": "number", "description": "Steps to a full step (default 16): resolution, not accuracy" } } },
51
+ "motor": { "type": "object", "required": ["model"], "additionalProperties": false, "description": "A motor from @rulecad/motors: bought, not printed; its shaft turns the joint it drives", "properties": { "model": { "type": "string" }, "drives": { "type": "string" }, "set": { "type": "object", "description": "Figures that differ from the catalogue's, by name" }, "speed": { "$ref": "#/$defs/expr", "description": "The motor's speed, rpm (default: what it does comfortably)" }, "margin": { "$ref": "#/$defs/expr", "description": "How many times over the torque must be (default 2)" }, "duty": { "$ref": "#/$defs/expr", "description": "The share of the time it runs, 0 to 1 (default 1), for its heat" }, "screw": { "type": "string", "description": "The screws that hold the motor, by a fixing's name: a thread through its plain holes, if not the size they take (M3), or a whole screw with its length and head (M3x8 hex), whose head sets the tool the order names" }, "driver": { "type": "string", "description": "The bought driver item this motor plugs into" }, "leadscrew": { "type": "object", "additionalProperties": false, "required": ["lead"], "properties": { "lead": { "$ref": "#/$defs/expr" }, "diameter": { "$ref": "#/$defs/expr" }, "friction": { "$ref": "#/$defs/expr" } } }, "belt": { "type": "object", "additionalProperties": false, "required": ["teeth"], "properties": { "teeth": { "$ref": "#/$defs/expr" }, "pitch": { "$ref": "#/$defs/expr" }, "stiffness": { "$ref": "#/$defs/expr", "description": "N per mm of strain, per mm of belt width" }, "width": { "$ref": "#/$defs/expr" }, "length": { "$ref": "#/$defs/expr" }, "load": { "$ref": "#/$defs/expr" } } }, "current": { "type": "number", "description": "A per coil, as set on the driver (default its rated current)" }, "cooled": { "type": "boolean", "description": "The driver has a heat sink and moving air" }, "microsteps": { "type": "number", "description": "Steps to a full step (default 16): resolution, not accuracy" } } },
51
52
  "bought": { "type": "string", "description": "A part from a rule set (\"608\", \"drv8825\", \"fitting-motedis-end-cap-20-b6\"): bought, not printed; drawn faint from its figures, with anchors from what it is. A frame's bought fitting (an end cap, a levelling foot, a hinge) placed at a beam's address is checked against that beam's profile, and its price goes on cad list" },
52
53
  "variant": { "type": "string" },
53
54
  "set": { "type": "object" },
@@ -87,7 +88,7 @@
87
88
  "b": { "$ref": "#/$defs/names" },
88
89
  "engage": { "$ref": "#/$defs/expr", "description": "a goes at least this far (mm) onto b along the joint between them: a part slid onto a shaft or a pin, not resting on its end" },
89
90
  "radius": { "$ref": "#/$defs/expr", "description": "With engage: how near the joint's axis to look (mm, default 10)" },
90
- "shaft": { "anyOf": [{ "type": "boolean" }, { "enum": ["slide", "press"] }], "description": "a or b is a motor, and the other takes its shaft: reads the bore from the part as drawn" },
91
+ "shaft": { "anyOf": [{ "type": "boolean" }, { "enum": ["slide", "press"] }], "description": "a or b is a motor, and the other takes its shaft: reads the bore from the part as drawn; slide: the bore as printed (the drawn gap less half the printer's hole_comp) must clear the shaft, as a part printed in place needs" },
91
92
  "seat": { "anyOf": [{ "type": "boolean" }, { "enum": ["press", "slip"] }, { "type": "number" }], "description": "a or b is a bought bearing, and the other its printed seat: reads the pocket as drawn against the bearing's rules and the printer's fit (fit.seat)" },
92
93
  "fastens": { "type": "boolean", "description": "a and b are fastened together (pins, a press, a clip): what holds a part that has no joint. Where screws hold them, use a fasten instead: it knows the screw, checks its holes and lists it" },
93
94
  "fastener": { "description": "What does the fastening: in words (two push pins), named on the shopping list and the assembly step as written; or pins, { \"pin\": \"snap pin 4x6\", \"count\": 2 }, found in the parts' holes and checked (fit.pin): each hole against the one @rulecad/fixings draws for the pin and the printer, the pin's length against the parts, and the load; or magnets, { \"magnet\": \"disc magnet 8x3\", \"count\": 2 }, found in the parts' pockets and checked (fit.magnet): each pocket against the one @rulecad/fixings draws for the magnet and the printer, its depth and floor, and their pull against the load. A screw is a fasten's, which chooses its length and counts it", "anyOf": [{ "$ref": "#/$defs/pins" }, { "$ref": "#/$defs/magnets" }, { "type": "string" }] },
@@ -18,6 +18,7 @@
18
18
  "orientation": { "type": "string", "description": "How it sits on the bed, and anything the printer or the person assembling it should know" },
19
19
  "role": { "enum": ["part", "reference", "board"], "description": "reference: drawn faint and never printed (a switch, a tablet); board: a circuit board" },
20
20
  "engine": { "enum": ["jscad", "manifold", "pcb"], "description": "manifold: v.ops booleans by Manifold (npm install manifold-3d); pcb: a circuit board" },
21
+ "printInPlace": { "type": "boolean", "description": "The parts print together, in the pose they are drawn in, and move apart once freed (a gearbox printed whole). cad check holds each part to a face of its own on the bed, every two parts to the printer's print_gap apart (measured by Manifold), and nothing to a support, since none can come out from between them" },
21
22
  "variables": { "type": "object", "additionalProperties": { "$ref": "#/$defs/variable" } },
22
23
  "display": { "type": "object", "description": "Settings the mirror and model page use instead (lighter meshes, no legends)" },
23
24
  "mirror": { "type": "object", "description": "The older name for display" },