@rulecad/cad 0.7.41 → 0.7.43

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/rules.mjs CHANGED
@@ -20,5 +20,11 @@ export function loadRuleSet(name, dir) {
20
20
  }
21
21
  return readJson(own);
22
22
  }
23
+ // A rule set read as it is, the workspace's if it has one: for figures a check only reads, leaving the workspace alone
24
+ export function peekRuleSet(name) {
25
+ const file = RULE_DIRS.map((d) => path.join(d, `${name}.json`)).find((f) => host.exists(f));
26
+ if (!file) throw new Error(`no rule set "${name}" (rules/${name}.json)`);
27
+ return readJson(file);
28
+ }
23
29
  // resolve() as @rulecad/variables describes it, loading the rule sets it isn't handed
24
30
  export const resolve = (object, opts = {}) => resolveWith(object, { load: loadRuleSet, ...opts });
package/lib/seats.mjs ADDED
@@ -0,0 +1,128 @@
1
+ // Seats and running fits, read from the parts as drawn: a slice across the axis, rays out from it. Whether a child turns
2
+ // freely on its pin (joint.running), and whether a printed pocket is right for the bought bearing in it (fit.seat).
3
+ import { createRequire } from 'node:module';
4
+
5
+ const require = createRequire(import.meta.url);
6
+ const n3 = (x, d = 3) => String(Number(x.toFixed(d)));
7
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
8
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
9
+ const unit = (v) => { const l = Math.hypot(...v); return v.map((c) => c / l); };
10
+
11
+ // Coordinates about an axis: z along it from O, x and y across it
12
+ export function axisFrame(O, Z) {
13
+ const z = unit(Z), seed = Math.abs(z[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0], x = unit(cross(seed, z)), y = cross(z, x);
14
+ return (p) => { const q = sub(p, O); return [dot(q, x), dot(q, y), dot(q, z)]; };
15
+ }
16
+ // A slice across the axis at z, as 2D segments
17
+ export function sliceAt(tris, z) {
18
+ const segs = [];
19
+ for (const t of tris) {
20
+ const c = [];
21
+ for (let i = 0; i < 3; i++) { const a = t[i], b = t[(i + 1) % 3]; if ((a[2] - z) * (b[2] - z) < 0) { const u = (z - a[2]) / (b[2] - a[2]); c.push([a[0] + u * (b[0] - a[0]), a[1] + u * (b[1] - a[1])]); } }
22
+ if (c.length === 2) segs.push(c);
23
+ }
24
+ return segs;
25
+ }
26
+ // How far out from the axis a ray crosses the slice's walls
27
+ export function rayHits(segs, ang) {
28
+ const dx = Math.cos(ang), dy = Math.sin(ang), out = [];
29
+ for (const [p, q] of segs) {
30
+ const ex = q[0] - p[0], ey = q[1] - p[1], den = dx * ey - dy * ex;
31
+ if (Math.abs(den) < 1e-12) continue;
32
+ const t = (p[0] * ey - p[1] * ex) / den, u = (p[0] * dy - p[1] * dx) / den;
33
+ if (t > 1e-6 && u >= 0 && u < 1) out.push(t);
34
+ }
35
+ return out.sort((a, b) => a - b);
36
+ }
37
+ const RAYS = 48, FACETS = 0.02; // mm: what a round drawn in facets is short of its true size
38
+ // At one slice: is the axis in solid (a pin) or in a space (a bore), and the first wall out, each way round
39
+ function round(segs) {
40
+ if (segs.length < 3) return null;
41
+ let solid = 0, bore = 0; const first = [];
42
+ for (let k = 0; k < RAYS; k++) { const h = rayHits(segs, ((k + 0.37) * 2 * Math.PI) / RAYS); if (!h.length) return null; (h.length % 2 ? solid++ : bore++); first.push(h[0]); }
43
+ return { pin: solid > bore, first };
44
+ }
45
+ const span = (tris, r) => { let lo = Infinity, hi = -Infinity; for (const t of tris) for (const p of t) if (Math.hypot(p[0], p[1]) < r) { lo = Math.min(lo, p[2]); hi = Math.max(hi, p[2]); } return [lo, hi]; };
46
+
47
+ // The running gap of a revolute: where one side is a pin and the other a bore round it, the least gap each side as drawn
48
+ // (over a few slices along the length they share) and how far along it runs. null: nothing there turns on a pin
49
+ export function runningGap(aTris, bTris) {
50
+ const reach = 40, [la, ha] = span(aTris, reach), [lb, hb] = span(bTris, reach), lo = Math.max(la, lb), hi = Math.min(ha, hb);
51
+ if (!(hi - lo > 0.2)) return null;
52
+ let least = null, along = 0, step = (hi - lo) / 8;
53
+ for (let k = 0; k < 8; k++) {
54
+ const z = lo + step * (k + 0.5), A = round(sliceAt(aTris, z)), B = round(sliceAt(bTris, z));
55
+ if (!A || !B || A.pin === B.pin) continue;
56
+ const pin = A.pin ? A : B, bore = A.pin ? B : A;
57
+ // A real pin is round about the axis: the widest and narrowest of it agree
58
+ if (Math.max(...pin.first) - Math.min(...pin.first) > 0.5) continue;
59
+ const gap = Math.min(...bore.first.map((r, i) => r - pin.first[i]));
60
+ if (gap > 2) continue; // room, not a running fit
61
+ along += step;
62
+ if (least == null || gap < least.gap) least = { gap, z, pin: Math.max(...pin.first), bore: Math.min(...bore.first), pinOn: A.pin ? 'a' : 'b' };
63
+ }
64
+ return least && { ...least, length: along };
65
+ }
66
+
67
+ // What the project prints on, for the fits to hold a gap against: a rule set the assembly reads, or the kit's default
68
+ export function printerRules(s) {
69
+ const pick = (name) => { try { return Object.fromEntries(Object.entries(require(`@rulecad/rules/${name}.json`).rules).map(([k, r]) => [k, r.value])); } catch { return null; } };
70
+ return { ...pick('x1c'), ...(s.values?.x1c && typeof s.values.x1c === 'object' ? s.values.x1c : {}) };
71
+ }
72
+
73
+ // joint.running: for each revolute, the gap where its child turns on a pin or in a bore. A printed bore comes out
74
+ // hole_comp smaller across, so half of that comes off the gap each side; what's left is held against the printer's fit
75
+ export function runningChecks(s, f, { axisOf, placeItems, jointValues, mul }) {
76
+ const motion = s.motion; if (!motion?.joints?.length) return;
77
+ const worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined)), ids = motion.items.map((x) => x[0]);
78
+ const P = printerRules(s), fit = P.fit ?? 0.2, comp = P.hole_comp ?? 0.1;
79
+ const refs = new Set(s.objects.filter((o) => o.role === 'reference').map((o) => String(o.id).split('.')[0]));
80
+ const partsOf = (id) => s.parts.filter((p) => p.item === id || p.leaf === id);
81
+ for (const j of motion.joints) {
82
+ if (j.type !== 'revolute' || j.parent < 0) continue;
83
+ const a = ids[j.parent], b = ids[j.child];
84
+ if (refs.has(a) || refs.has(b)) continue; // a bought part's seat is fit.seat's business
85
+ const pa = partsOf(a), pb = partsOf(b);
86
+ if (!pa.length || !pb.length) continue;
87
+ const { O, Z } = axisOf(motion, worlds, j, mul), to = axisFrame(O, Z), g = runningGap(pa.flatMap((p) => p.triangles).map((t) => t.map(to)), pb.flatMap((p) => p.triangles).map((t) => t.map(to)));
88
+ if (!g) continue;
89
+ const printed = g.gap - comp / 2, at = O.map((c, i) => c + unit(Z)[i] * g.z), pin = g.pinOn === 'a' ? a : b, bore = g.pinOn === 'a' ? b : a, refsOut = { joint: j.id, pin, bore };
90
+ const values = { drawn: g.gap, printed, fit, length: g.length }, words = `${bore} on ${pin}'s ${n3(g.pin * 2, 2)} mm pin: ${n3(g.gap)} mm each side as drawn, about ${n3(printed)} mm printed`;
91
+ if (printed <= 0) f('fail', `${j.id}: ${words} (a printed bore comes out ${comp} mm small across): it won't turn. The bore wants ${n3(2 * (g.pin + fit) + comp, 2)} mm`, `${j.id}: no running gap`, { code: 'joint.running', at, refs: refsOut, values });
92
+ else if (printed < fit - FACETS) f('warn', `${j.id}: ${words}, under the printer's ${fit} mm fit: expect it to bind. The bore wants ${n3(2 * (g.pin + fit) + comp, 2)} mm`, `${j.id}: tight on its pin`, { code: 'joint.running', at, refs: refsOut, values });
93
+ else f('pass', `${j.id}: ${words}`, null, { code: 'joint.running', at, refs: refsOut, values });
94
+ }
95
+ }
96
+
97
+ // fit.seat: a printed pocket against the bought bearing in it, read from the part as drawn, so a pocket drawn by hand is
98
+ // caught as well as one from bearingSeat. { "a": "b1", "b": "housing", "seat": "press" | "slip" | clearance in mm }
99
+ export function seatFit(x, s, f, { placeItems, jointValues, mul, seatSize }) {
100
+ const top = (n) => String(n).split(/[.@]/)[0], o = s.objects.find((y) => y.bought?.part === 'bearing' && (y.id === top(x.a) || y.id === top(x.b))), label = x.note || `${x.a} in ${x.b}`, code = 'fit.seat';
101
+ if (!o) return f('fail', `${label}: a seat holds a bought bearing, and neither ${x.a} nor ${x.b} is one`, `${label}: no bearing`, { code });
102
+ const other = top(x.a) === o.id ? top(x.b) : top(x.a), parts = s.parts.filter((p) => p.item === other || p.leaf === other);
103
+ if (!parts.length) return f('fail', `${label}: no part "${other}"`, null, { code });
104
+ const motion = s.motion, ids = motion.items.map((y) => y[0]), W = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined))[ids.indexOf(o.id)];
105
+ const inv = (p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
106
+ const tris = parts.flatMap((p) => p.triangles).map((t) => t.map(inv)), v = o.built.values, w = v.width, R = v.outer_diameter / 2, r = v.bore / 2;
107
+ const printer = printerRules(s), want = seatSize(v, { fit: x.seat === true ? 'press' : x.seat, printer }), refs = { item: o.id, part: other };
108
+ const firstWall = (z) => { const segs = sliceAt(tris, z); if (segs.length < 3) return null; const h = []; for (let k = 0; k < RAYS; k++) { const a = rayHits(segs, ((k + 0.37) * 2 * Math.PI) / RAYS); if (!a.length) return null; h.push(a[0]); } return h; };
109
+ const mid = firstWall(w / 2);
110
+ if (!mid) return f('fail', `${label}: halfway along ${o.bought.set}, ${other} doesn't go round it`, `${label}: no seat`, { code, refs });
111
+ const drawn = 2 * Math.max(...mid), diff = drawn - want.pocket, values = { drawn, wanted: want.pocket, difference: diff, comp: want.comp, clearance: want.clearance };
112
+ const inMaterial = 2 * Math.min(...mid) < 2 * r + 0.1;
113
+ if (inMaterial) return f('fail', `${label}: ${other} is solid where the bearing goes (the wall is ${n3(Math.min(...mid), 2)} mm from its axis, inside the ${v.bore} mm bore)`, `${label}: no pocket`, { code, refs, values });
114
+ const say = `${o.bought.set} (${n3(2 * R, 2)} mm) in a pocket drawn ${n3(drawn, 3)} mm`;
115
+ if (Math.abs(diff) > 0.15) f('fail', `${label}: ${say}, and a ${typeof want.fit === 'string' ? want.fit : `${want.fit} mm`} fit on this printer wants ${n3(want.pocket, 3)} mm: ${n3(Math.abs(diff), 2)} mm too ${diff < 0 ? 'small: it will not press in' : 'big: it will rattle'}`, `${label}: seat ${diff < 0 ? 'small' : 'big'}`, { code, refs, values });
116
+ else if (Math.abs(diff) > 0.05) f('warn', `${label}: ${say}, ${n3(diff, 3)} mm from the ${n3(want.pocket, 3)} mm a ${typeof want.fit === 'string' ? want.fit : `${want.fit} mm`} fit wants`, `${label}: seat off`, { code, refs, values });
117
+ else f('pass', `${label}: ${say}, a ${typeof want.fit === 'string' ? want.fit : `${want.fit} mm`} fit (printed about ${n3(want.clearance, 3)} mm)`, null, { code, refs, values });
118
+ // How much of the race the wall holds, and what stops it
119
+ const levels = 9, held = Array.from({ length: levels }, (_, k) => firstWall(w * (k + 0.5) / levels)).filter((h) => h && Math.min(...h) < R + 0.5).length / levels;
120
+ if (held < 0.8) f('warn', `${label}: the pocket holds only ${n3(held * w, 1)} mm of the ${w} mm race: the bearing can tip`, `${label}: shallow`, { code: 'fit.seat', refs, values: { held: held * w, width: w } });
121
+ const ledges = [firstWall(-0.3), firstWall(w + 0.3)].map((h) => (h ? Math.min(...h) : null)).filter((h) => h != null && h < R - 0.1);
122
+ if (!ledges.length) f('warn', `${label}: nothing stops the bearing at either face: draw a lip`, `${label}: no lip`, { code: 'fit.seat', refs });
123
+ else {
124
+ const lip = Math.max(...ledges);
125
+ if (lip < r + (R - r) / 2) f('fail', `${label}: the lip comes in to ${n3(2 * lip, 2)} mm across, onto the inner race (which turns): it wants ${n3(2 * r + (R - r), 2)} mm or more`, `${label}: lip on inner race`, { code: 'fit.seat', refs, values: { lip: 2 * lip } });
126
+ else f('pass', `${label}: a ${n3(R - lip, 2)} mm lip stops the outer race and clears the inner`, null, { code: 'fit.seat', refs, values: { lip: 2 * lip } });
127
+ }
128
+ }
package/lib/sheet.mjs CHANGED
@@ -38,7 +38,151 @@ const INK = '#1a1a1a', THIN = '#666', FILL = '#eceae4', METAL = '#c4c8cc';
38
38
  /** @param {string} name the rule set's name @returns {string} an SVG drawing of what it says the part mounts by */
39
39
  export function drawSet(name) { return drawing(readSet(fileOf(name)), vocabulary()); }
40
40
 
41
+ // The drawing's marks, in sheet units: each adds to out, and span is a dimension with its extension lines, ticks and figure
42
+ function pen() {
43
+ const out = [];
44
+ const line = (a, b, c, e, s = INK, sw = 1.2, dash = '') => out.push(`<line x1="${fig(a)}" y1="${fig(b)}" x2="${fig(c)}" y2="${fig(e)}" stroke="${s}" stroke-width="${sw}"${dash ? ` stroke-dasharray="${dash}"` : ''}/>`);
45
+ const circle = (x, y, r, fill = 'none', s = INK) => out.push(`<circle cx="${fig(x)}" cy="${fig(y)}" r="${fig(r)}" fill="${fill}" stroke="${s}" stroke-width="1.2"/>`);
46
+ const rect = (x, y, a, b, fill = FILL) => out.push(`<rect x="${fig(x)}" y="${fig(y)}" width="${fig(a)}" height="${fig(b)}" fill="${fill}" stroke="${INK}" stroke-width="1.2"/>`);
47
+ const text = (x, y, t, a = 'middle', z = 12) => out.push(`<text x="${fig(x)}" y="${fig(y)}" text-anchor="${a}" font-size="${z}" font-family="system-ui, sans-serif" fill="${INK}">${t}</text>`);
48
+ const span = (x1, y1, x2, y2, t, across_ = 14) => { // a dimension: extension lines, a line with its ticks, the figure
49
+ const horizontal = Math.abs(y2 - y1) < 1e-6, ox = horizontal ? 0 : across_, oy = horizontal ? across_ : 0;
50
+ line(x1, y1, x1 + ox, y1 + oy, THIN, 0.6); line(x2, y2, x2 + ox, y2 + oy, THIN, 0.6); line(x1 + ox, y1 + oy, x2 + ox, y2 + oy, THIN, 0.8);
51
+ for (const [a, b] of [[x1 + ox, y1 + oy], [x2 + ox, y2 + oy]]) line(a - 3, b + 3, a + 3, b - 3, THIN, 0.8);
52
+ if (horizontal) text((x1 + x2) / 2, y1 + oy + (across_ > 0 ? 13 : -4), t); else text(x1 + ox + (across_ > 0 ? 4 : -4), (y1 + y2) / 2 + 4, t, across_ > 0 ? 'start' : 'end');
53
+ };
54
+ return { out, line, circle, rect, text, span };
55
+ }
56
+
57
+ // The sheet's heading (what's trustworthy) and its frame
58
+ function sheet(set, { out, text }, W, H) {
59
+ const kinds = Object.values(set.rules).reduce((m, r) => ({ ...m, [r.kind]: (m[r.kind] || 0) + 1 }), {});
60
+ text(20, 26, set.name, 'start', 16);
61
+ text(20, 44, `all in mm. ${Object.entries(kinds).map(([k, c]) => `${c} ${k}`).join(', ')}: compare it with the datasheet`, 'start', 11);
62
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${fig(W)} ${fig(H + 60)}" width="${fig(W)}" height="${fig(H + 60)}"><rect width="100%" height="100%" fill="#fff"/>${out.join('')}</svg>\n`;
63
+ }
64
+
65
+ // A bearing from its end and in section: bore, outer diameter, width, and the flange or the thrust washers where it has them
66
+ function bearingDrawing(set) {
67
+ const n = (k) => set.rules[k]?.value ?? 0, thrust = set.rules.type?.value === 'thrust';
68
+ const d = n('bore'), D = n('outer_diameter'), B = n('width'), F = n('flange_diameter'), Fw = n('flange_width'), d1 = n('shaft_washer_diameter'), D1 = n('housing_washer_bore');
69
+ const R = Math.max(D, F) / 2, S = Math.max(4, Math.min(20, 90 / R)), W = 2 * R * S + B * S + 330, H = 2 * R * S + 170;
70
+ const cx = R * S + 70, cy = H / 2 + 22, sx = cx + R * S + 120, top = cy - R * S, bottom = cy + R * S;
71
+ const pens = pen(), { line, circle, rect, text, span } = pens;
72
+ // ---- from the end ----
73
+ if (F) circle(cx, cy, (F / 2) * S, '#f6f4ee');
74
+ circle(cx, cy, (D / 2) * S, FILL);
75
+ if (D1) circle(cx, cy, (D1 / 2) * S, 'none', THIN);
76
+ circle(cx, cy, (d / 2) * S, '#fff');
77
+ line(cx - R * S - 8, cy, cx + R * S + 8, cy, THIN, 0.5, '8 3 2 3'); line(cx, cy - R * S - 8, cx, cy + R * S + 8, THIN, 0.5, '8 3 2 3');
78
+ span(cx - (D / 2) * S, bottom + 6, cx + (D / 2) * S, bottom + 6, `Ø${fig(D)}`, 18);
79
+ span(cx - (d / 2) * S, top - 6, cx + (d / 2) * S, top - 6, `bore Ø${fig(d)}`, -14);
80
+ if (F) text(cx, bottom + 66, `flange Ø${fig(F)}, ${fig(Fw)} thick`);
81
+ if (thrust) text(cx, bottom + 66, `shaft washer Ø${fig(d1)}, housing washer bore Ø${fig(D1)}`);
82
+ // ---- the section, axis along the sheet ----
83
+ for (const side of [-1, 1]) {
84
+ const y = (a, b) => (side < 0 ? [cy - b * S, (b - a) * S] : [cy + a * S, (b - a) * S]);
85
+ const [ry, rh] = y(d / 2, D / 2); rect(sx, ry, B * S, rh);
86
+ if (F) { const [fy, fh] = y(D / 2, F / 2); rect(sx, fy, Fw * S, fh, '#ddd9cf'); }
87
+ if (thrust) line(sx + (B * S) / 2, ry, sx + (B * S) / 2, ry + rh, THIN, 0.8, '4 3');
88
+ }
89
+ line(sx - 12, cy, sx + B * S + 12, cy, THIN, 0.5, '8 3 2 3');
90
+ span(sx, bottom + 6, sx + B * S, bottom + 6, `${fig(B)}`, 18);
91
+ span(sx + B * S + 6, cy - (D / 2) * S, sx + B * S + 6, cy + (D / 2) * S, `Ø${fig(D)}`, 30);
92
+ text(sx + (B * S) / 2, top - 22, `chamfer ${fig(n('chamfer'))}`, 'middle', 11);
93
+ text(cx, bottom + 86, `${set.rules.type?.value || 'bearing'}: ${fig(n('dynamic_rating'))} N dynamic, ${fig(n('static_rating'))} N static${set.rules.radial_play ? `, ${set.rules.radial_play.value}` : ''}`, 'middle', 11);
94
+ return sheet(set, pens, W, H);
95
+ }
96
+
97
+ // A driver module from above: the board and its two header rows, at their spacing
98
+ function driverDrawing(set) {
99
+ const n = (k) => set.rules[k]?.value ?? 0, w = n('body_width'), d = n('body_depth'), pitch = n('pin_pitch'), row = n('row_spacing'), count = n('pin_count') / 2;
100
+ const S = 16, W = w * S + 260, H = d * S + 170, cx = W / 2, cy = H / 2 + 22, X = (x) => cx + x * S, Y = (y) => cy - y * S;
101
+ const pens = pen(), { line, circle, rect, text, span } = pens;
102
+ rect(X(-w / 2), Y(d / 2), w * S, d * S);
103
+ const pins = Array.from({ length: count }, (_, i) => (i - (count - 1) / 2) * pitch);
104
+ for (const y of [-row / 2, row / 2]) for (const x of pins) circle(X(x), Y(y), (pitch / 3.2) * S, METAL);
105
+ line(X(-w / 2) - 10, Y(0), X(w / 2) + 10, Y(0), THIN, 0.5, '8 3 2 3');
106
+ span(X(-w / 2), Y(-d / 2) + 6, X(w / 2), Y(-d / 2) + 6, `${fig(w)}`, 18);
107
+ span(X(-w / 2) - 6, Y(d / 2), X(-w / 2) - 6, Y(-d / 2), `${fig(d)}`, -18);
108
+ span(X(w / 2) + 6, Y(row / 2), X(w / 2) + 6, Y(-row / 2), `rows ${fig(row)}`, 18);
109
+ span(X(pins[0]), Y(d / 2) - 6, X(pins[1]), Y(d / 2) - 6, `pitch ${fig(pitch)}`, -14);
110
+ text(cx, Y(-d / 2) + 66, `${n('pin_count')} pins: ${set.rules.vref_formula?.value ?? ''}`, 'middle', 11);
111
+ text(cx, Y(-d / 2) + 84, `Rs ${n('sense_resistor')} ohm, ${n('vref_gain')} A per volt of Vref`, 'middle', 11);
112
+ return sheet(set, pens, W, H);
113
+ }
114
+
115
+ // A round part from its end and along its axis: linear bearings, nuts, couplers, pulleys, idlers, rods. Each says what it has: flange, hole circle, a dashed pitch circle, the bores of a coupler
116
+ function roundDrawing(set, { D, d = 0, L, bores, flange, circle: holeCircle, pitchD, notes = [] }) {
117
+ const R = Math.max(D, flange?.D ?? 0) / 2, S = Math.max(3, Math.min(14, 90 / R)), W = 2 * R * S + L * S + 340, H = 2 * R * S + 190;
118
+ const cx = R * S + 70, cy = H / 2 + 22, sx = cx + R * S + 120, top = cy - R * S, bottom = cy + R * S;
119
+ const pens = pen(), { line, circle, rect, text, span } = pens;
120
+ // ---- from the end ----
121
+ if (flange) circle(cx, cy, (flange.D / 2) * S, '#f6f4ee');
122
+ circle(cx, cy, (D / 2) * S, FILL);
123
+ if (pitchD) circle(cx, cy, (pitchD / 2) * S, 'none', THIN);
124
+ if (d) circle(cx, cy, (d / 2) * S, '#fff');
125
+ if (holeCircle) for (let i = 0; i < holeCircle.count; i++) { const a = (2 * Math.PI * i) / holeCircle.count; circle(cx + (holeCircle.D / 2) * Math.cos(a) * S, cy + (holeCircle.D / 2) * Math.sin(a) * S, (holeCircle.hole / 2) * S, '#fff'); }
126
+ line(cx - R * S - 8, cy, cx + R * S + 8, cy, THIN, 0.5, '8 3 2 3'); line(cx, cy - R * S - 8, cx, cy + R * S + 8, THIN, 0.5, '8 3 2 3');
127
+ span(cx - R * S, bottom + 6, cx + R * S, bottom + 6, `Ø${fig(flange?.D ?? D)}`, 18);
128
+ if (d) span(cx - (d / 2) * S, top - 6, cx + (d / 2) * S, top - 6, `bore Ø${fig(d)}`, -14);
129
+ // ---- along the axis ----
130
+ const ring = (x, len, a, b, fill = FILL) => { for (const side of [-1, 1]) rect(x, side < 0 ? cy - (b / 2) * S : cy + (a / 2) * S, len * S, ((b - a) / 2) * S, fill); };
131
+ if (bores) { ring(sx, L / 2, bores[0], D); ring(sx + (L / 2) * S, L / 2, bores[1], D); }
132
+ else if (d) ring(sx, L, d, D);
133
+ else rect(sx, cy - (D / 2) * S, L * S, D * S, METAL);
134
+ if (flange) ring(sx + flange.at * S, flange.w, d, flange.D, '#ddd9cf');
135
+ line(sx - 12, cy, sx + L * S + 12, cy, THIN, 0.5, '8 3 2 3');
136
+ span(sx, bottom + 6, sx + L * S, bottom + 6, `${fig(L)}`, 18);
137
+ span(sx + L * S + 6, cy - (D / 2) * S, sx + L * S + 6, cy + (D / 2) * S, `Ø${fig(D)}`, 30);
138
+ notes.forEach((t, i) => text(cx, bottom + 66 + i * 18, t, 'middle', 11));
139
+ return sheet(set, pens, W, H);
140
+ }
141
+
142
+ // A lead screw from the side: the crest and root, the starts' flanks, and pitch against lead
143
+ function leadScrewDrawing(set) {
144
+ const n = (k) => set.rules[k]?.value ?? 0, D = n('diameter'), root = n('root_diameter'), P = n('pitch'), lead = n('lead'), starts = n('starts') || 1;
145
+ const L = Math.max(3 * lead, 20), S = Math.min(14, 420 / L), W = L * S + 240, H = D * S + 200, x0 = 110, cy = H / 2 + 12;
146
+ const pens = pen(), { line, rect, text, span } = pens;
147
+ rect(x0, cy - (D / 2) * S, L * S, D * S, METAL);
148
+ for (const side of [-1, 1]) line(x0, cy + side * (root / 2) * S, x0 + L * S, cy + side * (root / 2) * S, THIN, 0.6, '4 3');
149
+ const lean = (D * S * Math.tan((n('helix_angle') * Math.PI) / 180)) / 2;
150
+ for (let i = 0; i * P <= L + 1e-9; i++) { const x = x0 + i * P * S; if (x - lean >= x0 && x + lean <= x0 + L * S) line(x - lean, cy + (D / 2) * S, x + lean, cy - (D / 2) * S, i % starts === 0 ? INK : THIN, i % starts === 0 ? 1.6 : 0.7); }
151
+ line(x0 - 12, cy, x0 + L * S + 12, cy, THIN, 0.5, '8 3 2 3');
152
+ const below = cy + (D / 2) * S + 6, above = cy - (D / 2) * S - 6;
153
+ span(x0, below, x0 + P * S, below, `pitch ${fig(P)}`, 18);
154
+ span(x0, below, x0 + lead * S, below, `lead ${fig(lead)}`, 44);
155
+ span(x0 + L * S + 6, cy - (D / 2) * S, x0 + L * S + 6, cy + (D / 2) * S, `Ø${fig(D)}`, 30);
156
+ span(x0 - 6, cy - (root / 2) * S, x0 - 6, cy + (root / 2) * S, `root Ø${fig(root)}`, -18);
157
+ text(x0 + (L * S) / 2, above - 8, `${set.rules.thread?.value ?? ''}, ${fig(starts)} start${starts > 1 ? 's' : ''}, helix ${fig(n('helix_angle'))}°`, 'middle', 12);
158
+ text(x0 + (L * S) / 2, below + 72, 'each dark line one start, repeating at the lead', 'middle', 11);
159
+ return sheet(set, pens, W, H);
160
+ }
161
+
162
+ // A short length of belt, teeth along it
163
+ function beltDrawing(set) {
164
+ const n = (k) => set.rules[k]?.value ?? 0, P = n('pitch'), w = n('width'), L = P * 8, S = 12, W = L * S + 220, H = w * S + 190, x0 = 90, cy = H / 2 + 10;
165
+ const pens = pen(), { line, rect, text, span } = pens;
166
+ rect(x0, cy - (w / 2) * S, L * S, w * S);
167
+ for (let i = 0; i <= 8; i++) line(x0 + i * P * S, cy - (w / 2) * S, x0 + i * P * S, cy + (w / 2) * S, THIN, 0.7);
168
+ span(x0, cy + (w / 2) * S + 6, x0 + P * S, cy + (w / 2) * S + 6, `pitch ${fig(P)}`, 18);
169
+ span(x0 + L * S + 6, cy - (w / 2) * S, x0 + L * S + 6, cy + (w / 2) * S, `${fig(w)}`, 18);
170
+ text(x0 + (L * S) / 2, cy + (w / 2) * S + 66, `${fig(n('stiffness'))} N per unit strain, pitch line ${n('pitch_line_offset')} beyond the teeth`, 'middle', 11);
171
+ text(x0 + (L * S) / 2, cy + (w / 2) * S + 84, `rated ${fig(n('rated_tension'))} N, breaks at ${fig(n('breaking_strength'))} N`, 'middle', 11);
172
+ return sheet(set, pens, W, H);
173
+ }
174
+
41
175
  export function drawing(set, vocab) {
176
+ if (set.part === 'bearing') return bearingDrawing(set);
177
+ if (set.part === 'driver') return driverDrawing(set);
178
+ const v = (k) => set.rules[k]?.value ?? 0;
179
+ if (set.part === 'leadscrew') return leadScrewDrawing(set);
180
+ if (set.part === 'belt') return beltDrawing(set);
181
+ if (set.part === 'linear_bearing') return roundDrawing(set, { D: v('outer_diameter'), d: v('bore'), L: v('length'), notes: [`linear bearing: ${fig(v('dynamic_rating'))} N dynamic, ${fig(v('static_rating'))} N static`] });
182
+ if (set.part === 'nut') { return roundDrawing(set, { D: v('body_diameter'), d: v('diameter'), L: v('length'), flange: { D: v('flange_diameter'), w: v('flange_width'), at: v('flange_offset') }, circle: { D: v('hole_circle'), count: v('hole_count'), hole: v('mount_hole_diameter') || 3.5 }, notes: [`${set.rules.thread?.value ?? ''}, ${set.rules.material?.value ?? ''}, lead ${fig(v('lead'))}`, `${fig(v('hole_count'))} × Ø${fig(v('mount_hole_diameter'))} on Ø${fig(v('hole_circle'))}`] }); }
183
+ if (set.part === 'coupler') return roundDrawing(set, { D: v('outer_diameter'), L: v('length'), bores: [v('bore_a'), v('bore_b')], d: 0, notes: [`bores Ø${fig(v('bore_a'))} and Ø${fig(v('bore_b'))}`, String(set.rules.style?.value ?? '')] });
184
+ if (set.part === 'pulley' || set.part === 'idler') return roundDrawing(set, { D: v('outer_diameter'), d: v('bore'), L: v('body_width'), pitchD: v('pitch_diameter'), notes: [set.part === 'pulley' ? `${fig(v('teeth'))} teeth, pitch circle Ø${fig(v('pitch_diameter'))} (thin), across the teeth Ø${fig(v('tooth_diameter'))}` : `${set.rules.toothed?.value === 'yes' ? `${fig(v('teeth'))} teeth` : 'smooth'}, for ${fig(v('belt_width'))} mm belt`, set.part === 'pulley' ? `for ${fig(v('belt_width'))} mm belt` : ''] });
185
+ if (set.part === 'rod') return roundDrawing(set, { D: v('diameter'), L: 40, notes: [`${String(set.rules.tolerance?.value ?? '')}; ${String(set.rules.hardness?.value ?? '')}`] });
42
186
  const get = (k) => { const r = set.rules[set.interface?.[k] ?? k]; return r?.value; }, n = (k, d = 0) => { const x = get(k); return typeof x === 'number' ? x : d; };
43
187
  if (!set.part && !Object.keys(set.interface || {}).some((k) => k.startsWith('body_'))) throw new Error(`rule set "${set.name}" doesn't say what shape it is (no body_ names in it, or "part", or "interface"): there's nothing to draw`);
44
188
  const shape = get('body_shape') ?? 'box', round = shape === 'round', w = round ? n('body_diameter') : n('body_width'), d = round ? w : shape === 'square' ? w : n('body_depth', n('body_width'));
@@ -52,17 +196,7 @@ export function drawing(set, vocab) {
52
196
  const W = 2 * reach * S + (L + Math.max(shaftL, top + bossH) + 8) * S + 200, H = Math.max(2 * reach * S + 150, 280);
53
197
  const fx = reach * S + 70, fy = H / 2 + 8, X = (x) => fx + x * S, Y = (y) => fy - y * S; // the face view, shaft at the origin
54
198
  const sx = fx + reach * S + 90 + L * S, SX = (z) => sx + z * S, SY = (y) => fy - y * S; // the side view: z along the sheet, the mounting face at z = 0
55
- const out = [];
56
- const line = (a, b, c, e, s = INK, sw = 1.2, dash = '') => out.push(`<line x1="${fig(a)}" y1="${fig(b)}" x2="${fig(c)}" y2="${fig(e)}" stroke="${s}" stroke-width="${sw}"${dash ? ` stroke-dasharray="${dash}"` : ''}/>`);
57
- const circle = (x, y, r, fill = 'none', s = INK) => out.push(`<circle cx="${fig(x)}" cy="${fig(y)}" r="${fig(r)}" fill="${fill}" stroke="${s}" stroke-width="1.2"/>`);
58
- const rect = (x, y, a, b, fill = FILL) => out.push(`<rect x="${fig(x)}" y="${fig(y)}" width="${fig(a)}" height="${fig(b)}" fill="${fill}" stroke="${INK}" stroke-width="1.2"/>`);
59
- const text = (x, y, t, a = 'middle', z = 12) => out.push(`<text x="${fig(x)}" y="${fig(y)}" text-anchor="${a}" font-size="${z}" font-family="system-ui, sans-serif" fill="${INK}">${t}</text>`);
60
- const span = (x1, y1, x2, y2, t, across_ = 14) => { // a dimension: extension lines, a line with its ticks, the figure
61
- const horizontal = Math.abs(y2 - y1) < 1e-6, ox = horizontal ? 0 : across_, oy = horizontal ? across_ : 0;
62
- line(x1, y1, x1 + ox, y1 + oy, THIN, 0.6); line(x2, y2, x2 + ox, y2 + oy, THIN, 0.6); line(x1 + ox, y1 + oy, x2 + ox, y2 + oy, THIN, 0.8);
63
- for (const [a, b] of [[x1 + ox, y1 + oy], [x2 + ox, y2 + oy]]) line(a - 3, b + 3, a + 3, b - 3, THIN, 0.8);
64
- if (horizontal) text((x1 + x2) / 2, y1 + oy + (across_ > 0 ? 13 : -4), t); else text(x1 + ox + (across_ > 0 ? 4 : -4), (y1 + y2) / 2 + 4, t, across_ > 0 ? 'start' : 'end');
65
- };
199
+ const pens = pen(), { out, line, circle, rect, text, span } = pens;
66
200
  // ---- the face, from the shaft's end ----
67
201
  if (tabs) rect(X(cx - tabs / 2), Y(cy + d / 2), tabs * S, d * S, '#f6f4ee');
68
202
  for (const [hx, hy] of earR ? holes : []) circle(X(hx), Y(hy), earR * S, '#f6f4ee');
@@ -96,11 +230,7 @@ export function drawing(set, vocab) {
96
230
  if (shaftL) span(SX(top + (top ? bossH : 0)), under, SX(top + (top ? bossH : 0) + shaftL), under, `shaft ${fig(shaftL)}`, 36);
97
231
  if (flat) span(SX(top + (top ? bossH : 0) + shaftL - flat), SY(shaftD / 2) - 4, SX(top + (top ? bossH : 0) + shaftL), SY(shaftD / 2) - 4, `flat ${fig(flat)}`, -14);
98
232
  if (bossH) text(SX(bossAt + bossH / 2), under + 74, `boss ${fig(bossH)} high`, 'middle', 11);
99
- // ---- what's trustworthy ----
100
- const kinds = Object.values(set.rules).reduce((m, r) => ({ ...m, [r.kind]: (m[r.kind] || 0) + 1 }), {});
101
- text(20, 26, set.name, 'start', 16);
102
- text(20, 44, `all in mm. ${Object.entries(kinds).map(([k, c]) => `${c} ${k}`).join(', ')}: compare it with the datasheet`, 'start', 11);
103
- return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${fig(W)} ${fig(H + 60)}" width="${fig(W)}" height="${fig(H + 60)}"><rect width="100%" height="100%" fill="#fff"/>${out.join('')}</svg>\n`;
233
+ return sheet(set, pens, W, H);
104
234
  }
105
235
 
106
236
  // ---------- a draft from a datasheet's text ----------
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);