@rulecad/cad 0.7.70 → 0.7.77

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,37 @@ 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.77: a leg's gait for the streamer (#199)
9
+ ### Added
10
+
11
+ - `cad machine <project>/<assembly>` on an assembly with a `gait` and no `task`: a legged machine, an axis for each
12
+ motor's shaft the gait turns, ordered by the CNC shield slot (X, Y, Z) its motor is wired to, each with its `slot`.
13
+ - `cad plot <project>/<assembly>` with no drawing, on an assembly with a gait: the gait as a step file for the streamer,
14
+ `exports/<project>/<assembly>-gait.steps.json`, from the pose shown (`--pose` for another) through `--cycles` (3) and
15
+ back, at the gait's period or `--period`, and a picture of each axis through the run in `.preview/`. A motor wired to
16
+ a slot out of the streamer's order fails (`stream.wiring`); more than three axes is a warning (`stream.axes`). The
17
+ bench stand's gait plays at 2.89 s a cycle against its 2 s period: its knee would need 11712 steps/s, past the 5333
18
+ of a 17HS4401 at 200 rpm and 1/8 steps.
19
+
20
+ ## 0.7.75: parts milled, cast or printed in a powder bed
21
+ ### Added
22
+
23
+ - Problems take how the part is made: `"mill": "+z"` (milled from that side, no undercuts), `"cast": "+z"` or
24
+ `"cast": { "draw": "z", "parting": 6 }` (a mould drawn off one way, or two halves from a parting plane), with
25
+ `"symmetry": { "mirror": "y", "turns": 4, "axis": "z" }` and `"extrude": "x"` for any process, and
26
+ `"voids": "refused"` for a metal powder bed print. The problem schema has each field.
27
+ - `cad optimise` says how a milled or cast part is made and counts its undercuts (none unless an avoid region sits
28
+ behind material), says what is mirrored or extruded, and fails on a problem that refuses voids with each enclosed
29
+ void's volume and centre. `--json` gives `process`, `undercuts`, `symmetry`, `extrude`, `grey` and `voids`.
30
+ - `cad optimise` warns when more than a tenth of a milled, cast, symmetric or extruded result is grey (neither empty
31
+ nor solid), and refuses a symmetry that swaps the side the part is made from for its opposite.
32
+ - Rule sets `mill-3axis`, `mould-injection` and `dmls` (from @rulecad/rules) to read the processes' limits from.
33
+
34
+ ### Changed
35
+
36
+ - Every optimised result is made again once, since topopt's solver file changed; a problem without the new fields
37
+ gets the same densities as before. No printed size moved.
38
+
8
39
  ## 0.7.70: printed bolts into slot nuts, a slotted snap pot
9
40
  ### Fixed
10
41
 
package/README.md CHANGED
@@ -1522,6 +1522,24 @@ A problem whose regions have a z is solid. It has no thickness, and takes more k
1522
1522
  Supports and loads can be any region; a force has x, y and z. `"overhang": "+z"` keeps only material that prints
1523
1523
  without supports standing that way up (a variable holding `"+z"` or `"none"` works too, so a variant can switch it).
1524
1524
 
1525
+ A part made another way says so in place of `overhang` (one process to a problem; two are refused by name):
1526
+ - **Milled:** `"mill": "+z"` (the tool cuts down from above). No undercuts: a cell is as solid as every cell
1527
+ between it and the tool. `cad optimise` says `milled from +z: no undercuts`, or counts the cells an avoid region
1528
+ or the space's own edge hides behind material. The `mill-3axis` rule set holds the walls, corners and pockets a 3-axis machine manages.
1529
+ - **Cast or moulded:** `"cast": "+z"` for a mould drawn off one way, or `"cast": { "draw": "z", "parting": 6 }` for
1530
+ two halves drawn off both ways from a parting plane (mm along the axis; the space's middle when left out). Draft
1531
+ (`mould-injection`: a degree or so) is less than a cell, so it is left to the drawing.
1532
+ - **Printed in a metal powder bed:** `"overhang": "+z"` with `"voids": "refused"`. Powder left in an enclosed void
1533
+ can't be got out, so `cad optimise` fails with each void's volume and centre: open it with an avoid region (an
1534
+ escape hole, `dmls.escape_hole` wide) or allow voids. The `dmls` rule set holds the process's limits.
1535
+
1536
+ Any of them can also be `"symmetry": { "mirror": "y" }` (mirrored across the grid's middle planes; `"turns": 2` or
1537
+ `4` about `"axis"` for half or quarter turns) or `"extrude": "x"` (one section all along x, a part cut from a bar).
1538
+ A mirror or turn that would swap the side the part is made from for its opposite is refused by name (a mould in two
1539
+ halves parted at the middle may be mirrored across its draw). With a process or a tie, `cad optimise` warns when more
1540
+ than a tenth of the design is grey (neither empty nor solid): the outline drawn is then a guess. A 2D section milled
1541
+ or cast across its own plane often comes out so; give the problem in 3D or make it from another side.
1542
+
1525
1543
  `cad optimise` draws the result's four views in `.preview/`. A design builds the result with
1526
1544
  `v.shapes.optimisedSolid(v.problems[v.problem], { ops: v.ops })`, which adds the keep regions and cuts the avoid
1527
1545
  regions exactly. The surface is a big mesh, so set the object's `"engine": "manifold"`. With `"overhang"` set, the
@@ -1687,7 +1705,7 @@ module and read `pip`'s variables) and name them in the assembly's `"printInPlac
1687
1705
  together, so the assembly order never takes them apart from each other. `cad order` fits them as one step and
1688
1706
  `cad list` gives them one printed row, the one print's grams and minutes.
1689
1707
 
1690
- 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.
1708
+ 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. `cad machine <project>/<assembly>` on such an assembly describes it as a legged machine, an axis for each motor's shaft in the order the shield's slots are wired, and `cad plot <project>/<assembly>` with no drawing writes the gait as a step file for the streamer: `--cycles` of it (3) from a pose (`--pose`, by default the one shown) and back, every axis in each block, slowed where a motor cannot keep to the gait's period (`--period` to set it) and where a joint turns back, with a picture of each axis through the run in `.preview/`. A motor wired to a shield slot out of the streamer's order (X, Y, Z) fails by name.
1691
1709
 
1692
1710
  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.
1693
1711
 
package/bin/cad.mjs CHANGED
@@ -111,6 +111,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
111
111
  cad machine <project>/<assembly> the machine as plain data: axes, steps, limits, homing, the task, in exports/
112
112
  cad plot <project>/<assembly> <drawing.svg> plans a drawing on the machine: a step file in exports/, an animation in
113
113
  .preview/, and any stroke refused [--calibrate: the calibration drawing] [--tol 0.1] [--json]
114
+ cad plot <project>/<assembly> on an assembly with a gait: its cycle as a step file in exports/ for the streamer, from a pose and
115
+ back to it, and a picture of each axis through the run in .preview/ [--cycles 3] [--period s] [--pose <start>] [--json]
114
116
  cad order <project>/<assembly> the order it goes together in, each step with its fasteners; a frame from bars to square: cut, drill, sides built flat, nuts to load, joins with their torque, diagonals [--preview: an exploded picture of each step in .preview/]
115
117
  cad plates <project>/<assembly> every printed part on beds, by material and filament, spaced by the first-layer rule: written as plate assemblies and checked; a changed part re-packs only its plate; a frame's jigs on plates of their own [--gap mm] [--no-jigs] [--json]
116
118
  cad kit <project>/<assembly> the folder to build it from without the model, in exports/: README.md (checks, what to buy and print, cut list, drilling, the build step by step), buy.csv, the plates' 3MFs, the jigs, each beam's sheet [--pictures] [--json]
@@ -164,7 +166,7 @@ const COMMANDS = ['new', 'remove', 'move', 'import-kle', 'clone', 'agents', 'tru
164
166
  const OPTIONS = ['table', 'calibrate', 'check', 'turns', 'preview', 'gap', 'no-steps', 'all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
165
167
  'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'profile', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
166
168
  'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
167
- 'unit', 'rule', 'label', 'from', 'out', 'jigs', 'no-jigs', 'expand', 'size', 'write', 'pictures', // cad set, cad rules, cad beams, cad frame, cad plates, cad kit
169
+ 'unit', 'rule', 'label', 'from', 'out', 'jigs', 'no-jigs', 'expand', 'size', 'write', 'pictures', 'cycles', 'period', // cad set, cad rules, cad beams, cad frame, cad plates, cad kit, cad plot
168
170
  'a', 'b', 'min', 'max', 'poses', 'id', 'type', 'parent', 'child', 'follow', 'value', 'ratio', 'object', 'assembly', 'variant', 'rotate', 'to', 'roll', // cad add
169
171
  'screw', 'through', 'into', 'holes', 'nut', 'washer', 'length', 'torque', 'from-fits', // cad add fasten
170
172
  'kind', 'fitting', // cad add join
@@ -255,7 +257,8 @@ async function optimiseProblem(ref) {
255
257
  const p = await readProblem(project, name), cells = r.dim === 3 ? `${r.grid.nx} × ${r.grid.ny} × ${r.grid.nz}` : `${r.grid.nx} × ${r.grid.ny}`;
256
258
  const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => c.moment ? `${c.name} ${sig(c.angle * 180 / Math.PI)}° (${sig(c.torsion / 1000 * Math.PI / 180)} N·m/°)` : `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
257
259
  `${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}${r.dropped ? `; ${r.dropped.length} loose ${r.dropped.length === 1 ? 'piece' : 'pieces'} dropped (${sig(r.dropped.reduce((t, v) => t + v, 0))} mm³)` : ''}${r.emptied ? `; ${r.emptied} ${r.emptied === 1 ? 'cell' : 'cells'} that wouldn't print emptied` : ''}${r.cleared ? `; sliced as the printer will, ${r.cleared} ${r.cleared === 1 ? 'cell' : 'cells'} under islands emptied` : ''}`,
258
- ...(r.unsupported > 0.01 ? [`${fmt(r.unsupported * 100)}% of the kept regions has nothing holding it up (at ${r.overhang ? 'the printer\'s overhang limit' : '45°'} or less): give the part more material to stand them on, or keep less`] : [])];
260
+ ...(r.unsupported > 0.01 ? [`${fmt(r.unsupported * 100)}% of the kept regions has nothing holding it up (at ${r.overhang ? 'the printer\'s overhang limit' : '45°'} or less): give the part more material to stand them on, or keep less`] : []),
261
+ ...(r.process ? [processLine(r)] : []), ...(r.voids?.length ? [voidsLine(r)] : [])];
259
262
  let out;
260
263
  if (r.dim === 3) {
261
264
  out = paths.preview(project, `${name.replace(':', '-')}-optimised.png`);
@@ -274,8 +277,28 @@ async function optimiseProblem(ref) {
274
277
  if (r.dim === 3) console.log(` ${fmt(r.volume * 100)}% of the space filled: ${fmt(r.solid / 1000)} cm³ (${fmt(r.solid / 1000 * (p.material.density || 0))} g of ${p.material.name})${r.overhang ? `, printable built ${r.overhang}` : ''}`);
275
278
  else console.log(` ${fmt(r.volume * 100)}% of the space filled, outline ${fmt(r.area)} mm² (${fmt(r.area * r.thickness / 1000)} cm³ before bosses and holes are made exact)`);
276
279
  console.log(` ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? ', settled' : ': stopped before it settled (raise steps)'}`);
280
+ if (r.process) console.log(` ${processLine(r)}`);
281
+ if (r.symmetry || r.extrude) console.log(` ${[r.symmetry?.mirror ? `mirrored across ${[...r.symmetry.mirror].join(' and ')}` : '', r.symmetry?.turns ? `the same each ${r.symmetry.turns === 4 ? 'quarter' : 'half'} turn about ${r.symmetry.axis || 'z'}` : '', r.extrude ? `one section along ${r.extrude}` : ''].filter(Boolean).join(', ')}`);
282
+ if (r.grey > 0.1) console.log(` warning: ${greyLine(r)}`);
283
+ if (r.voids?.length) { console.log(` error: ${voidsLine(r)}`); process.exitCode = 1; }
277
284
  console.log(out);
278
285
  }
286
+ // How a milled or cast result is made, and its undercuts (none, unless an avoid region or the space's own shape sits
287
+ // behind material: the optimiser keeps every cell as solid as those on its way out, but can't fill a cell it mustn't)
288
+ function processLine(r) {
289
+ const how = r.process.mill ? `milled from ${r.process.mill}` : typeof r.process.cast === 'string' ? `cast, drawn off ${r.process.cast}` : `cast in two halves drawn off along ${r.process.cast.draw} from ${fmt(r.process.cast.parting)} mm`;
290
+ return r.undercuts ? `${how}: ${r.undercuts} ${r.undercuts === 1 ? 'cell is' : 'cells are'} undercut (an avoid region, or the edge of the space, with material between it and the ${r.process.mill ? 'tool' : 'draw'}: move it, or make it from that side)` : `${how}: no undercuts`;
291
+ }
292
+ // A grey result (warned of above a tenth): its design cells between a tenth and nine tenths solid. A clear design has
293
+ // a few per cent, on its surfaces (the 3D cantilever milled from above 5.3%, free 2D cantilevers 1 to 3%): a tenth
294
+ // is a choice from those, an estimate
295
+ function greyLine(r) {
296
+ return `${fmt(r.grey * 100)}% of the design is grey (neither empty nor solid): the outline drawn at half density is a guess, not a part. A section milled, cast or extruded across its own plane often comes out so; give the problem in 3D, make it from another side, or allow more steps`;
297
+ }
298
+ // Enclosed voids, refused by the problem (powder that can't get out, a trapped core)
299
+ function voidsLine(r) {
300
+ return `${r.voids.length} enclosed ${r.voids.length === 1 ? 'void' : 'voids'} (${r.voids.map((v) => `${sig(v.volume)} ${r.dim === 3 ? 'mm³' : 'mm²'} at ${v.at.map(fmt).join(', ')}`).join('; ')}): powder or a core can't get out: open ${r.voids.length === 1 ? 'it' : 'each'} to the outside with an avoid region (an escape hole), or allow voids`;
301
+ }
279
302
 
280
303
  // An object's analyses for cad check: each problem's load cases on the part, and its volume against a target
281
304
  function place(triangles, [rx, ry, rz], move) {
@@ -1094,7 +1117,8 @@ async function machineCommand(what, ref) {
1094
1117
  const m = await import('../lib/machine.mjs'), s = await buildAssembly(ref);
1095
1118
  if (what === 'machine') { const out = m.machineOf(s), file = m.writeMachine(s, out); (await import('../lib/buildpage.mjs')).writeWiring(s); return console.log(opt('json') ? JSON.stringify(out, null, 2) : file); }
1096
1119
  const source = positional()[2], tol = opt('tol') != null ? Number(opt('tol')) : undefined;
1097
- if (!source && !opt('calibrate')) throw new Error('usage: cad plot <project>/<assembly> <drawing.svg> [--calibrate]');
1120
+ if (!source && !opt('calibrate') && s.gait && !s.task?.sheet) return gaitPlot(m, s, ref);
1121
+ if (!source && !opt('calibrate')) throw new Error('usage: cad plot <project>/<assembly> <drawing.svg> [--calibrate], or cad plot <project>/<assembly> on an assembly with a gait');
1098
1122
  const { sheetFrame } = await import('@rulecad/robots'), f = s.task?.sheet ? sheetFrame(s.task.sheet) : null;
1099
1123
  const svg = opt('calibrate') ? m.CALIBRATION(f?.width ?? 148, f?.height ?? 210) : fs.readFileSync(source, 'utf8'), base = `${s.name}-${opt('calibrate') ? 'calibration' : path.basename(source, path.extname(source))}`;
1100
1124
  const r = m.plot(s, svg, { tolerance: tol, name: base });
@@ -1105,6 +1129,18 @@ async function machineCommand(what, ref) {
1105
1129
  process.exitCode = failed ? 1 : 0;
1106
1130
  }
1107
1131
 
1132
+ // A gait as a step file: --cycles (3), --period (s a cycle; default the gait's), --pose (where it starts and ends; default the one shown)
1133
+ async function gaitPlot(m, s, ref) {
1134
+ const cycles = opt('cycles') != null ? Number(opt('cycles')) : 3, period = opt('period') != null ? Number(opt('period')) : undefined;
1135
+ if (!Number.isInteger(cycles) || cycles < 1) throw new Error(`--cycles is a whole number, 1 or more (got ${opt('cycles')})`);
1136
+ if (period != null && !(period > 0)) throw new Error(`--period is the seconds of one cycle, above 0 (got ${opt('period')})`);
1137
+ const r = m.plotGait(s, { cycles, period, from: opt('pose') });
1138
+ if (opt('json')) { console.log(JSON.stringify({ ok: r.ok, findings: r.findings, time: r.time, ...(r.ok ? { file: m.writeGait(s, r).file } : {}) }, null, 2)); process.exitCode = r.ok ? 0 : 1; return; }
1139
+ report(r.findings, { assembly: ref, title: `${ref}: its gait` });
1140
+ if (r.ok) { const w = m.writeGait(s, r); console.log(path.relative(WS, w.file)); console.log(path.relative(WS, w.preview)); }
1141
+ process.exitCode = r.ok ? 0 : 1;
1142
+ }
1143
+
1108
1144
  async function platesCommand(what, ref) {
1109
1145
  if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
1110
1146
  const s = await buildAssembly(ref);
package/lib/machine.mjs CHANGED
@@ -2,31 +2,106 @@
2
2
  // the task. cad plot plans a drawing on it, checks it against the task, and shows the result before anything moves.
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
- import { svgToStrokes, orderStrokes, planToolpath, stepBlocks, estimate, sheetFrame, fk } from '@rulecad/robots';
5
+ import { svgToStrokes, orderStrokes, planToolpath, stepBlocks, estimate, sheetFrame, fk, gaitBlocks } from '@rulecad/robots';
6
+ import { gaitSequence } from './gait.mjs';
6
7
  import { trainFrom, workingSpeed } from './motors.mjs';
7
8
  import { chainOf, accuracyOf, sample, jacobianError } from './task.mjs';
8
9
  import { paths } from './workspace.mjs';
9
10
 
10
- const r6 = (x) => +Number(x).toFixed(6), n3 = (x, d = 2) => String(Number(x.toFixed(d)));
11
+ const num = Number.isFinite, r6 = (x) => +Number(x).toFixed(6), n3 = (x, d = 2) => String(Number(x.toFixed(d)));
11
12
 
12
- /** The machine as plain data. Every figure's origin is said in _why, by the name of the figure. @param {object} s a built assembly with a task */
13
+ // One driven joint as an axis: its motor, the steps it takes a degree (or mm) through its train, and the fastest it steps
14
+ function axisOf(s, id) {
15
+ const motion = s.motion, t = trainFrom(motion, id), d = motion.drives.find((x) => x.joint === t.root), j = motion.joints.find((x) => x.id === id), spec = new Map((s.a.joints || []).map((x) => [x.id, x])).get(id) ?? {};
16
+ if (!d?.model.stepAngle) throw new Error(`${s.project}/${s.name}: joint ${id} has no stepper driving it, and a step file needs one`);
17
+ const micro = d.spec.microsteps ?? 16, per = (360 / d.model.stepAngle) * micro, stepsPerUnit = j.type === 'prismatic' ? (per * t.ratio) / t.slide / 360 : (per * t.ratio) / 360;
18
+ const rpm = workingSpeed(d.model, d.spec, d.supply), maxRate = (rpm / 60) * per, home = spec.home;
19
+ const homing = home ? { endstop: home.endstop, direction: home.direction ?? -1, rate: Math.round(maxRate / 8), back: Math.round(stepsPerUnit * 3) } : null;
20
+ return { name: id, joint: id, motor: d.id, model: d.model.name, driver: d.spec.driver ?? null, stepAngle: d.model.stepAngle, microsteps: micro, ratio: r6(t.ratio), stepsPerUnit: r6(stepsPerUnit), unit: j.type === 'prismatic' ? 'mm' : 'deg', limits: (j.limits ?? j.dofs[0].slice(0, 2)).map(r6), maxRate: Math.round(maxRate), homing,
21
+ _why: { stepAngle: `${d.model.name}.step_angle`, microsteps: d.spec.microsteps != null ? `the motor item's "microsteps" (resolution only, not accuracy)` : 'the default, 1/16 (resolution only, not accuracy)', ratio: t.stages.length ? `the train from ${t.root} to ${id}` : 'direct', maxRate: `${n3(rpm, 1)} rpm, ${d.spec.speed != null ? 'the motor item\'s speed' : `the working speed of a ${d.model.name}`}` } };
22
+ }
23
+
24
+ /** The slots of a CNC shield each motor is wired to, by motor item: from a wire "<motor>.<anchor>" to "<item>.X" (X, Y, Z or A). */
25
+ export function shieldSlots(a) {
26
+ const out = {};
27
+ for (const w of a.wires || []) { const [from, to] = [String(w.from), String(w.to)], m = /^[^.]+\.([XYZA])$/.exec(to); if (m) out[from.split('.')[0]] = m[1]; }
28
+ return out;
29
+ }
30
+ /** The step and direction slots of the streamer (arm.ino on a CNC Shield V3), in its axis order: axis 0 on X, 1 on Y, 2 on Z. */
31
+ export const STREAMER_SLOTS = ['X', 'Y', 'Z'];
32
+
33
+ /** The machine as plain data. Every figure's origin is said in _why, by the name of the figure. A machine with a gait and no
34
+ * task is its legs: an axis for each joint a motor turns, in the order the shield's slots are wired. @param {object} s a built assembly with a task or a gait */
13
35
  export function machineOf(s) {
14
- if (!s.task) throw new Error(`${s.project}/${s.name} has no "task": a machine says what it is for`);
15
- const c = chainOf(s), motion = s.motion, specs = new Map((s.a.joints || []).map((j) => [j.id, j]));
16
- const axes = c.names.map((id) => {
17
- const t = trainFrom(motion, id), d = motion.drives.find((x) => x.joint === t.root), j = motion.joints.find((x) => x.id === id), spec = specs.get(id) ?? {};
18
- if (!d?.model.stepAngle) throw new Error(`${s.project}/${s.name}: joint ${id} has no stepper driving it, and a step file needs one`);
19
- const micro = d.spec.microsteps ?? 16, per = (360 / d.model.stepAngle) * micro, stepsPerUnit = j.type === 'prismatic' ? (per * t.ratio) / t.slide / 360 : (per * t.ratio) / 360;
20
- const rpm = workingSpeed(d.model, d.spec, d.supply), maxRate = (rpm / 60) * per, home = spec.home;
21
- const homing = home ? { endstop: home.endstop, direction: home.direction ?? -1, rate: Math.round(maxRate / 8), back: Math.round(stepsPerUnit * 3) } : null;
22
- return { name: id, joint: id, motor: d.id, model: d.model.name, driver: d.spec.driver ?? null, stepAngle: d.model.stepAngle, microsteps: micro, ratio: r6(t.ratio), stepsPerUnit: r6(stepsPerUnit), unit: j.type === 'prismatic' ? 'mm' : 'deg', limits: (j.limits ?? j.dofs[0].slice(0, 2)).map(r6), maxRate: Math.round(maxRate), homing,
23
- _why: { stepAngle: `${d.model.name}.step_angle`, microsteps: d.spec.microsteps != null ? `the motor item's "microsteps" (resolution only, not accuracy)` : 'the default, 1/16 (resolution only, not accuracy)', ratio: t.stages.length ? `the train from ${t.root} to ${id}` : 'direct', maxRate: `${n3(rpm, 1)} rpm, ${d.spec.speed != null ? 'the motor item\'s speed' : `the working speed of a ${d.model.name}`}` } };
24
- });
36
+ if (!s.task && s.gait) return gaitMachineOf(s);
37
+ if (!s.task) throw new Error(`${s.project}/${s.name} has no "task" and no "gait": a machine says what it is for`);
38
+ const c = chainOf(s), motion = s.motion;
39
+ const axes = c.names.map((id) => axisOf(s, id));
25
40
  const kinematics = c.names.length === 2 && motion.joints.filter((j) => c.names.includes(j.id)).every((j) => j.type === 'revolute') ? 'scara' : motion.joints.filter((j) => c.names.includes(j.id)).every((j) => j.type === 'prismatic') ? 'cartesian' : 'serial';
26
41
  const pen = s.a.task.pen ?? null;
27
42
  return { format: 'rulecad.machine/1', name: `${s.project}/${s.name}`, kinematics, tool: s.task.tool, elbow: sample(s).elbow, axes, task: { sheet: s.a.task.sheet ?? null, region: s.a.task.region ?? null, volume: s.a.task.volume ?? null, speed: s.task.speed, accuracy: s.task.accuracy, accel: s.task.accel ?? 500, ...(s.task.blockTime ? { blockTime: s.task.blockTime } : {}) }, ...(pen ? { pen } : {}) };
28
43
  }
29
44
 
45
+ function gaitMachineOf(s) {
46
+ const seq = gaitSequence(s), slots = shieldSlots(s.a);
47
+ let axes = seq.names.map((id) => { const a = axisOf(s, id); return { ...a, ...(slots[a.motor] ? { slot: slots[a.motor] } : {}) }; });
48
+ if (axes.every((a) => STREAMER_SLOTS.includes(a.slot))) axes = [...axes].sort((a, b) => STREAMER_SLOTS.indexOf(a.slot) - STREAMER_SLOTS.indexOf(b.slot));
49
+ const g = s.gait, pattern = typeof s.a.gait.pattern === 'string' ? s.a.gait.pattern : `duty ${s.a.gait.pattern?.duty}`;
50
+ return { format: 'rulecad.machine/1', name: `${s.project}/${s.name}`, kinematics: 'legged', tool: null, axes, task: null,
51
+ gait: { legs: g.legs.map((l) => l.name), pattern, period: g.period, stride: g.stride, lift: g.lift, height: g.height, frames: seq.q.length } };
52
+ }
53
+
54
+ /**
55
+ * A gait as a step file: its cycle played for some cycles from a pose of the assembly and back to it, every leg's joints
56
+ * in the same blocks. Findings say how long a cycle takes on the motors against the gait's period, and whether the
57
+ * streamer can take the file: three axes at most, each on the shield's slot of its own number.
58
+ * @param {object} s a built assembly with a gait @param {{ cycles?: number, period?: number, from?: string }} [o] from: a pose's name (default the pose the assembly shows)
59
+ */
60
+ export function plotGait(s, { cycles = 3, period, from } = {}) {
61
+ if (!s.gait) throw new Error(`${s.project}/${s.name} has no "gait" to play`);
62
+ const m = machineOf(s), seq = gaitSequence(s), names = m.axes.map((a) => a.name), cols = names.map((n) => seq.names.indexOf(n));
63
+ const ordered = { period: seq.period, names, q: seq.q.map((r) => cols.map((i) => r[i])) };
64
+ const poses = s.motion.poses || {}, poseName = from ?? s.motion.pose ?? null;
65
+ if (from != null && !poses[from]) throw new Error(`--pose ${from}: no such pose (poses: ${Object.keys(poses).join(', ') || 'none'})`);
66
+ const pose = poseName ? poses[poseName] : null, findings = [];
67
+ const start = pose && names.every((n) => num(pose[n])) ? names.map((n) => pose[n]) : null;
68
+ if (poseName && !start) findings.push({ level: 'info', text: `the pose "${poseName}" does not set ${names.filter((n) => !num(pose?.[n])).join(', ')}, so the file starts and ends at the cycle's first frame`, code: 'gait.from', values: {} });
69
+ const r = gaitBlocks(ordered, { axes: m.axes.map((a) => ({ name: a.name, stepsPerUnit: a.stepsPerUnit, maxRate: a.maxRate, unit: a.unit })), cycles, ...(period != null ? { period } : {}), ...(start ? { from: start } : {}) });
70
+ findings.push(...r.findings);
71
+ // the streamer: three axes, axis k on the shield's slot X, Y or Z in that order
72
+ if (names.length > STREAMER_SLOTS.length) findings.push({ level: 'warn', text: `${names.length} axes, and the streamer steps ${STREAMER_SLOTS.length} (an Uno under a CNC Shield V3): the file is written, and send.mjs refuses it`, code: 'stream.axes', values: { axes: names.length, streamer: STREAMER_SLOTS.length } });
73
+ else for (const [k, a] of m.axes.entries()) {
74
+ if (!a.slot) findings.push({ level: 'info', text: `${a.name}'s motor ${a.motor} has no wire to a shield's slot: the streamer steps it as axis ${k}, on ${STREAMER_SLOTS[k]}`, code: 'stream.wiring', refs: { item: a.motor } });
75
+ else if (a.slot !== STREAMER_SLOTS[k]) findings.push({ level: 'fail', text: `${a.name}'s motor ${a.motor} is wired to the shield's ${a.slot}, and the streamer steps axis ${k} on ${STREAMER_SLOTS[k]}`, code: 'stream.wiring', refs: { item: a.motor } });
76
+ }
77
+ const n = r.blocks.length;
78
+ findings.push({ level: 'info', text: `${cycles} cycle${cycles === 1 ? '' : 's'} of the gait (${m.gait.pattern}) in ${n} blocks, ${n3(r.time, 1)} s${start ? `, from the pose "${poseName}" and back to it` : ''}`, code: 'plot.time', values: { time: r.time, cycles, blocks: n } });
79
+ const steps = { ...r, machine: m.name, drawing: 'gait', ...(start ? { pose: poseName } : {}) };
80
+ return { ok: findings.every((x) => x.level !== 'fail'), findings, steps, machine: m, time: { time: r.time } };
81
+ }
82
+
83
+ // A picture of a gait's step file: each axis's position through the run, from its blocks, with the gait's frames as dots
84
+ export function gaitPicture(result) {
85
+ const f = result.steps, W = 720, H = 160, pad = 40, colours = ['#135', '#c33', '#383', '#a60'];
86
+ const series = f.axes.map(() => []);
87
+ let t = 0, pos = [...f.start];
88
+ series.forEach((p, k) => p.push([0, pos[k] / f.axes[k].stepsPerUnit]));
89
+ for (const b of f.blocks) { t += b.time; pos = pos.map((x, k) => x + b.steps[k]); series.forEach((p, k) => p.push([t, pos[k] / f.axes[k].stepsPerUnit, b.kind])); }
90
+ const panels = series.map((p, k) => {
91
+ const lo = Math.min(...p.map((x) => x[1])), hi = Math.max(...p.map((x) => x[1])), y = (v) => H - 20 - ((v - lo) / (hi - lo || 1)) * (H - 40), x = (s) => pad + (s / (t || 1)) * (W - 2 * pad);
92
+ const line = p.map(([s, v]) => `${n3(x(s))},${n3(y(v))}`).join(' '), dots = p.filter((q) => q[2] === 'gait').map(([s, v]) => `<circle cx="${n3(x(s))}" cy="${n3(y(v))}" r="1.6" fill="${colours[k % 4]}"/>`).join('');
93
+ return `<g transform="translate(0 ${k * H})"><text x="${pad}" y="14" font-size="12" font-family="sans-serif">${f.axes[k].name}: ${n3(lo, 0)} to ${n3(hi, 0)} ${f.axes[k].unit} (the motor's shaft)</text><polyline points="${line}" fill="none" stroke="${colours[k % 4]}" stroke-width="1"/>${dots}</g>`;
94
+ }).join('');
95
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H * series.length + 24}" viewBox="0 0 ${W} ${H * series.length + 24}"><rect width="100%" height="100%" fill="#fff"/>${panels}<text x="${pad}" y="${H * series.length + 16}" font-size="12" font-family="sans-serif">${n3(t, 1)} s: ${f.cycles} cycles, ${n3(f.cycleTime, 2)} s each against the gait's ${f.period} s; dots are the gait's frames</text></svg>\n`;
96
+ }
97
+
98
+ export function writeGait(s, result) {
99
+ const dir = paths.exports(s.project); fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, `${s.name}-gait.steps.json`);
100
+ fs.writeFileSync(file, JSON.stringify(result.steps));
101
+ const prev = paths.preview(s.project, `${s.name}-gait.svg`); fs.mkdirSync(path.dirname(prev), { recursive: true }); fs.writeFileSync(prev, gaitPicture(result));
102
+ return { file, preview: prev };
103
+ }
104
+
30
105
  // A drawing's size against the sheet: the first stroke that leaves it, named
31
106
  function fitsSheet(strokes, frame) {
32
107
  const off = [];
package/lib/optimise.mjs CHANGED
@@ -11,7 +11,7 @@ import { host, readJson } from './host.mjs';
11
11
  import { paths, printerOf } from './workspace.mjs';
12
12
  import { resolve, evaluate } from './rules.mjs';
13
13
  import { located } from './errors.mjs';
14
- import { discretise, optimise, outlines, surface, area, bounds, resultant, printable, refine, despike } from '@rulecad/topopt';
14
+ import { discretise, optimise, outlines, surface, area, bounds, resultant, printable, refine, despike, undercuts, voids, grey } from '@rulecad/topopt';
15
15
  import { islands } from '@rulecad/printcheck';
16
16
  import { threadsBackend } from '@rulecad/fea/threads'; // the solver's products shared over the machine's cores
17
17
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
@@ -77,6 +77,9 @@ export async function readProblem(project, ref) {
77
77
  ...(p.filter != null ? { filter: ev(p.filter) } : {}), ...(p.penal != null ? { penal: ev(p.penal) } : {}),
78
78
  ...(p.projection != null ? { projection: p.projection } : {}), ...(p.steps != null ? { steps: p.steps } : {}),
79
79
  ...(overhang && overhang !== 'none' ? { overhang } : {}),
80
+ // How it's made other than printed: milled from a side, cast in a mould; symmetric, extruded (topopt's filters)
81
+ ...(p.mill ? { mill: p.mill } : {}), ...(p.cast ? { cast: typeof p.cast === 'string' ? p.cast : { draw: p.cast.draw, ...(p.cast.parting != null ? { parting: ev(p.cast.parting) } : {}) } } : {}),
82
+ ...(p.symmetry ? { symmetry: p.symmetry } : {}), ...(p.extrude ? { extrude: p.extrude } : {}),
80
83
  // A mechanism: where the output should move, along one axis, against a spring; a spring the input pushes against
81
84
  ...(p.output ? { output: { ...(await region(p.output)), direction: pt(p.output.direction), ...(p.output.spring != null ? { spring: ev(p.output.spring) } : {}) } } : {}),
82
85
  ...(p.input_spring != null ? { input_spring: ev(p.input_spring) } : {}),
@@ -87,7 +90,7 @@ export async function readProblem(project, ref) {
87
90
  // (outline.tip: faces the smoothing left steeper than the limit are tipped back to it too; off unless asked, since
88
91
  // tipped corners leave dips that slice as islands, and the layers step out no further for it)
89
92
  if (dim === 3 && problem.overhang) { const n = printerOf(project), pr = resolve({ uses: [n] }).values[n]; outline.overhang = { up: problem.overhang, angle: pr?.overhang ?? 45, bridge: pr?.bridge ?? 5, layer: pr?.layer ?? 0.2, line: pr?.line ?? 0.42, ...(p.outline?.tip ? { tip: true } : {}) }; problem.bridge = outline.overhang.bridge; } // (the optimiser bridges half that)
90
- return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline, critical: !!p.critical };
93
+ return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline, critical: !!p.critical, voids: p.voids || 'allowed' };
91
94
  }
92
95
 
93
96
  /**
@@ -105,6 +108,23 @@ function holdEmpty(spec) {
105
108
  for (let m = 0; m < g.nodes; m++) if (!on[m]) for (let a = 0; a < dim; a++) spec.fixed[dim * m + a] = 1;
106
109
  return spec;
107
110
  }
111
+ // How a result is made, and what that process can't make in it: for a milled or cast part, the cells a tool or mould
112
+ // half could not reach (undercuts, none by construction unless an avoid region or the space's own shape leaves material between a cell and its side), how grey it is; where enclosed voids are
113
+ // refused (a powder bed print, a trapped core), each void with its volume (mm³, or mm² in 2D) and where it is
114
+ function made(r, spec, density) {
115
+ const p = r.problem, out = {};
116
+ if (p.mill || p.cast) {
117
+ const c = spec.cast, from = p.mill || (typeof c === 'string' ? c : c.draw), u = undercuts(spec.grid, density, { from, ...(c && typeof c === 'object' ? { parting: c.parting } : {}) });
118
+ out.process = p.mill ? { mill: p.mill } : { cast: typeof c === 'string' ? c : { draw: c.draw, parting: round(c.at, 3) } };
119
+ out.undercuts = u.count;
120
+ }
121
+ if (p.symmetry) out.symmetry = p.symmetry;
122
+ if (p.extrude) out.extrude = p.extrude;
123
+ // How grey it came out: a process or a tie can leave no clear part (a 2D section milled from its side)
124
+ if (p.mill || p.cast || p.symmetry || p.extrude) out.grey = round(grey(density, spec.passive), 3);
125
+ if (r.voids === 'refused') out.voids = voids(spec.grid, density, { origin: spec.origin }).map((v) => ({ volume: round(v.volume, 3), at: v.at.map((x) => round(x, 3)) }));
126
+ return out;
127
+ }
108
128
  const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
109
129
  /**
110
130
  * The code an optimisation's densities are made by, each piece by name: this file's VERSION, topopt's solver (its file
@@ -126,7 +146,7 @@ export async function optimised(project, ref, { onStep, onRun, fresh = false } =
126
146
  // Two keeps: the densities, by the problem and the code that decides them (the slow part), and the shape drawn from
127
147
  // them, by everything: a change to how shapes are drawn redraws them without optimising again
128
148
  // The shape's key holds this file too, so a change to how cad draws a result (anchored below) redraws it
129
- const hash = digest([VERSION, r.problem, r.outline, topopt, source('@rulecad/fea'), fs.readFileSync(new URL(import.meta.url), 'utf8')]), file = paths.cache('optimise', `${hash}.json`);
149
+ const hash = digest([VERSION, r.problem, r.outline, r.voids, topopt, source('@rulecad/fea'), fs.readFileSync(new URL(import.meta.url), 'utf8')]), file = paths.cache('optimise', `${hash}.json`);
130
150
  if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file)) return { ...JSON.parse(host.readText(file)), cached: true };
131
151
  const spec = holdEmpty(discretise(r.problem)), densities = paths.cache('densities', `${densitiesKey(r.problem)}.json`);
132
152
  // A mark that this problem has been optimised before (by any solver), so a run can say whether it's the solver that changed
@@ -206,6 +226,7 @@ export async function optimised(project, ref, { onStep, onRun, fresh = false } =
206
226
  const result = {
207
227
  problem: ref, title: r.title, hash, dim: r.dim, material: r.material.name, ...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
208
228
  grid: spec.grid, origin: spec.origin, regions: { keep: named(spec.regions.keep), avoid: named(spec.regions.avoid) }, ...shape,
229
+ ...made(r, spec, o.density),
209
230
  volume: o.volume, compliance: o.compliance, cases: o.cases, ...(o.unsupported ? { unsupported: o.unsupported } : {}), ...(o.mechanism ? { mechanism: o.mechanism } : {}), ...(o.stress ? { stress: o.stress } : {}), overhang: r.problem.overhang || null,
210
231
  steps: o.steps, converged: o.converged, seconds: o.seconds, history: o.history, density: Array.from(o.density, (d) => round(d, 3)),
211
232
  supports: named(r.problem.supports), loads: named(r.problem.loads),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.70",
3
+ "version": "0.7.77",
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": {
@@ -65,16 +65,16 @@
65
65
  "@rulecad/model-link": "^0.3.2",
66
66
  "@rulecad/versions": "^0.1.6",
67
67
  "@rulecad/shapes": "^0.4.6",
68
- "@rulecad/rules": "^0.3.20",
68
+ "@rulecad/rules": "^0.3.22",
69
69
  "@jscad/modeling": "^2.12.0",
70
70
  "three": "^0.186.1",
71
71
  "@rulecad/fea": "^0.2.11",
72
- "@rulecad/topopt": "^0.3.0",
72
+ "@rulecad/topopt": "^0.3.4",
73
73
  "@rulecad/flexures": "^0.5.4",
74
74
  "@rulecad/gears": "^0.3.4",
75
75
  "@rulecad/motors": "^0.1.6",
76
76
  "@rulecad/fixings": "^0.1.7",
77
- "@rulecad/robots": "^0.1.3",
77
+ "@rulecad/robots": "^0.1.4",
78
78
  "@rulecad/frames": "^0.1.12"
79
79
  },
80
80
  "peerDependencies": {
@@ -155,6 +155,44 @@
155
155
  "type": "string",
156
156
  "description": "3D: printable this way up ('+z', '-y', …), or a variable holding it, or 'none': only material supported from below at 45° or less"
157
157
  },
158
+ "symmetry": {
159
+ "type": "object",
160
+ "additionalProperties": false,
161
+ "description": "The same either side of the grid's middle planes, and each half or quarter turn about its middle. The grid is centred on the space and keep regions (in 3D, except along an overhang's build direction). Keep and avoid regions stay as given. A mirror or turn that would swap the side a part is milled from, the way a mould is drawn off or the build direction for its opposite (or a quarter turn that moves it onto another axis) is refused by name; a mould in two halves parted at the grid's middle can be mirrored or half turned across its draw.",
162
+ "properties": {
163
+ "mirror": { "type": "string", "pattern": "^[xyz]{1,3}$", "description": "The axes mirrored across: 'x', 'xy', 'xyz' (2D: x and y)" },
164
+ "turns": { "enum": [2, 4], "description": "The same each half turn (2) or quarter turn (4) about the middle; a quarter turn needs the grid as wide both ways across its axis" },
165
+ "axis": { "enum": ["x", "y", "z"], "description": "3D: the axis turns are about (default z)" }
166
+ }
167
+ },
168
+ "extrude": {
169
+ "enum": ["x", "y", "z"],
170
+ "description": "One section all along this axis: a part cut from a bar, an extrusion or a plate of the profile"
171
+ },
172
+ "mill": {
173
+ "type": "string",
174
+ "pattern": "^[+-][xyz]$",
175
+ "description": "Milled from this side ('+z': the tool cuts down from above): no undercuts, so a cell is as solid as every cell between it and the tool. Not with overhang or cast. Rules: mill-3axis"
176
+ },
177
+ "cast": {
178
+ "description": "Cast or moulded: in a mould drawn off one way ('+z'), or in two halves drawn off both ways along an axis from a parting plane. No undercuts from the draw; draft is left to the drawing. Not with overhang or mill. Rules: mould-injection",
179
+ "oneOf": [
180
+ { "type": "string", "pattern": "^[+-][xyz]$" },
181
+ {
182
+ "type": "object",
183
+ "additionalProperties": false,
184
+ "required": ["draw"],
185
+ "properties": {
186
+ "draw": { "enum": ["x", "y", "z"], "description": "The axis the halves are drawn off along" },
187
+ "parting": { "$ref": "#/$defs/expr", "description": "The parting plane, mm along draw (default the space's middle)" }
188
+ }
189
+ }
190
+ ]
191
+ },
192
+ "voids": {
193
+ "enum": ["allowed", "refused"],
194
+ "description": "Enclosed voids in the result: allowed (the default), or refused, for metal powder bed printing (powder left inside can't be got out) or a casting's trapped core: cad optimise then reports each as an error with its volume and where it is. Rules: dmls"
195
+ },
158
196
  "output": {
159
197
  "type": "object",
160
198
  "additionalProperties": false,