@rulecad/cad 0.7.48 → 0.7.55

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.
@@ -0,0 +1,278 @@
1
+ // cad measure <model> --profile <name>: a beam's section read from a model from elsewhere (STL, 3MF) or from a DXF of
2
+ // the section, and written as a draft profile set with its outline in the workspace's rules/. The outline is the
3
+ // model's shape, so it goes into the person's own workspace with its source and licence, and nowhere else: the kit
4
+ // holds only outlines drawn for it. What is read off it (size, slots, bores) is measurement: kind derived, to check
5
+ // against the bar in hand.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { signedArea, polygonSection, slotModel } from '@rulecad/frames';
10
+ import { fmt } from './rules.mjs';
11
+ import { WS, paths, RULE_DIRS } from './workspace.mjs';
12
+ import { picture } from './preview.mjs';
13
+ import { AXES, axisOf, readMesh, bounds, section, profiles, loops as chain, limitingLicence } from './mesh.mjs';
14
+
15
+ const f2 = (n) => fmt(Math.round(n * 100) / 100), r2 = (n) => Math.round(n * 100) / 100, today = () => new Date().toISOString().slice(0, 10);
16
+ const RAD = Math.PI / 180;
17
+
18
+ // ---------- a DXF section ----------
19
+ const REFUSED = { SPLINE: 'a spline', ELLIPSE: 'an ellipse', POLYLINE: 'an old-style POLYLINE', INSERT: 'a block (INSERT)', HATCH: 'a hatch', '3DFACE': 'a 3D face', MLINE: 'a multiline', REGION: 'a region', LEADER: 'a leader' };
20
+ const IGNORED = new Set(['TEXT', 'MTEXT', 'DIMENSION', 'POINT', 'ATTDEF', 'ATTRIB', 'VIEWPORT']);
21
+ const UNITS = { 0: 1, 4: 1, 1: 25.4, 5: 10, 6: 1000 }; // $INSUNITS: unitless and mm as they are, inches, cm, m
22
+
23
+ /**
24
+ * A DXF's section as closed loops in mm. Reads LINE, LWPOLYLINE (with its bulges), ARC and CIRCLE from the ENTITIES
25
+ * section; text and dimensions are passed over; a SPLINE, an ELLIPSE or a block is refused by name, since guessing at
26
+ * one would put a wrong outline in a rule set. @param {string} text @returns {{ loops: number[][][], notes: string[] }}
27
+ */
28
+ export function readDxf(text, { chord = 0.002 } = {}) {
29
+ const lines = String(text).split(/\r?\n/), pairs = [];
30
+ for (let i = 0; i + 1 < lines.length; i += 2) { const code = Number(lines[i].trim()); if (!Number.isInteger(code)) throw new Error(`not a DXF: line ${i + 1} should be a group code (a whole number), and is ${JSON.stringify(lines[i].slice(0, 30))}`); pairs.push([code, lines[i + 1].trim()]); }
31
+ if (!pairs.some(([c, v]) => c === 0 && v === 'SECTION')) throw new Error('not a DXF: it has no SECTION (an ASCII DXF is wanted, not a binary one or a DWG)');
32
+ let scale = 1; const notes = [];
33
+ const units = pairs.findIndex(([c, v]) => c === 9 && v === '$INSUNITS');
34
+ if (units >= 0) { const u = Number(pairs[units + 1]?.[1]); if (!(u in UNITS)) throw new Error(`the DXF's units ($INSUNITS ${u}) are not ones this reads: millimetres (4), inches (1), centimetres (5), metres (6) or none (taken as mm)`); scale = UNITS[u]; if (scale !== 1) notes.push(`its units are ${{ 1: 'inches', 5: 'centimetres', 6: 'metres' }[u]}: turned into mm`); }
35
+ else notes.push('it names no units ($INSUNITS): taken as mm');
36
+ const start = pairs.findIndex(([c, v], i) => c === 2 && v === 'ENTITIES' && pairs[i - 1]?.[1] === 'SECTION');
37
+ if (start < 0) throw new Error('the DXF has no ENTITIES section: nothing is drawn in it');
38
+ const entities = []; let cur = null;
39
+ for (let i = start + 1; i < pairs.length; i++) { const [c, v] = pairs[i]; if (c === 0) { if (v === 'ENDSEC') break; cur = { type: v, codes: [] }; entities.push(cur); } else if (cur) cur.codes.push([c, v]); }
40
+ const segs = [], closed = [], passed = new Map();
41
+ // an arc as chords that stay within `chord` mm of it; a model's circle is likewise facets with their corners on it
42
+ const arc = (cx, cy, r, a0, sweep) => { const c = chord / scale, n = Math.max(2, Math.ceil(Math.abs(sweep) / (2 * Math.acos(Math.max(0, 1 - c / Math.max(r, c)))))); return Array.from({ length: n + 1 }, (_, k) => [cx + r * Math.cos(a0 + (sweep * k) / n), cy + r * Math.sin(a0 + (sweep * k) / n)]); };
43
+ const bulged = (p, q, b) => { // the arc from p to q that a polyline's bulge asks for: b is tan of a quarter of its angle
44
+ if (!b) return [p, q];
45
+ const dx = q[0] - p[0], dy = q[1] - p[1], c = Math.hypot(dx, dy); if (!c) return [p];
46
+ const d = ((c / 2) * (1 - b * b)) / (2 * b), cx = (p[0] + q[0]) / 2 - (dy / c) * d, cy = (p[1] + q[1]) / 2 + (dx / c) * d;
47
+ const pts = arc(cx, cy, Math.hypot(p[0] - cx, p[1] - cy), Math.atan2(p[1] - cy, p[0] - cx), 4 * Math.atan(b)); pts[0] = p; pts[pts.length - 1] = q; return pts;
48
+ };
49
+ for (const e of entities) {
50
+ const g = (code) => { const x = e.codes.find(([c]) => c === code); return x ? Number(x[1]) : undefined; }, all = (code) => e.codes.filter(([c]) => c === code).map(([, v]) => Number(v));
51
+ if (REFUSED[e.type]) throw new Error(`the DXF has ${REFUSED[e.type]} (${e.type}), which this does not read: export the section as lines, arcs and polylines (most CAD programs can "explode" or "convert to polyline"), and measure that`);
52
+ if (e.type === 'LINE') segs.push([[g(10), g(20)], [g(11), g(21)]]);
53
+ else if (e.type === 'CIRCLE') closed.push(arc(g(10), g(20), g(40), 0, 2 * Math.PI).slice(0, -1));
54
+ else if (e.type === 'ARC') { const a0 = g(50) * RAD; let sweep = (g(51) - g(50)) * RAD; while (sweep <= 0) sweep += 2 * Math.PI; const pts = arc(g(10), g(20), g(40), a0, sweep); for (let k = 0; k + 1 < pts.length; k++) segs.push([pts[k], pts[k + 1]]); }
55
+ else if (e.type === 'LWPOLYLINE') {
56
+ const pts = [], isClosed = ((g(70) ?? 0) & 1) === 1; let b = null;
57
+ for (const [c, v] of e.codes) { if (c === 10) { pts.push({ p: [Number(v), 0], b: 0 }); b = pts[pts.length - 1]; } else if (c === 20 && b) b.p[1] = Number(v); else if (c === 42 && b) b.b = Number(v); }
58
+ const out = [];
59
+ for (let k = 0; k < pts.length - (isClosed ? 0 : 1); k++) { const run = bulged(pts[k].p, pts[(k + 1) % pts.length].p, pts[k].b); out.push(...run.slice(0, -1)); if (!isClosed && k === pts.length - 2) out.push(run[run.length - 1]); }
60
+ if (isClosed) closed.push(out); else for (let k = 0; k + 1 < out.length; k++) segs.push([out[k], out[k + 1]]);
61
+ } else if (IGNORED.has(e.type)) passed.set(e.type, (passed.get(e.type) || 0) + 1);
62
+ else throw new Error(`the DXF has a ${e.type}, which this does not read: a section is LINE, LWPOLYLINE, ARC and CIRCLE entities`);
63
+ if ([...all(10), ...all(20)].some((x) => !Number.isFinite(x))) throw new Error(`the DXF's ${e.type} has a coordinate that is not a number`);
64
+ }
65
+ if (passed.size) notes.push(`passed over: ${[...passed].map(([t, n]) => `${n} ${t}`).join(', ')}`);
66
+ // lines and arcs drawn one by one: joined end to end into loops, which must close
67
+ for (const line of chain(segs, 1e-3)) {
68
+ const gap = Math.hypot(line[0][0] - line[line.length - 1][0], line[0][1] - line[line.length - 1][1]);
69
+ if (gap > 0.01) throw new Error(`the DXF's outline is not closed: a run of ${line.length - 1} lines and arcs ends ${f2(gap * scale)} mm from where it starts, at ${f2(line[line.length - 1][0] * scale)}, ${f2(line[line.length - 1][1] * scale)}. Close the gap (or delete the stray line) and measure again`);
70
+ closed.push(line.slice(0, -1));
71
+ }
72
+ if (!closed.length) throw new Error('the DXF has no outline: no LINE, LWPOLYLINE, ARC or CIRCLE in its ENTITIES section');
73
+ return { loops: closed.map((l) => l.map(([x, y]) => [x * scale, y * scale])), notes };
74
+ }
75
+
76
+ // ---------- the section of a model ----------
77
+ // The loops of the longest stretch of a mesh that keeps one cross-section
78
+ function meshSection(file, along) {
79
+ const tris = readMesh(file), B = bounds(tris), axis = along ? axisOf(along) : B.size.indexOf(Math.max(...B.size));
80
+ const runs = profiles(tris, axis).filter((r) => !r.varies && !r.empty).sort((a, b) => b.to - b.from - (a.to - a.from));
81
+ if (!runs.length) throw new Error(`${path.basename(file)} has no stretch along ${AXES[axis]} that keeps one cross-section: a beam's profile is measured where its section is constant (--along x|y|z picks another axis)`);
82
+ const run = runs[0], lines = chain(section(tris, axis, run.at));
83
+ for (const l of lines) if (Math.hypot(l[0][0] - l[l.length - 1][0], l[0][1] - l[l.length - 1][1]) > 1e-3) throw new Error(`${path.basename(file)}: its section at ${AXES[axis]} = ${f2(run.at)} is not closed outlines (the mesh has open edges there)`);
84
+ return { loops: lines.map((l) => l.slice(0, -1)), says: `the section across ${AXES[axis]} at ${f2(run.at)}, the middle of a stretch of ${f2(run.to - run.from)} mm that keeps it (of ${f2(B.size[axis])} mm)`, length: run.to - run.from };
85
+ }
86
+
87
+ // Loops tidied: no point twice, no point in the middle of a straight run, nothing with no area; about the middle of
88
+ // the envelope, lying flat (wider than high), the outside counter-clockwise and holes clockwise
89
+ export function tidy(loops) {
90
+ let out = loops.map((l) => { const p = l.filter((q, i) => { const n = l[(i + 1) % l.length]; return Math.hypot(q[0] - n[0], q[1] - n[1]) > 1e-6; }); return p.filter((q, i) => { const a = p[(i + p.length - 1) % p.length], b = p[(i + 1) % p.length]; return Math.abs((q[0] - a[0]) * (b[1] - a[1]) - (q[1] - a[1]) * (b[0] - a[0])) > 1e-7 * (1 + Math.hypot(b[0] - a[0], b[1] - a[1])); }); }).filter((l) => l.length >= 3 && Math.abs(signedArea(l)) > 1e-6);
91
+ if (!out.length) throw new Error('the section has no outline with any area');
92
+ const xs = out.flat().map((p) => p[0]), ys = out.flat().map((p) => p[1]), cx = (Math.min(...xs) + Math.max(...xs)) / 2, cy = (Math.min(...ys) + Math.max(...ys)) / 2;
93
+ let turned = false; out = out.map((l) => l.map(([x, y]) => [x - cx, y - cy]));
94
+ if (Math.max(...ys) - Math.min(...ys) > Math.max(...xs) - Math.min(...xs) + 1e-6) { out = out.map((l) => l.map(([x, y]) => [y, -x])); turned = true; }
95
+ out.sort((a, b) => Math.abs(signedArea(b)) - Math.abs(signedArea(a)));
96
+ const inside = ([x, y], loop) => { let inn = false; for (let i = 0, n = loop.length; i < n; i++) { const [ax, ay] = loop[i], [bx, by] = loop[(i + 1) % n]; if ((ay > y) !== (by > y) && x < ax + ((y - ay) * (bx - ax)) / (by - ay)) inn = !inn; } return inn; };
97
+ out = out.map((l, i) => { const depth = out.filter((o, j) => j !== i && inside(l[0], o)).length; return (depth % 2 === 0) === signedArea(l) > 0 ? l : l.slice().reverse(); });
98
+ return { loops: out.map((l) => l.map(([x, y]) => [+x.toFixed(4), +y.toFixed(4)])), turned };
99
+ }
100
+
101
+ // ---------- what a section has ----------
102
+ const FACES = { top: { n: [0, 1], a: [1, 0] }, bottom: { n: [0, -1], a: [1, 0] }, front: { n: [-1, 0], a: [0, 1] }, back: { n: [1, 0], a: [0, 1] } };
103
+
104
+ // One slot from its run of the outline in face coordinates [u along the face, v below it], mouth to mouth
105
+ function slotOf(run) {
106
+ const D = Math.max(...run.map((p) => p[1])), n = 600, step = D / n, mouth = Math.abs(run[run.length - 1][0] - run[0][0]), centre = (run[0][0] + run[run.length - 1][0]) / 2;
107
+ const width = (v) => { let lo = Infinity, hi = -Infinity; for (let i = 0; i + 1 < run.length; i++) { const [a, b] = [run[i], run[i + 1]]; if ((a[1] <= v && b[1] > v) || (b[1] <= v && a[1] > v)) { const u = a[0] + ((v - a[1]) * (b[0] - a[0])) / (b[1] - a[1]); lo = Math.min(lo, u); hi = Math.max(hi, u); } } return hi - lo; };
108
+ const w = Array.from({ length: n }, (_, k) => width((k + 0.5) * step)), widest = Math.max(...w);
109
+ // the neck: from the face down to where the width jumps toward the cavity's
110
+ let least = w[0], neck = -1;
111
+ for (let k = 0; k < n; k++) { least = Math.min(least, w[k]); if (widest - least > 0.2 && w[k] > least + 0.5 * (widest - least)) { neck = k; break; } }
112
+ if (neck < 0) return { kind: 'groove', centre, mouth, depth: D }; // no wider below than at its mouth: a groove, not a slot for a nut
113
+ const opening = Math.min(...w.slice(0, neck));
114
+ let tip = 0; for (let k = 0; k < neck; k++) if (w[k] <= opening + 0.05) tip = k; // the last depth still at the opening: the lip's tip
115
+ const lip = (tip + 1) * step;
116
+ let straight = neck; for (let k = neck; k < n; k++) if (w[k] >= widest - 0.05) straight = k;
117
+ const floor = w[n - 1], out = { kind: 'slot', centre, mouth, opening, lip, cavityWidth: widest, cavityDepth: D, floorWidth: floor };
118
+ if (floor < widest - 0.1) { out.flankAngle = Math.atan2(D - (straight + 1) * step, (widest - floor) / 2) / RAD; if (!(out.flankAngle > 1)) { delete out.flankAngle; out.floorWidth = widest; } } else out.floorWidth = widest;
119
+ if (mouth > opening + 0.2) { let k = 0; while (k < neck && w[k] > opening + 0.05) k++; out.trackWidth = mouth; out.trackAngle = (2 * Math.atan2((mouth - opening) / 2, Math.max(k * step, step))) / RAD; }
120
+ return out;
121
+ }
122
+
123
+ /**
124
+ * What a section has, from its tidied loops: the envelope, each face's slots (opening, lip, width under the lips,
125
+ * depth, floor, flanks, a V mouth), round bores and other hollows.
126
+ * @param {number[][][]} loops the outside first (counter-clockwise), then holes
127
+ */
128
+ export function findFeatures(loops) {
129
+ const outer = loops[0], xs = outer.map((p) => p[0]), ys = outer.map((p) => p[1]), W = Math.max(...xs) - Math.min(...xs), H = Math.max(...ys) - Math.min(...ys), on = 0.25;
130
+ const faces = {};
131
+ for (const [face, { n, a }] of Object.entries(FACES)) {
132
+ const half = n[0] ? W / 2 : H / 2, across = n[0] ? H : W, uv = outer.map(([x, y]) => [x * a[0] + y * a[1], half - (x * n[0] + y * n[1])]), N = uv.length, found = [];
133
+ const start = uv.findIndex((p, i) => p[1] <= on && uv[(i + 1) % N][1] > on);
134
+ if (start >= 0) for (let i = 0; i < N; i++) {
135
+ const k = (start + i) % N; if (!(uv[k][1] <= on && uv[(k + 1) % N][1] > on)) continue;
136
+ const run = [uv[k]]; let j = (k + 1) % N; while (uv[j][1] > on && run.length <= N) { run.push(uv[j]); j = (j + 1) % N; } run.push(uv[j]);
137
+ const deep = Math.max(...run.map((p) => p[1])), wide = Math.max(...run.map((p) => p[0])) - Math.min(...run.map((p) => p[0]));
138
+ if (deep >= (n[0] ? W : H) - on || wide > across * 0.9 || deep < 0.5) continue; // round a corner to another face, or a scratch
139
+ const s = slotOf(run[0][0] <= run[run.length - 1][0] ? run : run.slice().reverse());
140
+ found.push({ ...s, face, at: [a[0] * s.centre + n[0] * half, a[1] * s.centre + n[1] * half] });
141
+ }
142
+ faces[face] = found.sort((p, q) => p.centre - q.centre);
143
+ }
144
+ const bores = [], hollows = [];
145
+ for (const l of loops.slice(1)) {
146
+ const p = polygonSection([l.slice().reverse()]), c = p.centroid, rs = l.map(([x, y]) => Math.hypot(x - c[0], y - c[1])), mean = rs.reduce((s, r) => s + r, 0) / rs.length;
147
+ const bx = l.map((q) => q[0]), by = l.map((q) => q[1]);
148
+ if (Math.max(...rs) - Math.min(...rs) < 0.03 * mean + 0.03) bores.push({ at: [r2(c[0]), r2(c[1])], diameter: 2 * mean });
149
+ else hollows.push({ at: [r2(c[0]), r2(c[1])], width: Math.max(...bx) - Math.min(...bx), height: Math.max(...by) - Math.min(...by), area: p.area });
150
+ }
151
+ return { width: W, height: H, faces, bores, hollows, area: polygonSection(loops).area };
152
+ }
153
+
154
+ // ---------- slots against the families there are ----------
155
+ const DIMS = [['opening', 'opening'], ['lip_thickness', 'lip'], ['cavity_width', 'cavityWidth'], ['cavity_depth', 'cavityDepth']];
156
+ function allSets() { // every rule set by name, the workspace's own first
157
+ const found = new Map();
158
+ for (const d of RULE_DIRS) if (fs.existsSync(d)) for (const f of fs.readdirSync(d).sort()) if (f.endsWith('.json') && !['package.json', 'vocabulary.json'].includes(f) && !found.has(f.slice(0, -5))) found.set(f.slice(0, -5), path.join(d, f));
159
+ return found;
160
+ }
161
+ /** The slot family nearest a measured slot, and how far off its worst figure is: { name, off } or null where there is none */
162
+ export function nearestFamily(slot, families) {
163
+ let best = null;
164
+ for (const [name, set] of Object.entries(families)) { const off = Math.max(...DIMS.map(([rule, k]) => Math.abs((set.rules[rule]?.value ?? Infinity) - slot[k]))); if (!best || off < best.off) best = { name, off }; }
165
+ return best;
166
+ }
167
+
168
+ // ---------- the drawing ----------
169
+ function drawingSvg({ name, file, loops, feat, groups, bores, source, licence }) {
170
+ const W = feat.width, H = feat.height, S = Math.min(22, 560 / Math.max(W, H)), pad = 150, w = W * S + 2 * pad, top = 110, X = (x) => pad + (x + W / 2) * S, Y = (y) => top + (H / 2 - y) * S;
171
+ const esc = (t) => String(t).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
172
+ const d = loops.map((l) => `M ${l.map(([x, y]) => `${X(x).toFixed(2)} ${Y(y).toFixed(2)}`).join(' L ')} Z`).join(' ');
173
+ let body = `<path d="${d}" fill="#c4c8cc" fill-rule="evenodd" stroke="#1a1a1a" stroke-width="1.2" stroke-linejoin="round"/>`;
174
+ const text = (x, y, t, anchor = 'start', size = 13, weight = 400) => { body += `<text x="${x.toFixed(1)}" y="${y.toFixed(1)}" text-anchor="${anchor}" font-size="${size}" font-weight="${weight}">${esc(t)}</text>`; };
175
+ body += `<line x1="${X(-W / 2)}" y1="${Y(-H / 2) + 46}" x2="${X(W / 2)}" y2="${Y(-H / 2) + 46}" stroke="#666"/>`; text(X(0), Y(-H / 2) + 64, `${f2(W)}`, 'middle');
176
+ body += `<line x1="${X(-W / 2) - 46}" y1="${Y(H / 2)}" x2="${X(-W / 2) - 46}" y2="${Y(-H / 2)}" stroke="#666"/>`; text(X(-W / 2) - 52, Y(0) + 4, `${f2(H)}`, 'end');
177
+ for (const [face, list] of Object.entries(feat.faces)) for (const s of list) {
178
+ const n = FACES[face].n, x = X(s.at[0]) + n[0] * 22, y = Y(s.at[1]) - n[1] * 22 + 5;
179
+ body += `<circle cx="${x}" cy="${y - 5}" r="11" fill="#fff" stroke="#b0412e" stroke-width="1.4"/>`; text(x, y, s.kind === 'slot' ? s.letter : '~', 'middle', 13, 600);
180
+ }
181
+ bores.forEach((b, i) => { body += `<circle cx="${X(b.at[0])}" cy="${Y(b.at[1])}" r="${(b.diameter / 2) * S + 4}" fill="none" stroke="#2e6db0" stroke-width="1.4" stroke-dasharray="4 3"/>`; text(X(b.at[0]) + (b.diameter / 2) * S + 8, Y(b.at[1]) - (b.diameter / 2) * S - 4, `${i + 1}`, 'start', 12, 600); });
182
+ let y = Y(-H / 2) + 104; const line = (t, weight) => { text(40, y, t, 'start', 13, weight); y += 19; };
183
+ line('What was found (check each against the bar in hand):', 600);
184
+ for (const g of groups) line(`${g.letter} × ${g.count} on ${g.faces.join(', ')}: opening ${f2(g.opening)}, lip ${f2(g.lip)}, ${f2(g.cavityWidth)} under the lips, ${f2(g.cavityDepth)} deep${g.trackWidth ? `, V mouth ${f2(g.trackWidth)} at ${f2(g.trackAngle)}°` : ''}: ${g.family ? `${g.drafted ? 'no family fits, drafted as' : 'matches'} ${g.family}${g.drafted ? '' : ` (within ${f2(g.off)} mm)`}` : ''}`);
185
+ const grooves = Object.values(feat.faces).flat().filter((s) => s.kind === 'groove');
186
+ for (const g of grooves) line(`~ ${g.face}: an opening ${f2(g.mouth)} wide and ${f2(g.depth)} deep with no room under lips: not a slot for a nut (what is inside it is in the outline only)`);
187
+ bores.forEach((b, i) => line(`${i + 1} bore Ø${f2(b.diameter)} at ${f2(b.at[0])}, ${f2(b.at[1])}`));
188
+ if (feat.hollows.length) line(`${feat.hollows.length} other hollow${feat.hollows.length === 1 ? '' : 's'} (${feat.hollows.map((h) => `${f2(h.width)} × ${f2(h.height)}`).join(', ')}): kept in the outline, not in the rules`);
189
+ line(`area of the section ${f2(feat.area)} mm²`);
190
+ const h = y + 20;
191
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${Math.max(w, 1080).toFixed(0)}" height="${h.toFixed(0)}" viewBox="0 0 ${Math.max(w, 1080).toFixed(0)} ${h.toFixed(0)}" font-family="-apple-system, Helvetica, Arial, sans-serif" fill="#1a1a1a"><rect width="100%" height="100%" fill="#fff"/>
192
+ <text x="40" y="40" font-size="20">${esc(name)}: measured from ${esc(path.basename(file))}</text><text x="40" y="64" font-size="12" fill="#555">all in mm · source: ${esc(source)}${licence ? ` · licence: ${esc(licence)}` : ''} · the outline stays in this workspace</text>${body}</svg>`;
193
+ }
194
+
195
+ // ---------- the command ----------
196
+ /**
197
+ * measureProfile(file, { profile, source, licence, along, tol, force, pictures }): the report, the outline and the
198
+ * draft sets written to the workspace's rules/, and the drawing in .preview/measure/.
199
+ */
200
+ export async function measureProfile(file, o = {}) {
201
+ const name = String(o.profile);
202
+ if (!/^[a-z][a-z0-9_-]*$/.test(name)) throw new Error('--profile <name>: lower case, digits, - and _ (a rule set name, like profile-2020-mine)');
203
+ if (!fs.existsSync(file)) throw new Error(`no file ${file}`);
204
+ const ext = path.extname(file).toLowerCase(), tol = o.tol == null ? 0.1 : Number(o.tol);
205
+ if (!(tol > 0)) throw new Error(`--tol is how close a slot must be to a known family, in mm, above 0 (got ${o.tol})`);
206
+ if (!['.stl', '.3mf', '.dxf'].includes(ext)) throw new Error(`${path.basename(file)}: a profile is measured from an STL or 3MF model of the beam, or a DXF of its section (not ${ext || 'a file with no extension'})`);
207
+ const rulesDir = path.join(WS, 'rules'), to = path.join(rulesDir, `${name}.json`), outlineTo = path.join(rulesDir, 'outlines', `${name}.json`);
208
+ // the kit holds no maker's outline: this writes to a workspace, never into the published rules
209
+ const kit = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/rules/vocabulary.json')));
210
+ if (fs.realpathSync(fs.existsSync(rulesDir) ? rulesDir : WS).startsWith(fs.realpathSync(kit))) throw new Error('this is the kit\'s own rules folder: a measured outline goes into a workspace of your own, never into the kit');
211
+ if ((fs.existsSync(to) || fs.existsSync(outlineTo)) && !o.force) throw new Error(`rules/${name}.json or its outline already exists (--force to replace them)`);
212
+ const read = ext === '.dxf' ? { ...readDxf(fs.readFileSync(file, 'utf8')), says: 'the DXF\'s outline' } : meshSection(file, o.along);
213
+ const { loops, turned } = tidy(read.loops), feat = findFeatures(loops), source = o.source || path.basename(file), stamp = today();
214
+ console.log(`${path.basename(file)}: ${read.says}${turned ? ', turned a quarter turn to lie flat' : ''}`);
215
+ for (const n of read.notes || []) console.log(` ${n}`);
216
+ if (o.licence && limitingLicence(o.licence)) console.log(` ! licence "${o.licence}" limits reuse: measurements are facts, but the outline is the model's shape. Keep it in this workspace, and don't publish it or build it into a design under another licence`);
217
+ console.log(` ${f2(feat.width)} × ${f2(feat.height)} mm, ${loops.length - 1} hole${loops.length === 2 ? '' : 's'}, area ${f2(feat.area)} mm²`);
218
+ // ---- slots: alike ones grouped, each group matched to a family or drafted as a new one ----
219
+ const sets = allSets(), families = Object.fromEntries([...sets].map(([n, f]) => [n, JSON.parse(fs.readFileSync(f, 'utf8'))]).filter(([, s]) => s.part === 'slot'));
220
+ const groups = [], found = Object.values(feat.faces).flat().filter((s) => s.kind === 'slot');
221
+ for (const s of found) {
222
+ let g = groups.find((x) => DIMS.every(([, k]) => Math.abs(x[k] - s[k]) <= tol));
223
+ if (!g) { g = { ...s, count: 0, faces: [], letter: String.fromCharCode(65 + groups.length) }; groups.push(g); }
224
+ g.count++; if (!g.faces.includes(s.face)) g.faces.push(s.face); s.letter = g.letter;
225
+ }
226
+ const extra = { kind: 'derived', source, ...(o.licence ? { licence: o.licence } : {}), checked: stamp }, written = [];
227
+ const rule = (value, unit, says) => ({ value: typeof value === 'number' ? r2(value) : value, ...(unit != null ? { unit } : {}), rule: says, ...extra });
228
+ const base = name.replace(/^profile-/, '');
229
+ for (const g of groups) {
230
+ const near = nearestFamily(g, families);
231
+ if (near && near.off <= tol) { g.family = near.name; g.off = near.off; continue; }
232
+ g.family = `slot-${Math.max(1, Math.round(g.opening))}-${base}${groups.filter((x) => x.drafted).length ? `-${String.fromCharCode(98 + groups.filter((x) => x.drafted).length - 1)}` : ''}`; g.drafted = true; g.near = near;
233
+ const rules = { opening: rule(g.opening, 'mm', 'Between the lips, at their narrowest: measured off the model\'s section'), lip_thickness: rule(g.lip, 'mm', 'From the face to the underside of the lip at its tip: measured off the model\'s section'), cavity_width: rule(g.cavityWidth, 'mm', 'Width under the lips, at its widest: measured off the model\'s section'), cavity_depth: rule(g.cavityDepth, 'mm', 'From the face to the deepest point of the slot: measured off the model\'s section') };
234
+ if (g.flankAngle) { rules.floor_width = rule(g.floorWidth, 'mm', 'Width of the slot at its floor: measured off the model\'s section'); rules.flank_angle = rule(g.flankAngle, 'deg', 'How steeply the walls close in to the floor, from the face\'s plane: worked out from where they leave the full width'); }
235
+ if (g.trackWidth) { rules.track_width = rule(g.trackWidth, 'mm', 'Width of the V mouth at the face: measured off the model\'s section'); rules.track_angle = rule(g.trackAngle, 'deg', 'The angle between the V mouth\'s two sides: worked out from its width and depth'); }
236
+ rules.nut_family = rule(g.family, null, `No known slot family is within ${tol} mm of this one${near ? ` (the nearest, ${near.name}, is ${f2(near.off)} mm off in its worst figure)` : ''}: name the family whose nuts it takes once you know`);
237
+ const set = { _doc: `A draft slot family, measured from ${path.basename(file)} by cad measure --profile ${name}. kind derived: read off someone else's model, so check it against the real thing.${o.licence ? ` The model's licence: ${o.licence}.` : ''}`, name: g.family, part: 'slot', rules };
238
+ slotModel(set); // (held to sense before it is written)
239
+ written.push([path.join(rulesDir, `${g.family}.json`), set]);
240
+ }
241
+ // ---- the profile's own rules ----
242
+ const count = (f) => feat.faces[f].filter((s) => s.kind === 'slot').length, across = Math.max(1, count('top'), count('bottom')), up = Math.max(1, count('front'), count('back'));
243
+ const main = groups.slice().sort((a, b) => b.count - a.count)[0], family = !groups.length ? 'custom' : groups.some((g) => g.trackWidth) ? 'v-slot' : 't-slot';
244
+ const rules = { family: rule(family, null, family === 'custom' ? 'No slot for a nut was found in the section: it is taken as an outline of its own' : family === 'v-slot' ? 'Slots with a V mouth were found: a rail for wheels' : 'Slots with room under their lips were found: a profile for T-nuts') };
245
+ if (groups.length) { const pitch = Math.min(feat.width / across, feat.height / up); rules.series = rule(pitch, 'mm', `The size of one cell: ${across} slot${across === 1 ? '' : 's'} along the wide faces and ${up} up the sides`); rules.cells_across = rule(across, '', 'Slots found side by side on a wide face'); rules.cells_up = rule(up, '', 'Slots found one above the other on a side'); }
246
+ rules.width = rule(feat.width, 'mm', 'Across the section\'s envelope, measured off the model'); rules.height = rule(feat.height, 'mm', 'Up the section\'s envelope, measured off the model');
247
+ if (main) {
248
+ rules.slot = rule(main.family, null, `The slot found on ${main.faces.join(', ')} (${main.count} in all): ${main.drafted ? 'drafted as a family of its own' : `it matches ${main.family} within ${f2(main.off)} mm`}`);
249
+ for (const f of Object.keys(FACES)) { const list = feat.faces[f].filter((s) => s.kind === 'slot'), n = f === 'top' || f === 'bottom' ? across : up, names = list.length === n ? list.map((s) => groups.find((g) => g.letter === s.letter).family) : null; const written2 = !list.length ? 'closed' : names && names.every((x) => x === main.family) ? null : names ? names.join(', ') : 'closed'; if (written2) rules[`slot_${f}`] = rule(written2, null, !list.length ? `No slot was found on the ${f} face` : names ? `The ${f} face's slots, as found` : `The ${f} face has ${list.length} slot${list.length === 1 ? '' : 's'} where its cells would give ${n}: left closed here, see the outline`); }
250
+ }
251
+ // bores: the round holes at the middles of the cells are the profile's bores; others are told, and stay in the outline
252
+ const cells = Array.from({ length: across * up }, (_, k) => [((k % across) - (across - 1) / 2) * (feat.width / across), (Math.floor(k / across) - (up - 1) / 2) * (feat.height / up)]);
253
+ const central = feat.bores.filter((b) => cells.some((c) => Math.hypot(c[0] - b.at[0], c[1] - b.at[1]) < 0.15)), others = feat.bores.filter((b) => !central.includes(b));
254
+ const bore = central.length ? central : groups.length ? [] : [];
255
+ if (bore.length) { rules.bore_diameter = rule(bore.reduce((s, b) => s + b.diameter, 0) / bore.length, 'mm', `The round hole at the middle of ${bore.length === 1 ? 'the section' : `each of ${bore.length} cells`}, measured off the model. Name the thread it taps to (bore_thread) once you know`); if (bore.length !== cells.length) rules.bore_at = rule(bore.map((b) => `${b.at[0]},${b.at[1]}`).join('; '), null, 'Where the bores are: not every cell has one'); }
256
+ const doc = `A draft profile, measured from ${path.basename(file)} by cad measure --profile (${read.says}). kind derived: read off someone else's model, so check each figure against the bar in hand, name its maker and series, and add what a model cannot say: the alloy, a material set (for its mass), the thread its bore taps to and the lengths it is sold in. Its outline is rules/outlines/${name}.json, which the check and the drawing use in place of a drawn one${others.length || feat.hollows.length ? `; it also holds ${[others.length ? `${others.length} round hole${others.length === 1 ? '' : 's'} off the cells' middles` : '', feat.hollows.length ? `${feat.hollows.length} hollow${feat.hollows.length === 1 ? '' : 's'}` : ''].filter(Boolean).join(' and ')} that the rules do not name` : ''}.${o.licence ? ` The model's licence: ${o.licence}.` : ''} The outline is the model's shape: it stays in this workspace.`;
257
+ written.push([to, { _doc: doc, name, part: 'profile', rules }]);
258
+ fs.mkdirSync(path.dirname(outlineTo), { recursive: true });
259
+ fs.writeFileSync(outlineTo, `${JSON.stringify({ _doc: `The section of ${path.basename(file)}, measured by cad measure --profile. It is the model's shape: keep it in this workspace.`, name, unit: 'mm', source, licence: o.licence || 'not given: find the model\'s terms before sharing this', checked: stamp, loops })}\n`);
260
+ for (const [f, set] of written) fs.writeFileSync(f, `${JSON.stringify(set, null, 2)}\n`);
261
+ // ---- the report ----
262
+ for (const g of groups) console.log(` slot ${g.letter} × ${g.count} (${g.faces.join(', ')}): opening ${f2(g.opening)}, lip ${f2(g.lip)}, ${f2(g.cavityWidth)} under the lips, ${f2(g.cavityDepth)} deep${g.flankAngle ? `, floor ${f2(g.floorWidth)}` : ''}${g.trackWidth ? `, V mouth ${f2(g.trackWidth)} at ${f2(g.trackAngle)}°` : ''}\n ${g.drafted ? `no slot family within ${tol} mm${g.near ? ` (nearest ${g.near.name}, ${f2(g.near.off)} off)` : ''}: drafted as ${g.family}` : `matches ${g.family} within ${f2(g.off)} mm`}`);
263
+ const grooves = Object.values(feat.faces).flat().filter((s) => s.kind === 'groove');
264
+ for (const g of grooves) console.log(g.depth > 2 && g.mouth > 0.3 * Math.min(feat.width, feat.height) ? ` an open channel ${f2(g.mouth)} wide and ${f2(g.depth)} deep in the ${g.face} face (a C section): whatever slots are inside it are in the outline, not in the rules. Give the set cells_absent for them (see profile-4080-openbuilds-cbeam)` : ` a groove ${f2(g.mouth)} wide and ${f2(g.depth)} deep in the ${g.face} face, with no room under lips: not a slot for a nut`);
265
+ if (!groups.length) console.log(' no slot for a nut found: written as a custom profile (its outline is all of it)');
266
+ if (bore.length) console.log(` ${bore.length} bore${bore.length === 1 ? '' : 's'} Ø${f2(rules.bore_diameter.value)} at the cells' middles`);
267
+ if (others.length) console.log(` ${others.length} other round hole${others.length === 1 ? '' : 's'}: ${others.map((b) => `Ø${f2(b.diameter)} at ${f2(b.at[0])}, ${f2(b.at[1])}`).join('; ')} (in the outline, not in the rules)`);
268
+ if (feat.hollows.length) console.log(` ${feat.hollows.length} hollow${feat.hollows.length === 1 ? '' : 's'}: ${feat.hollows.map((h) => `${f2(h.width)} × ${f2(h.height)}`).join(', ')} (in the outline, not in the rules)`);
269
+ const rel = (f) => path.relative(process.cwd(), f).split(path.sep).join('/');
270
+ console.log(`\n draft profile: ${rel(to)} (${Object.keys(rules).length} values, kind derived)\n outline: ${rel(outlineTo)} (${loops.length} loops${o.licence ? '' : '; no --licence given: say what terms the model came under'})`);
271
+ for (const [f] of written.slice(0, -1)) console.log(` draft slot: ${rel(f)}`);
272
+ const svg = drawingSvg({ name, file, loops, feat, groups, bores: feat.bores, source, licence: o.licence }), svgTo = paths.preview('measure', `${name}-profile.svg`);
273
+ fs.mkdirSync(path.dirname(svgTo), { recursive: true }); fs.writeFileSync(svgTo, svg);
274
+ console.log(` drawing: ${rel(svgTo)}`);
275
+ if (o.pictures !== false) { const png = paths.preview('measure', `${name}-profile.png`); const size = svg.match(/width="(\d+)" height="(\d+)"/); await picture(`<!doctype html><html><head><meta charset="utf-8"></head><body style="margin:0">${svg}</body></html>`, png, { width: Number(size[1]), height: Number(size[2]) }); console.log(` ${rel(png)}`); }
276
+ console.log(`\n next: look at the drawing, then npx cad rules check ${name}, and npx cad rules draw ${name}`);
277
+ return { name, loops, features: feat, groups, files: written.map(([f]) => f).concat(outlineTo, svgTo) };
278
+ }
@@ -1,11 +1,11 @@
1
- // The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears, @rulecad/motors and files of
1
+ // The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears, @rulecad/motors, @rulecad/frames, @rulecad/fixings and files of
2
2
  // its own project, nothing else (no node: modules: no files, network or processes). The tool's own modules are free.
3
3
  import { builtinModules } from 'node:module';
4
4
 
5
5
  let project = '';
6
6
  export async function initialize(data) { project = data?.project || ''; }
7
7
 
8
- const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors'];
8
+ const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors', '@rulecad/frames', '@rulecad/fixings'];
9
9
  const deny = (spec, why) => Object.assign(new Error(`designs can't import "${spec}": ${why}`), { code: 'design.sandbox' });
10
10
 
11
11
  // The same check, for in-thread hooks (synchronous) and worker hooks (async)
@@ -6,6 +6,8 @@ import * as shapes from '@rulecad/shapes';
6
6
  import * as flexures from '@rulecad/flexures';
7
7
  import * as gears from '@rulecad/gears';
8
8
  import * as motors from '@rulecad/motors';
9
+ import { designFrames } from './frames.mjs';
10
+ import { designFixings } from './fixings.mjs';
9
11
  import { named, faces, unpack, watch } from './parts.mjs';
10
12
  import { lineOf } from './errors.mjs';
11
13
 
@@ -18,7 +20,7 @@ for (const k of ['getBuiltinModule', 'binding', '_linkedBinding', 'dlopen', 'kil
18
20
  }
19
21
  const chunks = [];
20
22
  for await (const c of process.stdin) chunks.push(c);
21
- const { js, values, meta, engine, optional, stages } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
23
+ const { js, values, meta, engine, optional, stages, bound } = JSON.parse(Buffer.concat(chunks).toString('utf8')), context = bound?.fixings;
22
24
  // A lamina's slow stages: read from the tool's cache (the workspace is readable), and what this run makes handed back
23
25
  // with the parts for the tool to write (this process can't)
24
26
  const kept = {}; // (what this run made of them)
@@ -29,10 +31,11 @@ console.log = console.info = console.debug = (...a) => console.error(...a);
29
31
  try {
30
32
  const mod = await import(js);
31
33
  if (typeof mod.main !== 'function') throw Object.assign(new Error('the design has no exported main(v)'), { code: 'design.main' });
32
- const { v, read } = watch(values, { shapes, flexures, gears, motors, ops: await shapes.ops(engine || 'jscad') }, optional);
34
+ const ops = await shapes.ops(engine || 'jscad'), df = designFixings({ ...(context || {}), ops }); // (v.fixings: bound to the project, as the build's own is)
35
+ const { v, read } = watch(values, { shapes, flexures, gears, motors, frames: designFrames(bound?.frames), fixings: df.fixings, ops }, optional);
33
36
  const { shapes: made, mechanism } = unpack(await mod.main(v));
34
37
  const parts = named(made, meta).map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) }));
35
- done({ parts, read: [...read], ...(mechanism ? { mechanism } : {}), ...(Object.keys(kept).length ? { stages: kept } : {}) });
38
+ done({ parts, read: [...read], ...(mechanism ? { mechanism } : {}), ...(df.used() ? { fixings: df.found() } : {}), ...(Object.keys(kept).length ? { stages: kept } : {}) });
36
39
  } catch (e) {
37
40
  const line = lineOf(e, js);
38
41
  done({ error: { message: e?.message || String(e), ...(line ? { line } : {}), ...(e?.name === 'SyntaxError' ? { syntax: true } : {}), code: e?.code && typeof e.code === 'string' && !/^ERR_/.test(e.code) ? e.code : e?.code === 'ERR_ACCESS_DENIED' ? 'design.sandbox' : 'design.run', ...(e?.code === 'ERR_ACCESS_DENIED' && e.resource ? { resource: e.resource } : {}) } });
package/lib/sandbox.mjs CHANGED
@@ -2,7 +2,8 @@
2
2
  // promises, whatever the design does: it can't write or delete files, start programs or workers, or load addons, and
3
3
  // it reads only the workspace and the packages designs use. That much is Node's own boundary.
4
4
  // On top of it, to keep a design to making shapes: an import hook (sandbox-hooks.mjs) lets it import only
5
- // @jscad/modeling, @rulecad/shapes, @rulecad/flexures and files in its own project (no node: modules); the runner
5
+ // @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears, @rulecad/motors, @rulecad/frames, @rulecad/fixings and
6
+ // files in its own project (no node: modules); the runner
6
7
  // takes away fetch and its kin and process's own ways to Node's modules; and it is started with none of this
7
8
  // process's environment (no tokens). Those close the ordinary roads to the network, not every one: before Node 25
8
9
  // the permission model doesn't cover the network, so a design written to get round them might still reach it, and
@@ -30,7 +31,8 @@ const inThread = typeof nodeModule.registerHooks === 'function'; // import hooks
30
31
  // (a workspace's "sandbox": false counts only once the user has trusted it: cad trust)
31
32
  export const sandboxed = () => !!flag && process.env.CAD_TRUST !== '1' && !(config.sandbox === false && trusted());
32
33
 
33
- // What the sandbox may read: the workspace, and the packages designs and the runner load (wherever npm put them)
34
+ // What the sandbox may read: the workspace, and the packages designs and the runner load (wherever npm put them), and
35
+ // what those load in turn (@rulecad/frames sizes a beam's operations through @rulecad/fixings)
34
36
  function readable() {
35
37
  const real = (p) => { try { return fs.realpathSync(p); } catch { return null; } };
36
38
  const pkgDir = (name, from) => { // the package's folder: from its entry up to its package.json (exports may hide that file)
@@ -40,7 +42,7 @@ function readable() {
40
42
  // Every node_modules above the workspace and the tool (package lookups read their links), and where links lead
41
43
  const up = (dir) => { const out = []; for (let d = dir; ; d = path.dirname(d)) { out.push(path.join(d, 'node_modules')); if (path.dirname(d) === d) return out; } };
42
44
  const dirs = [WS, TOOL, ...[...up(WS), ...up(TOOL)].filter((d) => fs.existsSync(d)),
43
- ...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors', '@rulecad/rules/x1c.json', '@rulecad/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
45
+ ...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors', '@rulecad/frames', '@rulecad/fixings', '@rulecad/rules/x1c.json', '@rulecad/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
44
46
  return [...new Set(dirs.filter(Boolean).flatMap((d) => [d, real(d)]).filter(Boolean))];
45
47
  }
46
48
 
@@ -61,8 +63,9 @@ function refused(e) {
61
63
  * @param {{ js: string }} d the design @param {object} values @param {object} meta the .json's parts @param {'jscad' | 'manifold'} [engine] v.ops's booleans
62
64
  * @param {string[]} [optional] names main may read that aren't among the values (the display's own inputs)
63
65
  * @param {{ salt: string, get: (k: string) => string | undefined, put: (k: string, text: string) => void } | null} [stages] where a lamina's slow stages are kept: the child reads them from the cache (it may read the workspace) and hands back what it made, which is written here
66
+ * @param {{ frames?: object, fixings?: { sets?: object, printer?: object, material?: string | null } | null }} [bound] what the design's helpers are bound to: frames, the workspace's profile sets (lib/frames.mjs framesContext); fixings, what v.fixings is bound to (design.mjs fixingsContext), whose calls come back as fixings
64
67
  */
65
- export function runSandboxed(d, values, meta, engine = 'jscad', optional = [], stages = null) {
68
+ export function runSandboxed(d, values, meta, engine = 'jscad', optional = [], stages = null, bound = {}) {
66
69
  const here = path.dirname(fileURLToPath(import.meta.url));
67
70
  const args = [flag, ...readable().map((p) => `--allow-fs-read=${p}`), ...(inThread ? [] : ['--allow-worker']), '--import', pathToFileURL(path.join(here, 'sandbox-preload.mjs')).href, path.join(here, 'sandbox-run.mjs')];
68
71
  // (real paths: Node names an imported file by where it really is, so a workspace reached through a link still matches)
@@ -83,8 +86,8 @@ export function runSandboxed(d, values, meta, engine = 'jscad', optional = [], s
83
86
  if (err.length) process.stderr.write(Buffer.concat(err)); // what the design printed
84
87
  if (r.error) return reject(located(Object.assign(new Error(refused(r.error)), { code: r.error.code, ...(r.error.line ? { line: r.error.line } : {}), ...(r.error.syntax ? { name: 'SyntaxError' } : {}) }), d.js, r.error.code || 'design.run'));
85
88
  if (stages) for (const [k, text] of Object.entries(r.stages || {})) stages.put(k, text);
86
- resolve({ parts: r.parts.map(({ solid, ...p }) => ({ ...p, geometry: fromFaces(solid) })), read: new Set(r.read), mechanism: r.mechanism || null });
89
+ resolve({ parts: r.parts.map(({ solid, ...p }) => ({ ...p, geometry: fromFaces(solid) })), read: new Set(r.read), mechanism: r.mechanism || null, fixings: r.fixings || null });
87
90
  });
88
- child.stdin.end(JSON.stringify({ js: `${pathToFileURL(js).href}?t=${fs.statSync(js).mtimeMs}`, values, meta, engine, optional, ...(stages ? { stages: { dir: stagesDir, salt: stages.salt } } : {}) }));
91
+ child.stdin.end(JSON.stringify({ js: `${pathToFileURL(js).href}?t=${fs.statSync(js).mtimeMs}`, values, meta, engine, optional, ...(stages ? { stages: { dir: stagesDir, salt: stages.salt } } : {}), bound }));
89
92
  });
90
93
  }
package/lib/schema.mjs CHANGED
@@ -8,7 +8,7 @@ import { near } from './errors.mjs';
8
8
 
9
9
  const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'schemas');
10
10
  const cache = new Map();
11
- /** A schema by name: object, assembly, rules, layout or problem. @param {'object' | 'assembly' | 'rules' | 'layout' | 'problem'} name */
11
+ /** A schema by name: object, assembly, rules, layout, problem or outline. @param {'object' | 'assembly' | 'rules' | 'layout' | 'problem' | 'outline'} name */
12
12
  export function schema(name) {
13
13
  if (!cache.has(name)) cache.set(name, JSON.parse(fs.readFileSync(path.join(DIR, `${name}.schema.json`), 'utf8')));
14
14
  return cache.get(name);
package/lib/sheet.mjs CHANGED
@@ -7,7 +7,9 @@ import path from 'node:path';
7
7
  import zlib from 'node:zlib';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { checkRuleSet } from '@rulecad/variables';
10
+ import { profileModel, slotModel, slotPath, outline, section, profileFindings, slotNutModel, nutFit } from '@rulecad/frames';
10
11
  import { RULE_DIRS } from './workspace.mjs';
12
+ import { schema, validate } from './schema.mjs';
11
13
 
12
14
  const vocabularyFile = fileURLToPath(import.meta.resolve('@rulecad/rules/vocabulary.json'));
13
15
  const readSet = (f) => JSON.parse(fs.readFileSync(f, 'utf8'));
@@ -25,10 +27,44 @@ function fileOf(name) {
25
27
  return file;
26
28
  }
27
29
 
28
- /** Every named set checked (or all of them): [{ name, file, findings }] */
30
+ // What a profile's model reads beside its own set: any other set by name (its slot family, a thread, its material),
31
+ // the workspace's first, and a measured outline in outlines/<name>.json beside the set, held to its schema
32
+ function given(name, file, all = allSets()) {
33
+ const load = (n) => (all.has(n) ? readSet(all.get(n)) : undefined), at = path.join(path.dirname(file), 'outlines', `${name}.json`), problems = [];
34
+ let measured;
35
+ if (fs.existsSync(at)) {
36
+ try { measured = readSet(at); problems.push(...validate(measured, schema('outline')).map((x) => `outlines/${name}.json: ${x.path}: ${x.message}`)); } catch (e) { problems.push(`outlines/${name}.json isn't JSON: ${e.message}`); }
37
+ if (problems.length) measured = undefined;
38
+ }
39
+ return { load, ...(measured ? { outline: measured } : {}), problems };
40
+ }
41
+ const own = (e) => e.message.replace(/^\w+: /, ''); // a refusal without the function's name: the set's name follows
42
+
43
+ // A profile, a slot or a slot nut held to sense as well as to the vocabulary: what @rulecad/frames finds in its model
44
+ function partFindings(set, name, file, all) {
45
+ const out = [], say = (level, code, text, extra = {}) => out.push({ level, code, text, ...extra }), g = given(name, file, all);
46
+ for (const p of g.problems) say('fail', 'outline.schema', p);
47
+ try {
48
+ if (set.part === 'profile') out.push(...profileFindings(profileModel(set, {}, g)));
49
+ if (set.part === 'slot') slotModel(set, {}, g);
50
+ if (set.part === 'slot_nut') {
51
+ const r = (k) => set.rules[k]?.value, slot = g.load(String(r('slot')));
52
+ if (slot?.part !== 'slot') say('warn', 'slot_nut.slot', `slot names the slot family it is made for, and there is no slot set "${r('slot')}": its fit is not checked`, { rule: 'slot' });
53
+ else out.push(...nutFit(slotNutModel(set, {}, g), slotModel(slot, {}, g), g));
54
+ if (![...all.values()].some((f) => { const t = readSet(f); return t.part === 'thread' && (t.name === r('thread') || t.rules.thread?.value === r('thread')); })) say('warn', 'slot_nut.thread', `thread ${JSON.stringify(r('thread'))} is no thread set here (M5, or a set's name)`, { rule: 'thread' });
55
+ }
56
+ } catch (e) { say('fail', `${set.part}.model`, own(e)); }
57
+ return out;
58
+ }
59
+
60
+ /** Every named set checked (or all of them): [{ name, file, findings }]. A finding's level is fail, warn or info */
29
61
  export function checkSets(names = []) {
30
62
  const v = vocabulary(), all = allSets();
31
- return (names.length ? names.map((n) => [n, fileOf(n)]) : [...all]).map(([name, file]) => ({ name, file, findings: checkRuleSet(readSet(file), v) }));
63
+ return (names.length ? names.map((n) => [n, fileOf(n)]) : [...all]).map(([name, file]) => {
64
+ const set = readSet(file), findings = checkRuleSet(set, v);
65
+ if (!findings.length && ['profile', 'slot', 'slot_nut'].includes(set.part)) findings.push(...partFindings(set, name, file, all));
66
+ return { name, file, findings };
67
+ });
32
68
  }
33
69
 
34
70
  // ---------- a dimension drawing ----------
@@ -36,7 +72,7 @@ const fig = (x) => String(+Number(x).toFixed(2));
36
72
  const INK = '#1a1a1a', THIN = '#666', FILL = '#eceae4', METAL = '#c4c8cc';
37
73
 
38
74
  /** @param {string} name the rule set's name @returns {string} an SVG drawing of what it says the part mounts by */
39
- export function drawSet(name) { return drawing(readSet(fileOf(name)), vocabulary()); }
75
+ export function drawSet(name) { const file = fileOf(name); return drawing(readSet(file), vocabulary(), given(name, file)); }
40
76
 
41
77
  // The drawing's marks, in sheet units: each adds to out, and span is a dimension with its extension lines, ticks and figure
42
78
  function pen() {
@@ -257,7 +293,97 @@ function threadDrawing(set) {
257
293
  return sheet(set, pens, Math.max(W, 620), yNotes + notes.length * 17 - 50);
258
294
  }
259
295
 
260
- export function drawing(set, vocab) {
296
+ // ---------- profiles, slots and slot nuts ----------
297
+ const pathOf = (loops, X, Y) => loops.map((l) => `M ${l.map(([x, y]) => `${fig(X(x))} ${fig(Y(y))}`).join(' L ')} Z`).join(' ');
298
+ const sig = (x, n = 4) => String(+Number(x).toPrecision(n));
299
+
300
+ // A profile's section to scale, with what a sheet's drawing dimensions (size, slot, bore, corner), and under it the
301
+ // sheet's section figures beside what the drawn outline comes to
302
+ function profileDrawing(set, g) {
303
+ const m = profileModel(set, {}, g), o = outline(m), s = section(m), W = m.width, H = m.height;
304
+ const S = Math.min(18, 380 / Math.max(W, H)), sheetW = Math.max(W * S + 330, 640), cx = 130 + (W * S) / 2, cy = 110 + (H * S) / 2, X = (x) => cx + x * S, Y = (y) => cy - y * S;
305
+ const pens = pen(), { out, line, text, span } = pens;
306
+ out.push(`<path d="${pathOf(o.loops, X, Y)}" fill="${METAL}" fill-rule="evenodd" stroke="${INK}" stroke-width="1.2" stroke-linejoin="round"/>`);
307
+ line(X(-W / 2) - 10, Y(0), X(W / 2) + 10, Y(0), THIN, 0.5, '8 3 2 3'); line(X(0), Y(H / 2) - 10, X(0), Y(-H / 2) + 10, THIN, 0.5, '8 3 2 3');
308
+ span(X(-W / 2), Y(-H / 2) + 6, X(W / 2), Y(-H / 2) + 6, fig(W), 22);
309
+ span(X(-W / 2) - 6, Y(H / 2), X(-W / 2) - 6, Y(-H / 2), fig(H), -22);
310
+ // the slot nearest the top right: its opening and cavity above, its lip and depth at the side
311
+ const face = ['top', 'back', 'bottom', 'front'].find((f) => m.faces[f].some((p) => p.slot)), notes = [];
312
+ if (face && !o.measured) {
313
+ const p = m.faces[face].filter((q) => q.slot).at(-1), sl = m.slots[p.slot], top = face === 'top' || face === 'bottom', sign = face === 'top' || face === 'back' ? 1 : -1;
314
+ if (top) {
315
+ const y0 = Y(p.at[1]) - sign * 6, d = -sign * 14;
316
+ span(X(p.at[0] - sl.mouth / 2), y0, X(p.at[0] + sl.mouth / 2), y0, fig(sl.mouth), d);
317
+ span(X(p.at[0] - sl.cavityWidth / 2), y0 - sign * 24, X(p.at[0] + sl.cavityWidth / 2), y0 - sign * 24, fig(sl.cavityWidth), d);
318
+ const x0 = X(W / 2) + 6;
319
+ span(x0, Y(p.at[1]), x0, Y(p.at[1] - sign * sl.lip), fig(sl.lip), 16);
320
+ span(x0 + 44, Y(p.at[1]), x0 + 44, Y(p.at[1] - sign * sl.cavityDepth), fig(sl.cavityDepth), 16);
321
+ } else {
322
+ const x0 = X(p.at[0]) + sign * 6, d = sign * 14;
323
+ span(x0, Y(p.at[1] + sl.mouth / 2), x0, Y(p.at[1] - sl.mouth / 2), fig(sl.mouth), d);
324
+ span(x0 + sign * 30, Y(p.at[1] + sl.cavityWidth / 2), x0 + sign * 30, Y(p.at[1] - sl.cavityWidth / 2), fig(sl.cavityWidth), d);
325
+ const y0 = Y(-H / 2) + 6;
326
+ span(X(p.at[0]), y0 + 40, X(p.at[0] - sign * sl.lip), y0 + 40, fig(sl.lip), 14);
327
+ span(X(p.at[0]), y0 + 70, X(p.at[0] - sign * sl.cavityDepth), y0 + 70, fig(sl.cavityDepth), 14);
328
+ }
329
+ const families = [...new Set(Object.values(m.faces).flat().map((q) => q.slot ?? 'closed'))];
330
+ notes.push(`slot: ${families.join(', ')}${families.length > 1 ? ` (${['top', 'bottom', 'front', 'back'].map((f) => `${f} ${m.faces[f].map((q) => q.slot ?? 'closed').join(' | ')}`).join('; ')})` : ''}: ${fig(sl.mouth)} wide, ${fig(sl.cavityWidth)} under lips ${fig(sl.lip)} thick, ${fig(sl.cavityDepth)} deep, floor ${fig(sl.floorWidth)}`);
331
+ }
332
+ if (o.measured) notes.push(`drawn from its outline: ${esc(o.source)}`);
333
+ const kinds = ['cell', 'given', 'corner'].map((w) => m.bores.filter((b) => b.where === w)).filter((l) => l.length);
334
+ for (const list of kinds) notes.push(`${list.length} × ${list[0].where === 'corner' ? 'corner hole' : 'bore'} Ø${fig(list[0].diameter)}${list[0].thread ? `, taps ${esc(list[0].thread)}${list[0].tapDrill ? ` (tap drill Ø${fig(list[0].tapDrill)})` : ''}` : ''}`);
335
+ if (m.bores.length) { const b = m.bores.find((q) => q.where !== 'corner') ?? m.bores[0], a = X(b.at[0]) + (b.diameter / 2) * S * 0.7, c = Y(b.at[1]) + (b.diameter / 2) * S * 0.7; line(a, c, a + 26, c + 26, THIN, 0.8); text(a + 30, c + 34, `Ø${fig(b.diameter)}`, 'start'); }
336
+ if (m.cornerRadius) text(X(W / 2) + 8, Y(H / 2) - 8, `R${fig(m.cornerRadius)}`, 'start', 11);
337
+ if (m.wall) notes.push(`wall ${fig(m.wall)}`);
338
+ if (m.hollows.length) notes.push(`${m.hollows.length} × corner hollow ${fig(m.hollows[0].width)} square`);
339
+ if (m.chambers.length) notes.push(`${m.chambers.length} × hollow between cells, ${fig(m.chambers[0].width)} wide`);
340
+ notes.push(`${m.family}${m.cells[0] * m.cells[1] > 1 ? `, ${m.cells[0]} × ${m.cells[1]} cells of ${fig(m.pitch[0])}${m.absent?.length ? ` with ${m.absent.length} not there` : ''}` : ''}${m.material ? `, ${m.material.alloy ? `${esc(m.material.alloy)} (${m.material.name})` : m.material.name}` : ''}`);
341
+ if (m.supply.lengths.length || m.supply.cutMax) notes.push([m.supply.lengths.length ? `sold as ${m.supply.lengths.map(fig).join(', ')}` : '', m.supply.cutMax ? `cut ${fig(m.supply.cutMin ?? 0)} to ${fig(m.supply.cutMax)}${m.supply.cutTolerance != null ? ` ±${fig(m.supply.cutTolerance)}` : ''}` : '', m.supply.straightness != null ? `straight within ${fig(m.supply.straightness)} mm/m` : '', m.supply.twist != null ? `twist within ${fig(m.supply.twist)}°/m` : ''].filter(Boolean).join('; '));
342
+ // the table: what the sheet says, what the outline comes to
343
+ const rows = [['area, mm²', 'area', s.area], ['second moment about x, mm⁴', 'inertiaX', s.inertiaX], ['second moment about y, mm⁴', 'inertiaY', s.inertiaY], ['torsion constant, mm⁴', 'torsion', s.torsion], ['mass, kg/m', 'massPerMetre', s.massPerMetre]];
344
+ const ty = Y(-H / 2) + 120, tx = 40, col = [0, 230, 330, 440];
345
+ ['', 'sheet', o.measured ? 'measured' : 'drawn', 'difference'].forEach((t, i) => text(tx + col[i], ty, t, i ? 'end' : 'start', 11));
346
+ line(tx, ty + 6, tx + 450, ty + 6, THIN, 0.6);
347
+ rows.forEach(([label, k, got], i) => { const y = ty + 24 + i * 18, c = s.sheet[k]; text(tx, y, label, 'start', 11); text(tx + col[1], y, m.sheet[k] != null ? sig(m.sheet[k]) : 'not given', 'end', 11); text(tx + col[2], y, got != null ? sig(got) : 'no material', 'end', 11); text(tx + col[3], y, c ? `${c.difference >= 0 ? '+' : ''}${(c.difference * 100).toFixed(1)}%` : '', 'end', 11); });
348
+ const ny = ty + 24 + rows.length * 18 + 14;
349
+ notes.forEach((t, i) => text(tx, ny + i * 17, t, 'start', 11));
350
+ return sheet(set, pens, sheetW, ny + notes.length * 17 - 44);
351
+ }
352
+
353
+ // A slot cut into a block of metal, every figure of its family dimensioned
354
+ function slotDrawing(set, g) {
355
+ const sl = slotModel(set, {}, g), block = sl.cavityWidth + 8, deep = sl.cavityDepth + 4, S = Math.min(30, 380 / block), W = block * S + 300, x0 = 110 + (block * S) / 2, y0 = 110, X = (u) => x0 + u * S, Y = (v) => y0 + v * S;
356
+ const pens = pen(), { out, line, text, span } = pens, pts = [[-block / 2, 0], ...slotPath(sl), [block / 2, 0], [block / 2, deep], [-block / 2, deep]];
357
+ out.push(`<path d="M ${pts.map(([u, v]) => `${fig(X(u))} ${fig(Y(v))}`).join(' L ')} Z" fill="${METAL}" stroke="${INK}" stroke-width="1.2" stroke-linejoin="round"/>`);
358
+ line(X(0), Y(0) - 14, X(0), Y(deep) + 10, THIN, 0.5, '8 3 2 3');
359
+ span(X(-sl.opening / 2), Y(0) - 6, X(sl.opening / 2), Y(0) - 6, fig(sl.opening), -14);
360
+ if (sl.trackWidth) span(X(-sl.trackWidth / 2), Y(0) - 34, X(sl.trackWidth / 2), Y(0) - 34, `track ${fig(sl.trackWidth)}`, -14);
361
+ span(X(-sl.cavityWidth / 2), Y(deep) + 6, X(sl.cavityWidth / 2), Y(deep) + 6, fig(sl.cavityWidth), 16);
362
+ if (sl.floorWidth < sl.cavityWidth) span(X(-sl.floorWidth / 2), Y(deep) + 46, X(sl.floorWidth / 2), Y(deep) + 46, `floor ${fig(sl.floorWidth)}`, 16);
363
+ span(X(block / 2) + 6, Y(0), X(block / 2) + 6, Y(sl.lip), fig(sl.lip), 16);
364
+ span(X(block / 2) + 56, Y(0), X(block / 2) + 56, Y(sl.cavityDepth), fig(sl.cavityDepth), 16);
365
+ const notes = [`opening ${fig(sl.opening)}, lip ${fig(sl.lip)}${sl.lipAngle ? ` sloping ${fig(sl.lipAngle)}°` : ''}, ${fig(sl.cavityWidth)} wide under the lips, ${fig(sl.cavityDepth)} deep`, sl.floorWidth < sl.cavityWidth ? `walls straight to ${fig(sl.straight)} below the face, then flanks at ${fig(sl.flankAngle)}° to a floor of ${fig(sl.floorWidth)}` : 'straight walls', sl.trackWidth ? `V mouth ${fig(sl.trackWidth)} across at ${fig(sl.trackAngle)}°` : '', `takes the nuts of ${esc(sl.nutFamily)}`].filter(Boolean);
366
+ const ny = Y(deep) + 110; notes.forEach((t, i) => text(40, ny + i * 17, t, 'start', 11));
367
+ return sheet(set, pens, Math.max(W, 620), ny + notes.length * 17 - 44);
368
+ }
369
+
370
+ // A slot nut from above and from the side
371
+ function nutDrawing(set) {
372
+ const n = (k) => (typeof set.rules[k]?.value === 'number' ? set.rules[k].value : 0), says = (k) => String(set.rules[k]?.value ?? ''), L = n('length'), w = n('width'), h = n('height'), d = parseFloat(says('thread').replace(/^[^0-9]*/, '')) || 0;
373
+ const S = Math.min(24, 260 / Math.max(L, w, 1)), pens = pen(), { line, circle, rect, text, span } = pens, x0 = 90, y0 = 100;
374
+ rect(x0, y0, L * S, w * S, METAL); if (d) circle(x0 + (L * S) / 2, y0 + (w * S) / 2, (d / 2) * S, '#fff');
375
+ span(x0, y0 + w * S + 6, x0 + L * S, y0 + w * S + 6, fig(L), 16); span(x0 + L * S + 6, y0, x0 + L * S + 6, y0 + w * S, fig(w), 16);
376
+ const y1 = y0 + w * S + 80; rect(x0, y1, L * S, h * S, METAL); span(x0 + L * S + 6, y1, x0 + L * S + 6, y1 + h * S, fig(h), 16);
377
+ line(x0 + (L * S) / 2, y0 - 10, x0 + (L * S) / 2, y1 + h * S + 10, THIN, 0.5, '8 3 2 3');
378
+ const ny = y1 + h * S + 50; [`${esc(says('nut_kind'))} nut, ${esc(says('thread'))}, for ${esc(says('slot'))}`, says('nut_entry') === 'end' ? 'goes in from an open end of the slot' : 'goes in anywhere along the slot'].forEach((t, i) => text(40, ny + i * 17, t, 'start', 11));
379
+ return sheet(set, pens, Math.max(L * S + 260, 520), ny - 10);
380
+ }
381
+ const esc = (t) => String(t).replace(/&/g, '&amp;').replace(/</g, '&lt;');
382
+
383
+ export function drawing(set, vocab, g = { load: () => undefined, problems: [] }) {
384
+ if (set.part === 'profile') return profileDrawing(set, g);
385
+ if (set.part === 'slot') return slotDrawing(set, g);
386
+ if (set.part === 'slot_nut') return nutDrawing(set);
261
387
  if (set.part === 'thread') return threadDrawing(set);
262
388
  if (set.part === 'bearing') return bearingDrawing(set);
263
389
  if (set.part === 'driver') return driverDrawing(set);
@@ -339,6 +465,19 @@ export function pdfText(file) {
339
465
  return lines;
340
466
  }
341
467
 
468
+ /**
469
+ * A set with every field the vocabulary gives a part (profile, slot, slot_nut), each a starting value marked estimate,
470
+ * for a person to fill from the maker's sheet. @param {string} part @param {string} name @returns {object | null} null for a part with no draft
471
+ */
472
+ export function draftPart(part, name) {
473
+ const v = vocabulary(), fields = v.drafts?.[part];
474
+ if (!fields) return null;
475
+ const stamp = new Date().toISOString().slice(0, 10), rules = {};
476
+ for (const [k, value] of Object.entries(fields)) rules[k] = { value, ...(v.fields[k]?.unit != null ? { unit: v.fields[k].unit } : {}), rule: `DRAFT, not read from a sheet yet: ${v.fields[k]?.says ?? k}`, kind: 'estimate', source: 'DRAFT: give the sheet, its page and the date you read it', checked: stamp };
477
+ return { _doc: `A draft ${part.replace('_', ' ')}: every field the vocabulary has for one, each with a starting value. Put in the figures from the maker's sheet, with the sheet and its page as the source and today's date, and change each kind to spec as you go. Delete what the sheet has no figure for (cad rules check says which a ${part.replace('_', ' ')} needs). Then cad rules check ${name}, and cad rules draw ${name} to hold against the sheet's drawing.`, name, part, rules };
478
+ }
479
+ export const draftParts = () => Object.keys(vocabulary().drafts || {});
480
+
342
481
  /** Every figure a datasheet's text gives, as a rule set of estimates for a person to name and check. @returns {{ set: object, found: number }} */
343
482
  export function draftSet(name, file) {
344
483
  if (!fs.existsSync(file)) throw new Error(`no file ${file}`);