@rulecad/cad 0.7.46 → 0.7.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/EXAMPLES.md CHANGED
@@ -1214,8 +1214,14 @@ speed to it.
1214
1214
  ```sh
1215
1215
  npx cad check home/winder-driven # warns: nothing says whether it holds with the power off
1216
1216
  npx cad check home/winder-driven --sweep --steps 12 # warns, as above
1217
+ npx cad animate home/winder-driven
1218
+ npx cad preview home/winder-driven --check
1217
1219
  ```
1218
1220
 
1221
+ `cad animate` cuts the gearbox across its shafts and turns it: the planets roll round the held ring as the sun turns,
1222
+ and the reel, picked out as the part with the load, turns a quarter as far. `cad preview --check` labels the motor's
1223
+ torque where it starts and where it arrives, with the margin and the open question of holding unpowered.
1224
+
1219
1225
  The check says the sun drives the carrier at a quarter of its speed, the shaft has 6.6 mm of its flat in the sun's
1220
1226
  bore, and the motor gives `0.45 N m there against 0.2 N m needed, 2.25 times over (rests on derived figures)`: scaled
1221
1227
  from the 100:1 gearbox's, so measure it. It takes a DC motor's working speed as half its free speed: the reel at
package/README.md CHANGED
@@ -420,6 +420,7 @@ An item can be a motor instead of a printed object: `{ "id": "drive", "motor": {
420
420
  - `motor.mount`: the part a motor is fastened to (a `fastens` fit), read as drawn: how thick it is at the screw holes against the screws' size, and the screws' bearing on the plastic under the motor's full torque. 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`.
421
421
  - `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.
422
422
  - 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`).
423
+ - `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.
423
424
  - `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.
424
425
 
425
426
  ### Building it
@@ -663,6 +664,8 @@ moving bodies in blue and the flexures in orange, drawn bent, holding a moment a
663
664
 
664
665
  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.
665
666
 
667
+ 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.
668
+
666
669
  ## Checks
667
670
 
668
671
  - **Closed solids:** every edge must be matched by faces on the other side. T-junctions (an edge covered by several
package/bin/cad.mjs CHANGED
@@ -55,9 +55,11 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
55
55
  cad add fit|joint|item|loop|pose <project>/<assembly> --a … --b … --min … add to an assembly, keeping its layout
56
56
  cad why <project>/<object>.<name> what a value reads, down to the rules and their sources [--json] [--depth N]
57
57
  cad check <project>/<object> raw numbers in the design, then printability (exit 1 on a failure) [--json: findings as data]
58
- cad preview <project>/<object> six views as a PNG in .preview/ (prints the path)
58
+ cad preview <project>/<object> six views as a PNG in .preview/ (prints the path); an assembly with a motor also gets
59
+ its curve and its train as SVGs, and --check labels the torque at each joint it drives
59
60
  cad animate <project>/<object> a lamina mechanism's sequence, or an assembly's gait, start to finish, in .preview/: an animated SVG, the
60
- data (shapes, forces, energies, strains each frame, JSON) and a page that plays it
61
+ data (shapes, forces, energies, strains each frame, JSON) and a page that plays it; an
62
+ assembly with a motor or gears: the drive turning them, cut across the shafts [--turns n]
61
63
  cad optimise <project>/<problem> the stiffest layout for a problem in the project's problems/ (name:variant for a
62
64
  variant): a picture in .preview/, the result kept for designs [--fresh] [--json]
63
65
  [--watch [port]: a live view of it at http://127.0.0.1:8090/, with a stop button]
@@ -117,7 +119,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
117
119
  // Every command and option there is: a misspelt one is refused by name, not passed over
118
120
  const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
119
121
  'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'wires', 'machine', 'plot', 'plates', 'order', 'match', 'variants', 'compare', 'help'];
120
- const OPTIONS = ['table', 'calibrate', 'preview', 'gap', 'no-steps', 'all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
122
+ 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',
121
123
  'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
122
124
  'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
123
125
  'unit', 'rule', 'label', 'from', 'out', // cad set, cad rules
@@ -130,7 +132,7 @@ const USAGE = { add: 'fit|joint|item|loop|pose <project>/<assembly> --key value
130
132
  const args = process.argv.slice(2);
131
133
  // Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
132
134
  // (--sweep and --watch take one or not).
133
- const FLAGS = ['table', 'calibrate', 'preview', 'no-steps', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short'];
135
+ const FLAGS = ['table', 'calibrate', 'check', 'preview', 'no-steps', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short'];
134
136
  const opt = (k) => {
135
137
  const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
136
138
  if (i < 0) return undefined;
@@ -666,7 +668,12 @@ async function assembly(cmd, ref) {
666
668
  return;
667
669
  }
668
670
  if (cmd === 'animate') {
669
- if (!s.gait) throw new Error(`${ref} has no gait: cad animate plays a gait ("gait" at the top of the assembly), or a lamina mechanism's sequence`);
671
+ if (!s.gait) { // a motor turning what it drives: the gears cut across their shafts, the load's part turning with them
672
+ const { driveSvg } = await import('../lib/drive.mjs'), out = paths.preview(s.project, `${s.name}-drive.svg`);
673
+ fs.mkdirSync(path.dirname(out), { recursive: true });
674
+ fs.writeFileSync(out, driveSvg(s, { title, ...(opt('turns') ? { turns: Number(opt('turns')) } : {}) }));
675
+ return console.log(out);
676
+ }
670
677
  const { gaitSvg, gaitData } = await import('../lib/animate.mjs'), { framesOf } = await import('../lib/gait.mjs'), r = framesOf(s);
671
678
  if (!r.frames.length) throw new Error(`${ref}'s gait has nothing to play: ${r.findings.map((x) => x.text).join('; ')}`);
672
679
  const svg = paths.preview(s.project, `${s.name}-gait.svg`), json = paths.preview(s.project, `${s.name}-gait.json`);
@@ -675,13 +682,19 @@ async function assembly(cmd, ref) {
675
682
  console.log(svg); return console.log(json);
676
683
  }
677
684
  if (cmd === 'preview') {
678
- const out = paths.preview(s.project, `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}.png`);
685
+ const check = !!opt('check'); // the check view: each motor's torque labelled at its joints, never on the rest view
686
+ const out = paths.preview(s.project, `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}${check ? '-check' : ''}.png`);
687
+ let marks = null;
688
+ if (check) {
689
+ if (!s.motion?.drives?.length) throw new Error(`${ref} has no motor: cad preview --check labels the torque a motor sends through its joints`);
690
+ marks = (await import('../lib/motorsvg.mjs')).workMarks(s);
691
+ }
679
692
  const size = (await import('@rulecad/printcheck')).bounds(s.triangles).size.map((n) => fmt(n)).join(' × ');
680
693
  const faint = [...new Set(s.parts.filter((p) => p.role !== 'part').map((p) => `${p.object || p.item}${p.role === 'support' ? ' supports' : ''}`))]; // each kind once
681
- await preview([...s.parts, ...wireTubesOf(s)], { title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode') });
694
+ await preview([...s.parts, ...wireTubesOf(s)], { title: check ? `${title}: the motor at work` : title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode'), marks });
682
695
  // each motor at work beside it: its curve with the working point, and the torque through its train (said before
683
696
  // the picture, which stays the last line, for whatever reads it)
684
- if (s.motion?.drives?.length && !pose && !opt('explode')) {
697
+ if (s.motion?.drives?.length && !pose && !opt('explode') && !check) {
685
698
  const { motorWork, workCurve, trainSvg } = await import('../lib/motorsvg.mjs');
686
699
  for (const w of motorWork(s)) {
687
700
  for (const [kind, svg] of [['curve', workCurve(w)], ['train', trainSvg(w)]]) {
package/lib/drive.mjs ADDED
@@ -0,0 +1,133 @@
1
+ // A motor turning what it drives, as one animated SVG: the gears cut across their shafts, each part's outline drawn
2
+ // once and moved as a rigid body (a turn and a slide per frame), so a gearbox of fine teeth stays small. A section is
3
+ // taken at the middle of each gear (rings, suns, planets) and of the part with the load, up to three, side by side.
4
+ import { jointValues, placeItems, mul } from '@rulecad/model-link';
5
+ import { axisFrame, sliceAt } from './seats.mjs';
6
+ import { loops } from './mesh.mjs';
7
+ import { trainFrom, axisOf } from './motors.mjs';
8
+
9
+ const fmt = (n) => +Number(n).toFixed(3);
10
+ const esc = (s) => String(s).replace(/[<>&"]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' })[c]);
11
+ const rowsAt = (W, p) => [0, 1, 2].map((k) => W[4 * k] * p[0] + W[4 * k + 1] * p[1] + W[4 * k + 2] * p[2] + W[4 * k + 3]);
12
+ const COLOUR = { still: '#c9ccd1', moves: '#2f6fb3', load: '#e07a1f', bought: '#e9eaec' };
13
+
14
+ /**
15
+ * What the drive moves and where to cut: the joint the motor turns (or a gearbox's input), the joint with the load, the
16
+ * levels across the axis to section at, and how far to turn so the slowest part moves a readable amount.
17
+ */
18
+ export function drivePlan(s, { turns } = {}) {
19
+ const motion = s.motion, d = (motion.drives || []).find((x) => x.joint);
20
+ const root = d?.joint ?? motion.joints.find((j) => !j.follow && motion.joints.some((x) => x.follow?.[0] === j.id))?.id;
21
+ if (!root) return null;
22
+ const load = (motion.loads || []).find((l) => l.joint)?.joint ?? motion.joints.filter((j) => trainFrom(motion, j.id).root === root && j.id !== root).sort((a, b) => trainFrom(motion, b.id).ratio - trainFrom(motion, a.id).ratio)[0]?.id ?? root;
23
+ const ratio = Math.abs(trainFrom(motion, load).ratio) || 1;
24
+ const n = turns ?? Math.min(6, Math.max(1, (ratio * 60) / 360)); // the slowest part through about 60°, in one to six turns
25
+ return { root, load, motor: d?.id ?? null, ratio, turns: n };
26
+ }
27
+
28
+ export function driveSvg(s, { turns, title = '' } = {}) {
29
+ const plan = drivePlan(s, { turns });
30
+ if (!plan) throw new Error(`${s.name} has nothing driven to animate: give it a "motor" item that "drives" a joint, or gears that follow one`);
31
+ const motion = s.motion, rootJ = motion.joints.find((j) => j.id === plan.root);
32
+ const v0 = jointValues(motion, motion.pose ?? undefined), W0 = placeItems(motion, v0);
33
+ const { O, Z } = axisOf(motion, W0, rootJ, mul), F = axisFrame(O, Z);
34
+ const indexOf = new Map(s.items.map((it, k) => [it.id, k]));
35
+ const loadItem = motion.joints.find((j) => j.id === plan.load)?.child;
36
+ // Every part, in the axis's frame at rest: what's cut, and what it belongs to
37
+ const parts = s.parts.map((p) => ({ p, k: indexOf.get(p.item), world: p.triangles.map((t) => t.map(F)) })).filter((x) => x.k != null && x.world.length);
38
+ const span = (x) => { let lo = Infinity, hi = -Infinity; for (const t of x.world) for (const q of t) { lo = Math.min(lo, q[2]); hi = Math.max(hi, q[2]); } return [lo, hi]; };
39
+ // Where to cut: through each gear's teeth (the height whose section has the most edges, the middle of that run),
40
+ // rings named in a planetary included, and through the middle of what carries the load
41
+ const geared = new Set([...(motion.meshes || []).flatMap((m) => [m.joint, ...(m.members || [])]), ...motion.joints.filter((j) => j.follow).flatMap((j) => [j.id, j.follow[0]])]);
42
+ const childOf = new Map(motion.joints.map((j) => [j.id, j.child]));
43
+ const ringItems = new Set((s.a.planetary || []).flatMap((g) => [g.ring, g.output?.ring]).filter(Boolean).map((id) => indexOf.get(id)));
44
+ const gearItems = new Set([...[...geared].map((id) => childOf.get(id)), ...ringItems].filter((k) => k != null));
45
+ const teethAt = (x) => {
46
+ const [lo, hi] = span(x), n = Math.min(160, Math.max(8, Math.round((hi - lo) / 0.25))), counts = [];
47
+ for (let i = 1; i < n; i++) { const z = lo + ((hi - lo) * i) / n; counts.push([z, sliceAt(x.world, z).length]); }
48
+ const top = Math.max(...counts.map((c) => c[1])), run = counts.filter((c) => c[1] >= top * 0.9).map((c) => c[0]);
49
+ return run.length ? (run[0] + run.at(-1)) / 2 : (lo + hi) / 2;
50
+ };
51
+ const want = [];
52
+ for (const k of gearItems) { const own = parts.filter((x) => x.k === k && x.p.role === 'part'); if (own.length) want.push({ z: teethAt({ world: own.flatMap((x) => x.world) }), ring: ringItems.has(k) }); }
53
+ if (loadItem != null && !gearItems.has(loadItem)) { const own = parts.filter((x) => x.k === loadItem && x.p.role === 'part'); if (own.length) { const [lo, hi] = span({ world: own.flatMap((x) => x.world) }); want.push({ z: (lo + hi) / 2, ring: false }); } }
54
+ want.sort((a, b) => b.ring - a.ring || a.z - b.z);
55
+ const levels = [];
56
+ for (const { z } of want) if (!levels.some((l) => Math.abs(l - z) < 1.5)) levels.push(z);
57
+ const picked = levels.slice(0, 3).sort((a, b) => a - b); // rings first, then the rest, three at most
58
+ // The frames: the root turned through its turns, each item's rigid move in the plane from two points on it
59
+ const N = Math.min(240, Math.max(24, Math.round(plan.turns * 40))), base = v0[plan.root]?.[0] ?? 0;
60
+ const ks = [...new Set(parts.map((x) => x.k))], moves = new Map(ks.map((k) => [k, []]));
61
+ for (let f = 0; f <= N; f++) {
62
+ const W = f ? placeItems(motion, jointValues(motion, { ...Object.fromEntries(Object.entries(v0).filter(([id]) => !motion.joints.find((j) => j.id === id)?.follow)), [plan.root]: [base + (360 * plan.turns * f) / N] })) : W0;
63
+ for (const k of ks) {
64
+ const a = F(rowsAt(W[k], [0, 0, 0])), local = invRows(W0[k]), axisLocal = rotOnly(local, Z), e = perp(axisLocal);
65
+ const b = F(rowsAt(W[k], e)), a0 = F(rowsAt(W0[k], [0, 0, 0])), b0 = F(rowsAt(W0[k], e));
66
+ const th = Math.atan2(b[1] - a[1], b[0] - a[0]) - Math.atan2(b0[1] - a0[1], b0[0] - a0[0]);
67
+ const list = moves.get(k), prev = list.length ? list.at(-1).th : 0;
68
+ let t = th; while (t - prev > Math.PI) t -= 2 * Math.PI; while (t - prev < -Math.PI) t += 2 * Math.PI; // turned on, not back
69
+ const c = Math.cos(t), sn = Math.sin(t);
70
+ list.push({ th: t, tx: a[0] - (c * a0[0] - sn * a0[1]), ty: a[1] - (sn * a0[0] + c * a0[1]) });
71
+ }
72
+ }
73
+ const still = (k) => moves.get(k).every((m) => Math.abs(m.th) < 1e-6 && Math.abs(m.tx) < 1e-6 && Math.abs(m.ty) < 1e-6);
74
+ // Each panel: the cut through every part that crosses it, at rest; the moving ones animated
75
+ const panels = picked.map((z) => {
76
+ const cuts = [];
77
+ for (const x of parts) {
78
+ const outlines = loops(sliceAt(x.world, z)).filter((o) => o.length > 2);
79
+ if (outlines.length) cuts.push({ ...x, d: outlines.map((o) => `M${o.map(([u, w]) => `${fmt(u)} ${fmt(w)}`).join('L')}Z`).join('') });
80
+ }
81
+ const names = [...new Set(cuts.filter((c) => c.p.role === 'part').map((c) => c.p.item))];
82
+ return { z, cuts, names };
83
+ }).filter((p) => p.cuts.length);
84
+ if (!panels.length) throw new Error(`${s.name}: no part crosses the planes through its gears`);
85
+ // The view: everything every frame reaches, in each panel
86
+ let r = 0;
87
+ for (const pn of panels) for (const c of pn.cuts) for (const t of c.world) for (const q of t) if (Math.abs(q[2] - pn.z) < 50) r = Math.max(r, Math.hypot(q[0], q[1]));
88
+ const cell = 2 * r * 1.1, gap = cell * 0.08, cap = cell * 0.16, W = panels.length * cell + (panels.length + 1) * gap, H = cell + cap * 2 + gap;
89
+ const dur = `${fmt(Math.max(4, Math.min(12, plan.turns * 2)))}s`;
90
+ const anim = (k) => {
91
+ const m = moves.get(k);
92
+ return { t: `<animateTransform attributeName="transform" type="translate" values="${m.map((x) => `${fmt(x.tx)} ${fmt(x.ty)}`).join(';')}" dur="${dur}" repeatCount="indefinite"/>`,
93
+ r: `<animateTransform attributeName="transform" type="rotate" values="${m.map((x) => fmt((x.th * 180) / Math.PI)).join(';')}" dur="${dur}" repeatCount="indefinite"/>` };
94
+ };
95
+ const colour = (c) => (c.p.role !== 'part' ? COLOUR.bought : c.k === loadItem ? COLOUR.load : still(c.k) ? COLOUR.still : COLOUR.moves);
96
+ const art = panels.map((pn, i) => {
97
+ const cx = gap + i * (cell + gap) + cell / 2, cy = cap + gap + cell / 2;
98
+ const order = [...pn.cuts].sort((a, b) => (a.p.role !== 'part') - (b.p.role !== 'part') || still(b.k) - still(a.k)); // bought faint at the back, still parts under moving ones
99
+ const shapes = order.map((c) => {
100
+ const fill = `<path d="${c.d}" fill="${colour(c)}" fill-rule="evenodd" stroke="#1a1a1a" stroke-width="${fmt(cell / 900)}"/>`;
101
+ if (still(c.k)) return fill;
102
+ const a = anim(c.k);
103
+ return `<g>${a.t}<g>${a.r}${fill}</g></g>`;
104
+ }).join('');
105
+ const size = cap * 0.3, room = Math.floor(cell / (size * 0.55)), text = `at ${fmt(pn.z)} mm: ${pn.names.join(', ')}`;
106
+ const label = `<text x="${fmt(cx - cell / 2)}" y="${fmt(cap * 0.75)}" font-size="${fmt(size)}" font-family="system-ui, sans-serif" fill="#333">${esc(text.length > room ? `${text.slice(0, room - 1)}…` : text)}</text>`;
107
+ return `${label}<g transform="translate(${fmt(cx)} ${fmt(cy)}) scale(1 -1)">${shapes}</g>`;
108
+ }).join('\n');
109
+ const times = (n) => (n === 1 ? 'once' : `${fmt(n)} times`), along = `cut across ${plan.root}'s axis`;
110
+ const out = plan.ratio !== 1 ? `${along}: ${plan.load} turns ${fmt((360 * plan.turns) / plan.ratio)}° while ${plan.root} turns ${times(plan.turns)} (${fmt(plan.ratio)}:1)` : `${along}: ${plan.root} turned ${times(plan.turns)}`;
111
+ const KEY = [['moves', 'moves'], ['load', 'carries the load'], ['still', 'held still'], ['bought', 'bought']];
112
+ const ks2 = Math.min(cap * 0.3, (W - 2 * gap) / (KEY.reduce((n, [, t]) => n + t.length * 0.55 + 3.2, 0))), outSize = Math.min(cap * 0.34, (W - 2 * gap) / (out.length * 0.55));
113
+ let kx = gap;
114
+ const key = KEY.map(([k, t]) => { const x = kx; kx += ks2 * (t.length * 0.55 + 3.2); return `<rect x="${fmt(x)}" y="${fmt(H - cap * 0.95)}" width="${fmt(ks2 * 1.2)}" height="${fmt(ks2 * 1.2)}" fill="${COLOUR[k]}" stroke="#1a1a1a" stroke-width="${fmt(cell / 900)}"/><text x="${fmt(x + ks2 * 1.6)}" y="${fmt(H - cap * 0.95 + ks2)}" font-size="${fmt(ks2)}" font-family="system-ui, sans-serif" fill="#555">${t}</text>`; }).join('');
115
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${fmt(W)} ${fmt(H)}" width="${Math.min(1400, 480 * panels.length)}">
116
+ <title>${esc(title || s.a.title || s.name)}</title>
117
+ <rect width="${fmt(W)}" height="${fmt(H)}" fill="#fff"/>
118
+ ${art}
119
+ <text x="${fmt(gap)}" y="${fmt(H - cap * 1.25)}" font-size="${fmt(outSize)}" font-family="system-ui, sans-serif" fill="#333">${esc(out)}</text>
120
+ ${key}
121
+ </svg>
122
+ `;
123
+ }
124
+
125
+ // Helpers on the flat row-major 4 × 4 matrices placeItems gives
126
+ function invRows(W) { // a rigid move's inverse: the turn transposed, the shift turned back
127
+ const R = [[W[0], W[1], W[2]], [W[4], W[5], W[6]], [W[8], W[9], W[10]]], t = [W[3], W[7], W[11]];
128
+ const o = new Array(16).fill(0);
129
+ for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) o[4 * i + j] = R[j][i]; o[4 * i + 3] = -(R[0][i] * t[0] + R[1][i] * t[1] + R[2][i] * t[2]); }
130
+ o[15] = 1; return o;
131
+ }
132
+ const rotOnly = (W, v) => [0, 1, 2].map((k) => W[4 * k] * v[0] + W[4 * k + 1] * v[1] + W[4 * k + 2] * v[2]);
133
+ const perp = (z) => { const n = Math.hypot(...z) || 1, u = z.map((c) => c / n), seed = Math.abs(u[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]; const c = [seed[1] * u[2] - seed[2] * u[1], seed[2] * u[0] - seed[0] * u[2], seed[0] * u[1] - seed[1] * u[0]], m = Math.hypot(...c); return c.map((x) => (x / m) * 10); };
package/lib/motorsvg.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // through its train, a bar for each stage, against what the load needs there. The numbers are the check's own.
3
3
  import { mul, jointValues, placeItems } from '@rulecad/model-link';
4
4
  import { curve } from '@rulecad/motors/diagram';
5
- import { motorChecks, trainFrom } from './motors.mjs';
5
+ import { motorChecks, trainFrom, axisOf } from './motors.mjs';
6
6
  import { materialOf } from './list.mjs';
7
7
 
8
8
  const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;');
@@ -71,3 +71,26 @@ export function trainSvg(w, { title = '' } = {}) {
71
71
  const height = y + 8;
72
72
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">${out.join('')}</svg>\n`;
73
73
  }
74
+
75
+ // Labels for a check view: at each joint the motor's torque passes through, what reaches it and the margin; at the
76
+ // joint with the load, whether it holds with the power off. Never drawn on the rest view.
77
+ export function workMarks(s, works = motorWork(s)) {
78
+ const motion = s.motion, worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined)), out = [];
79
+ for (const w of works) {
80
+ const stages = [...w.train.stages].reverse(), atMotor = w.available / (w.train.ratio * w.train.efficiency);
81
+ const where = (id) => { const j = motion.joints.find((x) => x.id === id); return j ? axisOf(motion, worlds, j, mul).O : null; };
82
+ const first = where(w.drive.joint);
83
+ if (first && stages.length) out.push({ at: first, text: `${w.id}: ${fig(atMotor)} N m at the shaft`, level: 'info' });
84
+ let have = atMotor;
85
+ for (const [k, st] of stages.entries()) {
86
+ const slide = w.train.slide != null && k === stages.length - 1;
87
+ have = slide ? w.available : have * (1 / Math.abs(st.ratio)) * st.efficiency;
88
+ const at = where(st.joint), last = k === stages.length - 1;
89
+ if (!at) continue;
90
+ const off = last ? w.holds.find((h) => /power off|no figure/.test(h.text)) : null;
91
+ out.push({ at, text: `${st.joint}: ${fig(have)} ${slide ? 'N' : 'N m'}${last ? `, ${fig(w.margin)}× the load${off ? `; unpowered ${off.level === 'pass' ? 'holds' : off.level === 'fail' ? 'slips' : 'unknown'}` : ''}` : ''}`, level: last ? w.level : 'info' });
92
+ }
93
+ if (!stages.length && first) out.push({ at: first, text: `${w.joint}: ${fig(w.available)} N m, ${fig(w.margin)}× the load`, level: w.level });
94
+ }
95
+ return out;
96
+ }
@@ -66,7 +66,30 @@ views.forEach(([name, pos], i) => {
66
66
  renderer.render(scene, cam);
67
67
  const l = document.createElement('div'); l.className = 'label'; l.textContent = name;
68
68
  l.style.left = `${x + 32}px`; l.style.top = `${(i < 3 ? 112 : V + 24)}px`; document.body.append(l);
69
+ if (data.marks?.length && (name === '3/4' || name === 'front')) marks(cam, x, i < 3 ? 0 : V);
69
70
  });
71
+
72
+ // A check view's labels: a dot at each point, a line to its text, the texts stacked along the foot of the view in
73
+ // the order their points are, so none sits on another or on its point
74
+ function marks(cam, x0, top) {
75
+ const NS = 'http://www.w3.org/2000/svg', svg = document.createElementNS(NS, 'svg');
76
+ document.body.append(svg); // in the page first, so text can be measured
77
+ svg.setAttribute('width', W); svg.setAttribute('height', H); svg.style.position = 'absolute'; svg.style.left = '0'; svg.style.top = '0';
78
+ const colour = { pass: '#7bd88f', warn: '#f0b44c', fail: '#ff6b5b', info: '#d0d0d0' };
79
+ const pts = data.marks.map((m) => { const v = new THREE.Vector3(m.at[0], m.at[2], -m.at[1]).sub(center).project(cam); return { ...m, px: x0 + ((v.x + 1) / 2) * V, py: top + ((1 - v.y) / 2) * V }; }).sort((a, b) => a.py - b.py);
80
+ const gapY = 30, right = x0 + V - 16;
81
+ pts.forEach((p, k) => { p.row = top + V - 28 - (pts.length - 1 - k) * gapY; }); // stacked along the view's foot, in their points' order
82
+ for (const p of pts) {
83
+ const y = p.row;
84
+ const c = colour[p.level] || colour.info, add = (tag, a) => { const e = document.createElementNS(NS, tag); for (const [k, v] of Object.entries(a)) e.setAttribute(k, v); svg.append(e); return e; };
85
+ // the text right-aligned in the view, on a dark backing so it reads over a part; the line to its left end
86
+ const t = add('text', { x: right, y: y + 5, fill: c, 'font-size': 15, 'text-anchor': 'end', 'font-family': '-apple-system, Helvetica Neue, sans-serif' }); t.textContent = p.text;
87
+ const w = t.getComputedTextLength(), left = right - w;
88
+ const back = add('rect', { x: left - 6, y: y - 11, width: w + 12, height: 22, rx: 4, fill: '#000', 'fill-opacity': 0.82 }); svg.insertBefore(back, t);
89
+ add('polyline', { points: `${p.px},${p.py} ${left - 10},${y} ${left - 6},${y}`, fill: 'none', stroke: c, 'stroke-width': 1.5 });
90
+ add('circle', { cx: p.px, cy: p.py, r: 5, fill: c });
91
+ }
92
+ }
70
93
  document.body.dataset.ready = '1';
71
94
  </script>
72
95
  </body></html>
package/lib/preview.mjs CHANGED
@@ -18,9 +18,9 @@ const CHROME = process.env.CAD_CHROME || [
18
18
  ].find((f) => fs.existsSync(f));
19
19
  const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // wherever npm put it
20
20
 
21
- export async function preview(parts, { title = '', meta = '', out, explode = false }) {
21
+ export async function preview(parts, { title = '', meta = '', out, explode = false, marks = null }) {
22
22
  const flat = (tris) => { const positions = []; for (const t of tris) for (let i = 1; i < t.length - 1; i++) positions.push(...t[0], ...t[i], ...t[i + 1]); return positions; };
23
- const data = JSON.stringify({ title, meta, explode, parts: parts.map((p) => ({ name: p.name, role: p.role, label: p.label, item: p.object || p.item, positions: flat(p.triangles) })) });
23
+ const data = JSON.stringify({ title, meta, explode, marks, parts: parts.map((p) => ({ name: p.name, role: p.role, label: p.label, item: p.object || p.item, positions: flat(p.triangles) })) });
24
24
  const server = http.createServer((req, res) => {
25
25
  const u = new URL(req.url, 'http://x').pathname;
26
26
  const send = (type, body) => { res.writeHead(200, { 'Content-Type': type }); res.end(body); };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.46",
3
+ "version": "0.7.47",
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": {