@rulecad/cad 0.7.42 → 0.7.44

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/lib/task.mjs ADDED
@@ -0,0 +1,203 @@
1
+ // The task at the top of a machine: what it is for, and whether the tool gets there. The assembly's joints from its base
2
+ // to the tool become a chain (@rulecad/robots); the sheet is sampled against the chain; the joints' speeds and their
3
+ // errors are carried to the tool through the Jacobian. The picture and the figures come from the same samples.
4
+ // "task": { "tool": "pen.tip", "sheet": { "size": "a5", "at": [60, -74, 0] }, "speed": 50, "accuracy": 0.3 }
5
+ import fs from 'node:fs';
6
+ import { chainFromMotion, reach, sheetFrame, sheetPoint, jacobian, fk } from '@rulecad/robots';
7
+ import { evaluate, peekRuleSet } from './rules.mjs';
8
+ import { paths } from './workspace.mjs';
9
+ import { trainFrom, workingSpeed } from './motors.mjs';
10
+
11
+ const n3 = (x, d = 2) => String(Number(x.toFixed(d)));
12
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
13
+ const CORNERS = ['lower left', 'lower right', 'upper right', 'upper left'];
14
+
15
+ /** The task as written, checked by name when the assembly is built. */
16
+ export function taskOf(a, motion, num) {
17
+ const t = a.task; if (!t) return null;
18
+ const what = 'task';
19
+ if (!t.tool || !String(t.tool).includes('.')) throw new Error(`${what}: tool is an anchor, <item>.<anchor> (got ${JSON.stringify(t.tool)})`);
20
+ const given = ['sheet', 'region', 'volume'].filter((k) => t[k] != null);
21
+ if (given.length !== 1) throw new Error(`${what}: give one of sheet, region or volume (got ${given.join(', ') || 'none'})`);
22
+ const [id, name] = String(t.tool).split('.'), mark = motion.marks.find((m) => m.id === id && m.name === name);
23
+ if (!mark) throw new Error(`${what}: no anchor "${t.tool}" (anchors: ${motion.marks.filter((m) => m.id === id).map((m) => m.name).join(', ') || `no item ${id}`})`);
24
+ const vec = (v) => v.map(num), value = (k) => { if (t[k] == null) return null; const x = num(t[k]); if (!(x > 0)) throw new Error(`${what}: ${k} is above 0 (got ${x})`); return x; };
25
+ const out = { tool: t.tool, item: id, point: [mark.frame[3], mark.frame[7], mark.frame[11]], speed: value('speed'), accuracy: value('accuracy'), elbow: t.elbow ?? null, deflection: t.deflection != null ? num(t.deflection) : 0, payload: t.payload != null ? num(t.payload) : null, accel: t.accel != null ? num(t.accel) : null };
26
+ if (t.elbow != null && !['left', 'right'].includes(t.elbow)) throw new Error(`${what}: elbow is left or right (got ${JSON.stringify(t.elbow)})`);
27
+ if (t.sheet) out.sheet = { ...t.sheet, at: vec(t.sheet.at), ...(t.sheet.normal ? { normal: vec(t.sheet.normal) } : {}), ...(t.sheet.u ? { u: vec(t.sheet.u) } : {}) };
28
+ const ranges = (o) => Object.fromEntries(Object.entries(o).map(([k, x]) => [k, Array.isArray(x) ? x.map(num) : typeof x === 'object' ? x : num(x)]));
29
+ if (t.region) out.region = ranges(t.region);
30
+ if (t.volume) out.volume = ranges(t.volume);
31
+ try { if (out.sheet) sheetFrame(out.sheet); } catch (e) { throw new Error(`${what}: ${e.message}`); }
32
+ return out;
33
+ }
34
+
35
+ export const chainOf = (s) => chainFromMotion(s.motion, { tip: s.task.item, tool: s.task.point });
36
+
37
+ // One sampling of the task, kept so the three checks and the picture read the same samples
38
+ export function sample(s) {
39
+ if (s.taskSamples) return s.taskSamples;
40
+ const t = s.task, c = chainOf(s), spec = t.sheet ? { sheet: t.sheet } : t.region ? { region: t.region } : { volume: t.volume };
41
+ let step = 10;
42
+ if (t.sheet) { const f = sheetFrame(t.sheet); step = Math.min(f.width, f.height) / 12; }
43
+ const go = (elbow) => reach(c, { ...spec, step, ...(elbow ? { elbow } : {}) });
44
+ // Hold the elbow it's given, or the one that reaches the most
45
+ let r, elbow = t.elbow;
46
+ if (c.dof === 2 && !elbow) { const a = go('right'), b = go('left'); r = b.summary.reachable > a.summary.reachable || (b.summary.reachable === a.summary.reachable && b.summary.margin > a.summary.margin) ? (elbow = 'left', b) : (elbow = 'right', a); } else r = go(elbow);
47
+ return (s.taskSamples = { c, r, elbow, step });
48
+ }
49
+
50
+ // A point on the sheet, said in millimetres from its centre
51
+ const onSheet = (t, p) => { if (!t.sheet) return `(${p.map((x) => n3(x, 1)).join(', ')})`; const f = sheetFrame(t.sheet), d = p.map((x, k) => x - f.at[k]); return `(${n3(dot(d, f.u), 1)}, ${n3(dot(d, f.v), 1)}) from its centre`; };
52
+
53
+ function reachCheck(s, f, picture) {
54
+ const t = s.task, { r, elbow } = sample(s), code = 'task.reach', { summary } = r, thing = t.sheet ? 'sheet' : t.region ? 'region' : 'volume';
55
+ const miss = summary.corners.map((c, i) => ({ c, name: CORNERS[i] ?? `corner ${i + 1}` })).filter((x) => !x.c.reachable).sort((a, b) => b.c.miss - a.c.miss);
56
+ const values = { margin: summary.margin, reachable: summary.reachable, total: summary.total, elbow, samples: r.samples.map((x) => ({ point: x.point.map((v) => +v.toFixed(3)), reachable: x.reachable, q: x.q.map((v) => +v.toFixed(4)), margin: +x.margin.toFixed(3), manipulability: +x.manipulability.toFixed(1) })), picture };
57
+ if (miss.length) {
58
+ const w = miss[0];
59
+ return f('fail', `the ${w.name} corner of the ${thing} can't be reached: ${t.tool} misses it by ${n3(w.c.miss)} mm (${summary.reachable} of ${summary.total} points on it are in reach)`, `${thing}: ${w.name} out of reach`, { code, at: w.c.point, refs: { corner: w.name, tool: t.tool }, values: { ...values, miss: w.c.miss } });
60
+ }
61
+ if (summary.reachable < summary.total) {
62
+ const w = summary.worst;
63
+ return f('fail', `${summary.total - summary.reachable} of ${summary.total} points on the ${thing} can't be reached, ${n3(w.miss)} mm short at worst, at ${onSheet(t, w.point)}: limits or the hole near the base`, `${thing}: not all in reach`, { code, at: w.point, refs: { tool: t.tool }, values: { ...values, miss: w.miss } });
64
+ }
65
+ const w = summary.corners.reduce((a, b) => (b.margin < a.margin ? b : a)), near = Math.min(summary.margin, w.margin);
66
+ f('pass', `${t.tool} reaches the whole ${thing} with ${elbow ? `the elbow to the ${elbow}` : 'its joints'}: ${n3(near)} mm to spare at the worst point`, null, { code, at: summary.worst.point, refs: { tool: t.tool }, values });
67
+ }
68
+
69
+ // How fast a sampled point can go: in each direction across the sheet, the speed at which the first joint hits its limit
70
+ function fastest(c, q, frame, limits) {
71
+ if (!frame) return fastestAnyWay(c, q, limits);
72
+ const J = jacobian(c, q), rows = frame ? [frame.u, frame.v].map((d) => c.names.map((_, i) => d[0] * J[0][i] + d[1] * J[1][i] + d[2] * J[2][i])) : [J[0], J[1]];
73
+ const N = c.names.length, a = dot2(rows[0], rows[0]), b = dot2(rows[0], rows[1]), d = dot2(rows[1], rows[1]), det = a * d - b * b;
74
+ if (Math.abs(det) < 1e-9) return 0;
75
+ let worst = Infinity;
76
+ for (let k = 0; k < 24; k++) {
77
+ const th = (k * Math.PI) / 12, vx = Math.cos(th), vy = Math.sin(th), l0 = (d * vx - b * vy) / det, l1 = (a * vy - b * vx) / det;
78
+ let scale = Infinity;
79
+ for (let i = 0; i < N; i++) { const qd = Math.abs(rows[0][i] * l0 + rows[1][i] * l1); if (qd > 1e-12) scale = Math.min(scale, limits[i] / qd); }
80
+ worst = Math.min(worst, scale);
81
+ }
82
+ return worst;
83
+ }
84
+ const dot2 = (a, b) => a.reduce((t, x, i) => t + x * b[i], 0);
85
+ // In a volume or along a single axis: every way the joints can move together, the slowest the tool goes before a joint runs out
86
+ function fastestAnyWay(c, q, limits) {
87
+ const J = jacobian(c, q), N = c.names.length, turns = N === 1 ? [[1]] : N === 2 ? Array.from({ length: 24 }, (_, k) => [Math.cos((k * Math.PI) / 12), Math.sin((k * Math.PI) / 12)]) : Array.from({ length: 200 }, (_, k) => { const z = 1 - (2 * (k + 0.5)) / 200, r = Math.sqrt(1 - z * z), a = k * 2.399963; return [r * Math.cos(a), r * Math.sin(a), z, ...new Array(N - 3).fill(0)]; });
88
+ let worst = Infinity;
89
+ for (const d of turns) {
90
+ const v = J.map((row) => dot2(row, d)), tool = Math.hypot(...v); if (tool < 1e-9) continue;
91
+ let scale = Infinity; d.forEach((x, i) => { if (Math.abs(x) > 1e-12) scale = Math.min(scale, limits[i] / Math.abs(x)); });
92
+ worst = Math.min(worst, tool * scale);
93
+ }
94
+ return worst === Infinity ? 0 : worst;
95
+ }
96
+
97
+ // deg/s (or mm/s) each joint of the chain can go, from what drives it. null: nothing drives it
98
+ function jointSpeeds(s, c) {
99
+ const motion = s.motion;
100
+ return c.names.map((id) => {
101
+ const t = trainFrom(motion, id), d = motion.drives.find((x) => x.joint === t.root);
102
+ if (!d) return null;
103
+ const rpm = workingSpeed(d.model, d.spec), output = (rpm / t.ratio) * 6; // deg/s at the joint
104
+ return t.slide != null ? output * t.slide : output;
105
+ });
106
+ }
107
+
108
+ function speedCheck(s, f) {
109
+ const t = s.task, code = 'task.speed'; if (t.speed == null) return;
110
+ const { c, r } = sample(s), limits = jointSpeeds(s, c), frame = t.sheet ? sheetFrame(t.sheet) : null;
111
+ const free = c.names.filter((_, i) => limits[i] == null);
112
+ if (free.length) return f('warn', `nothing says how fast ${free.join(' and ')} can turn, so ${t.speed} mm/s isn't checked: give ${free.length > 1 ? 'them' : 'it'} a motor`, `speed: ${free.join(', ')} undriven`, { code, refs: { joints: free } });
113
+ let worst = null;
114
+ for (const x of r.samples) if (x.reachable) { const v = fastest(c, x.q, frame, limits); if (!worst || v < worst.v) worst = { v, x }; }
115
+ if (!worst) return;
116
+ const values = { slowest: worst.v, wanted: t.speed, margin: worst.v / t.speed }, at = worst.x.point, say = `at ${n3(worst.v, 1)} mm/s at the slowest point, ${onSheet(t, at)}, against the ${t.speed} mm/s it's asked for`;
117
+ if (worst.v < t.speed) f('fail', `${t.tool} moves ${say}: a faster motor speed, less ratio or a shorter arm`, `speed ${n3(worst.v, 0)} mm/s`, { code, at, values });
118
+ else f('pass', `${t.tool} moves ${say}`, null, { code, at, values });
119
+ }
120
+
121
+ // Each joint's error terms: step resolution from its motor, and what the assembly says of its play, its twist and so on
122
+ function terms(s, c) {
123
+ const motion = s.motion, specs = new Map((s.a.joints || []).map((j) => [j.id, j]));
124
+ return c.names.map((id) => {
125
+ const out = [], t = trainFrom(motion, id), d = motion.drives.find((x) => x.joint === t.root), spec = specs.get(id);
126
+ if (d?.model.stepAngle) { const micro = d.spec.microsteps ?? 16; out.push({ term: 'step', value: t.slide != null ? (d.model.stepAngle / micro) * t.slide : d.model.stepAngle / micro / t.ratio, kind: 'spec', note: `${n3(d.model.stepAngle, 3)}° at 1/${micro} step, ${n3(t.ratio, 1)}:1` }); }
127
+ const belt = motion.joints.find((x) => x.id === id)?.slide?.stretch; if (belt) out.push({ term: 'belt stretch', value: (belt.load * belt.length) / (belt.k * belt.width), kind: 'estimate', note: `${belt.load} N over ${belt.length} mm` });
128
+ for (const [term, expr] of Object.entries(spec?.errors ?? {})) out.push({ term, value: s.num(expr), kind: kindOf(expr), expr });
129
+ return { joint: id, terms: out, geared: t.stages.length > 0 };
130
+ });
131
+ }
132
+ function kindOf(expr) {
133
+ const kinds = [...String(expr).matchAll(/([a-z][\w-]*)\.([a-z_]\w*)/gi)].map(([, set, rule]) => { try { return peekRuleSet(set).rules[rule]?.kind ?? 'estimate'; } catch { return 'estimate'; } });
134
+ return kinds.length ? (kinds.includes('estimate') ? 'estimate' : kinds[0]) : 'estimate';
135
+ }
136
+
137
+ // The error at one sample: each angle times what it swings at the tool. Worst case, root-sum-square, and each term's share
138
+ function errorAt(c, q, list, extra) {
139
+ const J = jacobian(c, q), lever = c.names.map((_, i) => Math.hypot(J[0][i], J[1][i], J[2][i])), parts = [];
140
+ list.forEach((j, i) => { for (const x of j.terms) parts.push({ joint: j.joint, term: x.term, kind: x.kind, note: x.note, angle: x.value, mm: x.value * lever[i] }); });
141
+ if (extra) parts.push({ joint: null, term: 'link deflection', kind: 'estimate', mm: extra });
142
+ return { worst: parts.reduce((t, p) => t + p.mm, 0), rss: Math.sqrt(parts.reduce((t, p) => t + p.mm * p.mm, 0)), parts };
143
+ }
144
+
145
+ // The worst-case error at one joint configuration
146
+ export const jacobianError = (c, q, list, extra) => errorAt(c, q, list, extra).worst;
147
+
148
+ export function accuracyOf(s) {
149
+ const { c, r } = sample(s), list = terms(s, c), at = r.samples.filter((x) => x.reachable).map((x) => ({ x, e: errorAt(c, x.q, list, s.task.deflection) }));
150
+ return { list, at, worst: at.reduce((a, b) => (b.e.worst > a.e.worst ? b : a), at[0]) };
151
+ }
152
+
153
+ function accuracyCheck(s, f, picture) {
154
+ const t = s.task, code = 'task.accuracy'; if (t.accuracy == null) return null;
155
+ const { list, at, worst } = accuracyOf(s); if (!worst) return null;
156
+ const big = [...worst.e.parts].sort((a, b) => b.mm - a.mm)[0], soft = worst.e.parts.filter((p) => p.kind === 'estimate');
157
+ const name = (p) => `${p.joint ? `${p.joint}'s ` : ''}${p.term}${p.angle != null ? ` (${n3(p.angle, 3)}°)` : ''}`;
158
+ const unmeasured = list.filter((j) => j.geared && !j.terms.some((x) => /play|backlash/.test(x.term))).map((j) => j.joint);
159
+ const predict = { name: code, figure: `${t.tool} error at its worst point`, value: worst.e.worst, unit: 'mm' };
160
+ const margin = worst.e.worst / t.accuracy, level = margin > 1 ? 'fail' : margin > 0.8 ? 'warn' : 'pass';
161
+ const caveat = soft.length ? ` Rests on estimates (${soft.map(name).join(', ')}): settle them with cad measured.` : '', missing = unmeasured.length ? ` ${unmeasured.join(' and ')} ${unmeasured.length > 1 ? 'have' : 'has'} gears and no play given: it counts as none until measured (bench test 14).` : '';
162
+ const text = `${t.tool} can be out by ${n3(worst.e.worst, 3)} mm at worst, ${n3(worst.e.rss, 3)} mm root-sum-square, at ${onSheet(t, worst.x.point)}, against ${t.accuracy} mm. Biggest: ${name(big)}, ${n3(big.mm, 3)} mm.${caveat}${missing}`;
163
+ f(level, text, level === 'pass' ? null : `pen error ${n3(worst.e.worst, 2)} mm`, { code, at: worst.x.point, predict, refs: { biggest: big.term, joint: big.joint }, values: { worst: worst.e.worst, rss: worst.e.rss, wanted: t.accuracy, margin, terms: worst.e.parts, picture } });
164
+ return at;
165
+ }
166
+
167
+ // Pictures in .preview/: the sheet, what's reachable, shaded; the arm at its worst point
168
+ const colour = (x) => `rgb(${Math.round(240 - 180 * x)},${Math.round(240 - 100 * x)},${Math.round(250 - 40 * x)})`;
169
+ function pictures(s, errors) {
170
+ if (!s.task.sheet) return null;
171
+ const { c, r } = sample(s), f = sheetFrame(s.task.sheet), toSheet = (p) => { const d = p.map((x, k) => x - f.at[k]); return [dot(d, f.u), -dot(d, f.v)]; };
172
+ const pts = [...r.samples.map((x) => toSheet(x.point)), ...fk(c, r.summary.worst.q).frames.map((x) => toSheet(x.at))], lo = [0, 1].map((k) => Math.min(...pts.map((p) => p[k]))), hi = [0, 1].map((k) => Math.max(...pts.map((p) => p[k])));
173
+ const m = 15, W = hi[0] - lo[0] + 2 * m, H = hi[1] - lo[1] + 2 * m, step = sample(s).step;
174
+ const head = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${lo[0] - m} ${lo[1] - m} ${W} ${H}" width="${Math.round(W * 3)}" height="${Math.round(H * 3)}" font-family="sans-serif" font-size="5">`;
175
+ const sheet = `<rect x="${-f.width / 2}" y="${-f.height / 2}" width="${f.width}" height="${f.height}" fill="none" stroke="#333" stroke-width="0.6"/>`;
176
+ const arm = (q) => { const F = fk(c, q), P = [...F.frames.map((x) => x.at), F.position].map(toSheet); return `<polyline points="${P.map((p) => p.join(',')).join(' ')}" fill="none" stroke="#c33" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>` + P.map((p) => `<circle cx="${p[0]}" cy="${p[1]}" r="2" fill="#c33"/>`).join(''); };
177
+ const cells = (val) => r.samples.map((x) => { const [px, py] = toSheet(x.point), v = val(x); return `<rect x="${px - step / 2}" y="${py - step / 2}" width="${step}" height="${step}" fill="${v == null ? '#f8c0c0' : colour(v)}"/>`; }).join('');
178
+ const dir = paths.preview(s.project, ''); fs.mkdirSync(dir, { recursive: true });
179
+ const write = (name, body, title) => { const file = paths.preview(s.project, `${s.name}-${name}.svg`); fs.writeFileSync(file, `${head}<text x="${lo[0] - m + 2}" y="${lo[1] - m + 7}">${title}</text>${body}</svg>\n`); return file; };
180
+ const top = Math.max(...r.samples.map((x) => x.manipulability), 1e-9);
181
+ const out = { reach: write('reach', cells((x) => (x.reachable ? x.manipulability / top : null)) + sheet + arm(r.summary.worst.q), 'Reach: darker has more dexterity, red is out of reach. The arm at the least margin') };
182
+ if (errors?.length) {
183
+ const most = Math.max(...errors.map((e) => e.e.worst), 1e-9), by = new Map(errors.map((e) => [e.x, e.e.worst / most])), worst = errors.reduce((a, b) => (b.e.worst > a.e.worst ? b : a));
184
+ out.error = write('error', cells((x) => (by.has(x) ? by.get(x) : null)) + sheet + arm(worst.x.q), `Predicted error: darkest is ${n3(most, 3)} mm. The arm at its worst point`);
185
+ }
186
+ return out;
187
+ }
188
+
189
+ /** The task's findings, in the assembly's shape. */
190
+ export function taskChecks(s, f) {
191
+ if (!s.task) return;
192
+ const relative = (x) => x && x.replace(`${paths.preview(s.project, '')}/`, '');
193
+ let drawn = null;
194
+ try { const { c } = sample(s); if (!c.dof) return; drawn = true; } catch (e) { return f('fail', `task: ${e.message}`, 'task: no chain', { code: 'task.chain' }); }
195
+ const pic = pictures(s, s.task.accuracy != null ? accuracyOf(s).at : null);
196
+ reachCheck(s, f, relative(pic?.reach));
197
+ speedCheck(s, f);
198
+ accuracyCheck(s, f, relative(pic?.error));
199
+ return drawn;
200
+ }
201
+
202
+ // A point on the sheet, for what plans on it
203
+ export const pointOnSheet = (sheet, x, y) => sheetPoint(sheet, x, y);
package/lib/wires.mjs CHANGED
@@ -87,6 +87,42 @@ export function wireChecks(s, f, helpers) {
87
87
  }
88
88
  }
89
89
 
90
+ // A route's stations: each anchor as [item, local point]; a path joint in the route is its whole polyline, on its parent
91
+ function stations(s, chain, mul) {
92
+ const motion = s.motion, out = [], ids = motion.items.map((x) => x[0]);
93
+ for (const v of chain) {
94
+ if (typeof v === 'string' && !v.includes('.')) { const j = motion.joints.find((x) => x.id === v); if (j) for (const p of j.path) { const W = mul(j.a, [1, 0, 0, p[0], 0, 1, 0, p[1], 0, 0, 1, p[2]]); out.push([j.parent, W[3], W[7], W[11]]); } continue; }
95
+ const bits = String(v).split('.'), name = bits.pop(), id = bits.join('.'), m = motion.marks.find((x) => x.id === id && x.name === name);
96
+ if (m) out.push([ids.indexOf(id), m.frame[3], m.frame[7], m.frame[11]]);
97
+ }
98
+ return out;
99
+ }
100
+ const worldOf = (W, [, x, y, z]) => [W[0] * x + W[1] * y + W[2] * z + W[3], W[4] * x + W[5] * y + W[6] * z + W[7], W[8] * x + W[9] * y + W[10] * z + W[11]];
101
+ const I = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
102
+
103
+ /** Each wire's route as stations a link carries: [[id, [[item, x, y, z], …]]], the item -1 (world) when nothing moves. */
104
+ export function wireRoutes(s, { placeItems, mul }) {
105
+ const hasJoints = s.motion.joints.length > 0, W = hasJoints ? null : placeItems(s.motion, s.jointValues);
106
+ return (s.wires || []).map((w) => [w.id, stations(s, [w.from, ...(w.via ?? []), w.to], mul).map((p) => (hasJoints ? p.map((v) => +v.toFixed(3)) : [-1, ...worldOf(p[0] < 0 ? I : W[p[0]], p).map((v) => +v.toFixed(3))]))]);
107
+ }
108
+
109
+ // A thin square tube along each wire at the assembly's pose, for previews: drawn faint, never a part, so no check sees it
110
+ export function wireTubes(s, { placeItems, mul }) {
111
+ const worlds = placeItems(s.motion, s.jointValues), r = 0.5, out = [];
112
+ for (const w of s.wires || []) {
113
+ const pts = stations(s, [w.from, ...(w.via ?? []), w.to], mul).map((p) => worldOf(p[0] < 0 ? I : worlds[p[0]], p)), tris = [];
114
+ for (let k = 1; k < pts.length; k++) {
115
+ const a = pts[k - 1], b = pts[k], d = b.map((c, i) => c - a[i]), l = Math.hypot(...d); if (l < 1e-6) continue;
116
+ const z = d.map((c) => c / l), side = Math.abs(z[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0], x0 = [z[1] * side[2] - z[2] * side[1], z[2] * side[0] - z[0] * side[2], z[0] * side[1] - z[1] * side[0]], m = Math.hypot(...x0), x = x0.map((c) => c / m), y = [z[1] * x[2] - z[2] * x[1], z[2] * x[0] - z[0] * x[2], z[0] * x[1] - z[1] * x[0]];
117
+ const corner = (o, sx, sy) => o.map((c, i) => c + (sx * x[i] + sy * y[i]) * r), ring = (o) => [corner(o, 1, 1), corner(o, -1, 1), corner(o, -1, -1), corner(o, 1, -1)], A = ring(a), B = ring(b);
118
+ for (let q = 0; q < 4; q++) { const n = (q + 1) % 4; tris.push([A[q], A[n], B[n]], [A[q], B[n], B[q]]); }
119
+ tris.push([A[0], A[2], A[1]], [A[0], A[3], A[2]], [B[0], B[1], B[2]], [B[0], B[2], B[3]]);
120
+ }
121
+ if (tris.length) out.push({ name: `wire.${w.id}`, role: 'wire', label: `wire ${w.id}`, item: null, triangles: tris });
122
+ }
123
+ return out;
124
+ }
125
+
90
126
  // The sheet: each wire, its length, gauge, colour and connectors, in Markdown
91
127
  export function wiringSheet(rows) {
92
128
  const line = (a) => `| ${a.join(' | ')} |`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.42",
3
+ "version": "0.7.44",
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": {
@@ -57,21 +57,22 @@
57
57
  "url": "https://github.com/JoniBach/rulecad/issues"
58
58
  },
59
59
  "dependencies": {
60
- "@rulecad/variables": "^0.3.2",
60
+ "@rulecad/variables": "^0.3.3",
61
61
  "@rulecad/keyboard-layout": "^0.1.2",
62
62
  "@rulecad/printcheck": "^0.3.0",
63
63
  "@rulecad/fit": "^0.4.0",
64
- "@rulecad/model-link": "^0.3.0",
64
+ "@rulecad/model-link": "^0.3.2",
65
65
  "@rulecad/versions": "^0.1.0",
66
- "@rulecad/shapes": "^0.4.3",
67
- "@rulecad/rules": "^0.3.8",
66
+ "@rulecad/shapes": "^0.4.4",
67
+ "@rulecad/rules": "^0.3.9",
68
68
  "@jscad/modeling": "^2.12.0",
69
69
  "three": "^0.186.1",
70
70
  "@rulecad/fea": "^0.2.1",
71
71
  "@rulecad/topopt": "^0.3.0",
72
72
  "@rulecad/flexures": "^0.5.0",
73
73
  "@rulecad/gears": "^0.3.2",
74
- "@rulecad/motors": "^0.1.2"
74
+ "@rulecad/motors": "^0.1.4",
75
+ "@rulecad/robots": "^0.1.1"
75
76
  },
76
77
  "peerDependencies": {
77
78
  "@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0 || ^0.4.0 || ^0.5.0"
@@ -12,6 +12,7 @@
12
12
  "description": { "type": "string" },
13
13
  "note": { "type": "string" },
14
14
  "kind": { "enum": ["fit", "plate"] },
15
+ "packed": { "type": "object", "description": "Written by cad plates: which assembly this plate is for, its filament and gap, and each part's build hash, so a changed part re-packs only its plate", "required": ["of", "filament", "gap", "parts"], "additionalProperties": false, "properties": { "of": { "type": "string" }, "filament": { "type": "string" }, "gap": { "type": "number" }, "parts": { "type": "object" } } },
15
16
  "uses": { "type": "array", "items": { "type": "string" } },
16
17
  "requires": { "type": "object", "additionalProperties": { "type": "string" }, "description": "object → semver range" },
17
18
  "items": { "type": "array", "items": { "$ref": "#/$defs/item" } },
@@ -19,6 +20,9 @@
19
20
  "joints": { "type": "array", "items": { "$ref": "#/$defs/joint" } },
20
21
  "loops": { "type": "array", "items": { "$ref": "#/$defs/loop" } },
21
22
  "planetary": { "type": "array", "items": { "$ref": "#/$defs/planetary" } },
23
+ "task": { "type": "object", "required": ["tool"], "additionalProperties": false, "description": "What the machine is for: the tool, where it works, how fast and how accurately", "properties": { "tool": { "type": "string", "description": "An anchor, <item>.<anchor>" }, "sheet": { "type": "object", "required": ["at"], "additionalProperties": false, "properties": { "size": {}, "width": { "type": "number" }, "height": { "type": "number" }, "landscape": { "type": "boolean" }, "at": { "$ref": "#/$defs/vec3" }, "normal": { "$ref": "#/$defs/vec3" }, "u": { "$ref": "#/$defs/vec3" } } }, "region": { "type": "object" }, "volume": { "type": "object" }, "speed": { "$ref": "#/$defs/expr", "description": "mm/s" }, "accuracy": { "$ref": "#/$defs/expr", "description": "mm" }, "accel": { "$ref": "#/$defs/expr", "description": "mm/s², for planning" }, "elbow": { "enum": ["left", "right"] }, "deflection": { "$ref": "#/$defs/expr", "description": "mm of link deflection at the tool, an estimate; else worked out from the parts when there is a payload" }, "payload": { "$ref": "#/$defs/expr", "description": "kg at the tool" }, "grip": { "type": "object", "description": "A compliant gripper on a servo: { servo, horn, leaf: { length, thickness, width }, travel, friction, lever, margin }" }, "pen": { "type": "object", "description": "Servo angles for the pen: { up, down }" } } },
24
+ "gait": { "type": "object", "required": ["legs", "pattern", "stride", "lift", "period", "height", "mass"], "additionalProperties": false, "description": "Poses in time: the feet by anchor, a pattern, and the body", "properties": { "legs": { "type": "array", "items": { "type": "string" } }, "pattern": {}, "stride": { "$ref": "#/$defs/expr" }, "lift": { "$ref": "#/$defs/expr" }, "period": { "$ref": "#/$defs/expr" }, "height": { "$ref": "#/$defs/expr" }, "mass": { "$ref": "#/$defs/expr" }, "steps": { "$ref": "#/$defs/expr" }, "com": { "$ref": "#/$defs/vec3" }, "clearance": { "$ref": "#/$defs/expr" } } },
25
+ "power": { "type": "object", "additionalProperties": false, "properties": { "margin": { "type": "number" } } },
22
26
  "wires": { "type": "array", "description": "Wires between anchors, their length measured through every pose", "items": { "type": "object", "required": ["from", "to"], "additionalProperties": false, "properties": { "id": { "type": "string" }, "from": { "type": "string" }, "to": { "type": "string" }, "via": { "type": "array", "items": { "type": "string" }, "description": "Anchors or path joints the wire is routed by" }, "gauge": { "type": "string", "description": "awg22" }, "colour": { "type": "string" }, "conductors": { "type": "number" }, "connectors": { "type": "array", "items": { "type": "string" } }, "current": { "type": "number", "description": "A: else a motor's rated current at either end, or a signal's" }, "note": { "type": "string" } } } },
23
27
  "gravity": { "$ref": "#/$defs/vec3", "description": "Which way down is, for masses in loads (default [0, 0, -1])" },
24
28
  "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" } } } },
@@ -38,7 +42,7 @@
38
42
  "id": { "type": "string" },
39
43
  "object": { "type": "string" },
40
44
  "assembly": { "type": "string" },
41
- "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" } } },
45
+ "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" } } },
42
46
  "bought": { "type": "string", "description": "A part from a rule set (\"608\", \"drv8825\"): bought, not printed; drawn faint from its figures, with anchors from what it is" },
43
47
  "variant": { "type": "string" },
44
48
  "set": { "type": "object" },
@@ -74,6 +78,9 @@
74
78
  "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" },
75
79
  "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)" },
76
80
  "fastens": { "type": "boolean", "description": "a and b are fastened together (pins, screws, a press): what holds a part that has no joint" },
81
+ "fastener": { "type": "string", "description": "What does the fastening (an M3 × 12 screw): named on the shopping list and the assembly step" },
82
+ "count": { "$ref": "#/$defs/expr", "description": "With fastener: how many" },
83
+ "access": { "type": "string", "description": "<item>.<anchor>: where the screw's tool comes from, its z axis pointing out along the screw. Whatever stands on that line goes on after the screw; if nothing can, assembly.order says so" },
77
84
  "min": { "$ref": "#/$defs/expr" },
78
85
  "max": { "$ref": "#/$defs/expr" },
79
86
  "note": { "type": "string" },
@@ -107,6 +114,9 @@
107
114
  "min": { "$ref": "#/$defs/values" },
108
115
  "max": { "$ref": "#/$defs/values" },
109
116
  "value": { "$ref": "#/$defs/values" },
117
+ "support": { "type": "object", "additionalProperties": false, "description": "What takes this joint's tipping load: bought bearings, or printed clips (read by FE)", "properties": { "bearings": { "type": "array", "items": { "type": "string" } }, "clips": { "type": "array", "items": { "type": "string" } }, "pitch": { "$ref": "#/$defs/expr", "description": "Diameter the clips stand on, mm" }, "cell": { "$ref": "#/$defs/expr", "description": "FE cell, mm" } } },
118
+ "errors": { "type": "object", "description": "What this joint adds to the error at the tool, degrees, by name (play, twist, bearing): an expression reading a rule, so a measurement moves it", "additionalProperties": { "$ref": "#/$defs/expr" } },
119
+ "home": { "type": "object", "additionalProperties": false, "required": ["endstop"], "description": "How this joint finds zero", "properties": { "endstop": { "type": "string", "description": "An item.anchor at the switch" }, "direction": { "enum": [1, -1] } } },
110
120
  "brake": { "type": "string", "description": "What holds this joint with the power off (a ratchet, a detent): counted by motor.holds" },
111
121
  "follow": { "type": "string" },
112
122
  "ratio": { "$ref": "#/$defs/expr" },