@rulecad/cad 0.7.56 → 0.7.57

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/jigs.mjs ADDED
@@ -0,0 +1,237 @@
1
+ // Jigs for an assembly's beams (@rulecad/frames jig.mjs), generated from the assembly: a drill guide for each distinct
2
+ // hole across a beam (access, drill, counterbore), a tap guide for each distinct tapped end, a cut-length stop for
3
+ // each distinct length, and a squaring corner for each distinct pair of profiles and hand a square join (blind, end-tap)
4
+ // holds: the L whose arm b lies on b, its tongues whole on both beams and its plate clear of every beam.
5
+ // Distinct means drawn the same: one guide serves every hole of its size at its distance from an end, on every mark.
6
+ // Each jig is marked with what it is for (mark and the sheet's operation number: A3; a length stop: A 260), cut into
7
+ // a face that faces up as it prints, and laid out on the printer's bed as a plate: exports/<project>/<assembly>.jigs.3mf
8
+ // (.jigs-2.3mf and on where one bed is not enough). cad beams <project>/<assembly> --jigs writes them.
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import jscad from '@jscad/modeling';
12
+ import { JOINS, beamSheet, drillGuideModel, drillGuide, tapGuideModel, tapGuide, lengthStopModel, lengthStop, squareCornerModel, squareCorner, JIG_KINDS } from '@rulecad/frames';
13
+ import { placeItems } from '@rulecad/model-link';
14
+ import { text } from '@rulecad/shapes';
15
+ import { check as printCheck } from '@rulecad/printcheck';
16
+ import { paths, printerOf } from './workspace.mjs';
17
+ import { peekRuleSet } from './rules.mjs';
18
+ import { threemf } from './threemf.mjs';
19
+ import { cutListOf } from './beams.mjs';
20
+
21
+ const { measureBoundingBox } = jscad.measurements, { translate } = jscad.transforms, { geom3 } = jscad.geometries;
22
+ const mm = (x) => String(+Number(x).toFixed(2)), r3 = (x) => +x.toFixed(3);
23
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
24
+ const strip = (e) => String(e?.message ?? e).replace(/^\w+Model: /, '');
25
+ const HOLES = JIG_KINDS['drill-guide'].ops;
26
+ const SQUARE_JOINS = Object.keys(JOINS).filter((k) => ['blind', 'end-tap'].includes(k));
27
+
28
+ // The project's printer as frames reads it ({ name, rules }), and as printcheck reads it (plain numbers)
29
+ function printerFor(project) {
30
+ let set = null;
31
+ try { set = peekRuleSet(printerOf(project)); } catch { set = null; }
32
+ const num = (k, d) => (typeof set?.rules?.[k]?.value === 'number' ? set.rules[k].value : d);
33
+ const layer = num('layer', 0.2);
34
+ return { set, check: { bed: num('bed', 256), overhang: num('overhang', 45), layer, support_gap: num('support_gap', layer), bridge: num('bridge', 5), line: num('line', 0.42), print_gap: num('print_gap', 0.3), foot: num('foot', 0.15) } };
35
+ }
36
+
37
+ // Where a beam item's face lies in the world: its outward normal and a point on it, from the item's placed frame
38
+ function faceWorld(W, place, L) {
39
+ const dir = (v) => [0, 1, 2].map((k) => W[4 * k] * v[0] + W[4 * k + 1] * v[1] + W[4 * k + 2] * v[2]);
40
+ const pt = (p) => [0, 1, 2].map((k) => W[4 * k] * p[0] + W[4 * k + 1] * p[1] + W[4 * k + 2] * p[2] + W[4 * k + 3]);
41
+ return { n: dir([...place.normal, 0]), at: pt([...place.at, L / 2]), along: dir([...place.along, 0]) };
42
+ }
43
+
44
+ // 4x4s: an item's placed frame (row by row) as JSCAD's (column by column), a product of two of JSCAD's, a point through one
45
+ const colMajor = (W) => [W[0], W[4], W[8], 0, W[1], W[5], W[9], 0, W[2], W[6], W[10], 0, W[3], W[7], W[11], 1];
46
+ const mul = (P, Q) => Array.from({ length: 16 }, (_, i) => { const c = Math.floor(i / 4), r = i % 4; return P[r] * Q[4 * c] + P[4 + r] * Q[4 * c + 1] + P[8 + r] * Q[4 * c + 2] + P[12 + r] * Q[4 * c + 3]; });
47
+ const apply = (M, p) => [0, 1, 2].map((k) => M[k] * p[0] + M[4 + k] * p[1] + M[8 + k] * p[2] + M[12 + k]);
48
+ // a world point in a beam item's frame (its section in x and y about the envelope's middle, z from end a)
49
+ const local = (W, p) => [0, 1, 2].map((k) => W[k] * (p[0] - W[3]) + W[4 + k] * (p[1] - W[7]) + W[8 + k] * (p[2] - W[11]));
50
+ const inside = (beam, q, e = 0.01) => Math.abs(q[0]) < beam.profile.width / 2 - e && Math.abs(q[1]) < beam.profile.height / 2 - e && q[2] > e && q[2] < beam.length - e;
51
+ const inPolygon = (pts, x, y) => { let c = false; for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const [xi, yi] = pts[i], [xj, yj] = pts[j]; if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) c = !c; } return c; };
52
+
53
+ // How a squaring corner, fitted in the world by F, sits on its beams: how much of each tongue lies along its own beam
54
+ // (from the tongue's ends, in that beam's frame), and which beams its plate meets (its outline sampled every 2 mm at
55
+ // half its thickness). ok where both tongues lie whole on their beams and the plate meets none.
56
+ function cornerFit(m, F, ai, bi, beams, worlds) {
57
+ const t = m.plate.thickness, { a: ta, b: tb } = m.tongues, why = [];
58
+ const along = (id, p, q) => { const W = worlds[id], B = beams.get(id), u = local(W, apply(F, p)), v = local(W, apply(F, q)), mid = u.map((x, k) => (x + v[k]) / 2);
59
+ const across = Math.abs(mid[0]) < B.profile.width / 2 && Math.abs(mid[1]) < B.profile.height / 2;
60
+ return across ? Math.max(0, Math.min(Math.max(u[2], v[2]), B.length) - Math.max(Math.min(u[2], v[2]), 0)) : 0; };
61
+ const on = { a: r3(along(ai, [ta.at, ta.from, t + ta.depth / 2], [ta.at, ta.to, t + ta.depth / 2])), b: r3(along(bi, [tb.from, tb.at, t + tb.depth / 2], [tb.to, tb.at, t + tb.depth / 2])) };
62
+ const need = { a: r3(ta.to - ta.from), b: r3(tb.to - tb.from) };
63
+ for (const k of ['a', 'b']) if (on[k] < need[k] - 0.01) why.push(`its ${k} tongue has ${mm(on[k])} of its ${mm(need[k])} mm on ${k === 'a' ? ai : bi}, the rest past its end`);
64
+ const xs = m.outline.map((p) => p[0]), ys = m.outline.map((p) => p[1]), hits = new Set();
65
+ for (let x = Math.min(...xs) + 0.5; x < Math.max(...xs); x += 2) for (let y = Math.min(...ys) + 0.5; y < Math.max(...ys); y += 2) {
66
+ if (!inPolygon(m.outline, x, y)) continue;
67
+ const w = apply(F, [x, y, t / 2]);
68
+ for (const [id, B] of beams) if (worlds[id] && !hits.has(id) && inside(B, local(worlds[id], w))) hits.add(id);
69
+ }
70
+ if (hits.size) why.push(`its plate meets ${[...hits].join(', ')}`);
71
+ return { ok: !why.length, on, why, short: r3(need.a - on.a + need.b - on.b + 100 * hits.size) };
72
+ }
73
+
74
+ /**
75
+ * The jigs an assembly's beams take, each with what it is for. Holes too far from both ends for one print, tapped ends
76
+ * no guide can be drawn for, and square joins where no corner of either hand lies whole on both beams clear of the
77
+ * others, give a warning (jig.drill, jig.tap, jig.square) in place of a jig. Each squaring corner's use carries its
78
+ * hand, how much of each tongue lies on its beam (on), and fit: the 4x4 (JSCAD's) that puts the print pose in the world.
79
+ * @param {object} s a built assembly
80
+ * @returns {{ jigs: { kind: string, name: string, model: object, for: object[], label: string }[], findings: object[] }}
81
+ */
82
+ export function jigsOf(s) {
83
+ const c = cutListOf(s), jigs = new Map(), findings = [], printer = printerFor(s.project).set ?? undefined;
84
+ const warn = (code, txt, refs) => findings.push({ level: 'warn', code, text: txt, refs });
85
+ const add = (key, kind, model, who) => { if (!jigs.has(key)) jigs.set(key, { kind, name: model.name, model, for: [] }); jigs.get(key).for.push(who); };
86
+ if (!c) return { jigs: [], findings };
87
+ for (const mk of c.marks) {
88
+ const b = mk.beam, sheet = beamSheet(b, { mark: mk.mark, items: mk.items });
89
+ b.ops.forEach((x, i) => {
90
+ const who = { mark: mk.mark, items: mk.items, op: i + 1, at: x.at, line: x.line };
91
+ if (HOLES.includes(x.op)) {
92
+ try {
93
+ const m = drillGuideModel(b, i, { ...(printer ? { printer } : {}) }), z = r3(m.fit[6] * m.bush.at[1] + m.fit[14]); // (the bush's axis, fitted: its distance from end a)
94
+ const dim = sheet.dimensions.find((d) => d.op === i + 1);
95
+ add(`drill|${m.name}|${m.profile}|${m.plate.span.join(',')}`, 'drill-guide', m, { ...who, label: `${mk.mark}${i + 1}`, from: m.from, distance: m.bush.at[1], bush: z, sheet: dim ? dim.distance : null, sheetText: dim ? dim.text : null });
96
+ } catch (e) { warn('jig.drill', `mark ${mk.mark} (${mk.items.join(', ')}), operation ${i + 1}: no drill guide: ${strip(e)}`, { mark: mk.mark, op: i + 1 }); }
97
+ }
98
+ if (x.op === 'tap') {
99
+ try {
100
+ const m = tapGuideModel(b, i, { ...(printer ? { printer } : {}) });
101
+ add(`tap|${m.name}|${m.profile}|${JSON.stringify(m.bores)}`, 'tap-guide', m, { ...who, label: `${mk.mark}${i + 1}`, end: x.end, bores: x.bores });
102
+ } catch (e) { warn('jig.tap', `mark ${mk.mark} (${mk.items.join(', ')}), operation ${i + 1}: no tap guide: ${strip(e)}`, { mark: mk.mark, op: i + 1 }); }
103
+ }
104
+ });
105
+ const m = lengthStopModel(b.profile, b.length, { ...(printer ? { printer } : {}) });
106
+ add(`length|${b.profile.name}|${b.length}`, 'length-stop', m, { mark: mk.mark, items: mk.items, label: `${mk.mark} ${mm(b.length)}`, length: b.length });
107
+ }
108
+ // a squaring corner for each square join: on a face of each beam in one plane, of the hand whose arm b lies on b, its
109
+ // tongues whole on their beams and its plate clear of every beam; the outer pair of faces first, then right-handed
110
+ const marks = new Map(c.marks.flatMap((mk) => mk.items.map((id) => [id, mk.mark])));
111
+ const placed = s.joins?.length ? placeItems(s.motion, s.jointValues) : [], worlds = Object.fromEntries(s.motion.items.map((x, i) => [x[0], placed[i]])), beams = new Map(s.objects.filter((o) => o.beam && !o.unplaced).map((o) => [o.id, o.beam]));
112
+ const middle = (() => { const pts = [...beams.keys()].filter((id) => worlds[id]).map((id) => { const W = worlds[id], L = beams.get(id).length; return [W[2] * L / 2 + W[3], W[6] * L / 2 + W[7], W[10] * L / 2 + W[11]]; }); return pts.length ? [0, 1, 2].map((k) => pts.reduce((t, p) => t + p[k], 0) / pts.length) : [0, 0, 0]; })();
113
+ const models = new Map(), corner = (...args) => { const key = JSON.stringify(args); if (!models.has(key)) models.set(key, squareCornerModel(...args)); return models.get(key); };
114
+ for (const j of s.joins ?? []) {
115
+ if (!SQUARE_JOINS.includes(j.kind) || j.model.b.end != null) continue;
116
+ const [ai, bi] = j.items, A = beams.get(ai), B = beams.get(bi), Wa = worlds[ai], Wb = worlds[bi];
117
+ if (!A || !B || !Wa || !Wb) continue;
118
+ const end = j.end[0], away = [0, 1, 2].map((k) => (end === 'a' ? 1 : -1) * Wa[4 * k + 2]); // along a, away from b
119
+ const tried = [];
120
+ for (const pa of A.places.filter((q) => q.slot)) for (const pb of B.places.filter((q) => q.slot)) {
121
+ const fa = faceWorld(Wa, pa, A.length), fb = faceWorld(Wb, pb, B.length);
122
+ if (dot(fa.n, fb.n) < 1 - 1e-6 || Math.abs(dot(fa.n, fa.at.map((v, k) => v - fb.at[k]))) > 0.05) continue;
123
+ const out = dot(fa.n, fb.at.map((v, k) => v - middle[k])), edge = dot(fb.along, away) > 0 ? 'hi' : 'lo';
124
+ for (const hand of ['right', 'left']) {
125
+ const m = corner({ profile: A.profile, face: pa.name, end, length: A.length }, { profile: B.profile, face: pb.name, edge }, { hand, ...(printer ? { printer } : {}) });
126
+ tried.push({ pa, pb, hand, out, m, fit: mul(colMajor(Wa), m.fit), ...cornerFit(m, mul(colMajor(Wa), m.fit), ai, bi, beams, worlds) });
127
+ }
128
+ }
129
+ if (!tried.length) { warn('jig.square', `${j.label}: no squaring corner: ${ai} and ${bi} have no slotted faces in one plane for it to key into`, { join: j.index }); continue; }
130
+ const fits = tried.filter((x) => x.ok).sort((x, y) => y.out - x.out || (x.hand === 'right' ? -1 : 1) - (y.hand === 'right' ? -1 : 1));
131
+ if (!fits.length) {
132
+ const near = [...tried].sort((x, y) => x.short - y.short)[0];
133
+ warn('jig.square', `${j.label}: no squaring corner fits: on ${ai}'s ${near.pa.name} and ${bi}'s ${near.pb.name}, the nearest (${near.hand}-handed) ${near.why.join('; ')}. Square this join with an engineer's square`, { join: j.index });
134
+ continue;
135
+ }
136
+ const best = fits[0], m = best.m;
137
+ add(`corner|${m.name}|${JSON.stringify([m.outline, m.tongues])}`, 'square-corner', m, { join: j.index, label: `${marks.get(ai)}${marks.get(bi)}`, marks: [marks.get(ai), marks.get(bi)], items: [ai, bi], faces: [best.pa.name, best.pb.name], end, edge: m.edge, hand: best.hand, on: best.on, fit: best.fit.map(r3), text: j.label });
138
+ }
139
+ const out = [...jigs.values()].map((x) => ({ ...x, label: labelOf(x) }));
140
+ return { jigs: out, findings };
141
+ }
142
+
143
+ // A jig's mark: what it is for, as short as the face it is cut in takes (the first and a + where all do not fit)
144
+ function labelOf(x) {
145
+ const marks = [...new Set(x.for.flatMap((w) => w.marks ?? [w.mark]))].sort().join(''), t = x.kind === 'length-stop' ? `${marks} ${mm(x.model.length)}` : marks;
146
+ return t.length <= 9 ? t : `${t.slice(0, 8)}+`;
147
+ }
148
+
149
+ // A mark as a 2D outline that fits the room given ([along, across]), or null where none fits
150
+ function markShape(label, room) {
151
+ if (!label || !room || room[1] < 2.5 || room[0] < 4) return null;
152
+ let h = Math.min(4, room[1] * 0.7), g = text({ text: label, height: h, stroke: 0.6 });
153
+ const [lo, hi] = measureBoundingBox(g), w = hi[0] - lo[0];
154
+ if (w > room[0]) { h *= room[0] / w; if (h < 2) return null; g = text({ text: label, height: h, stroke: 0.6 }); }
155
+ return g;
156
+ }
157
+
158
+ /** Each jig's printed parts, in print pose and marked: [{ name, solid, count }]. @param {object} x one of jigsOf's */
159
+ export function jigParts(x) {
160
+ const m = x.model, mark = (room) => markShape(x.label, room);
161
+ if (x.kind === 'drill-guide') return [{ name: m.name, solid: drillGuide(m, { mark: mark(m.label.room) }), count: 1 }];
162
+ if (x.kind === 'tap-guide') return [{ name: m.name, solid: tapGuide(m, { mark: mark(m.label?.room) }), count: 1 }];
163
+ if (x.kind === 'square-corner') return [{ name: m.name, solid: squareCorner(m, { mark: mark(m.label.room) }), count: 1 }];
164
+ return [{ name: `${m.name}-block`, solid: lengthStop(m, { mark: mark(m.label.room) }), count: 1 }, { name: `${m.name}-gauge`, solid: lengthStop(m, { part: 'gauge', mark: mark(m.gaugeLabel.room) }), count: m.gauge.pieces }];
165
+ }
166
+
167
+ const triangles = (g) => geom3.toPolygons(g).flatMap((p) => p.vertices.slice(1, -1).map((v, i) => [[...p.vertices[0]], [...v], [...p.vertices[i + 2]]]));
168
+
169
+ // Shelves on a bed, largest first, each part gap apart: as many beds as it takes
170
+ function pack(items, bed, gap) {
171
+ const sorted = [...items].sort((a, b) => b.size[1] - a.size[1] || b.size[0] - a.size[0]), beds = [], room = bed - 2 * gap;
172
+ for (const p of sorted) {
173
+ if (p.size[0] > room || p.size[1] > room) throw new Error(`${p.name} is ${mm(p.size[0])} x ${mm(p.size[1])} mm, more than the ${mm(bed)} mm bed takes`);
174
+ let done = false;
175
+ for (const b of beds) {
176
+ const shelf = b.shelves.at(-1);
177
+ if (shelf.x + p.size[0] <= room + 1e-9) { b.parts.push({ ...p, at: [shelf.x, shelf.y] }); shelf.x += p.size[0] + gap; shelf.h = Math.max(shelf.h, p.size[1]); done = true; break; }
178
+ const y = shelf.y + shelf.h + gap;
179
+ if (y + p.size[1] <= room + 1e-9) { b.shelves.push({ x: p.size[0] + gap, y, h: p.size[1] }); b.parts.push({ ...p, at: [0, y] }); done = true; break; }
180
+ }
181
+ if (!done) beds.push({ shelves: [{ x: p.size[0] + gap, y: 0, h: p.size[1] }], parts: [{ ...p, at: [0, 0] }] });
182
+ }
183
+ return beds;
184
+ }
185
+
186
+ /** The plate files cad beams --jigs writes for an assembly: exports/<project>/<assembly>.jigs.3mf, .jigs-2.3mf, ... */
187
+ export const jigFile = (s, n, of) => paths.exports(s.project, `${s.name}.jigs${of > 1 ? `-${n}` : ''}.3mf`);
188
+
189
+ /**
190
+ * The jigs of an assembly, made, checked by printcheck and laid out on the printer's bed as plates, written to
191
+ * exports/; old plates of this assembly's jigs removed first.
192
+ * @param {object} s a built assembly @param {{ write?: boolean }} [o]
193
+ * @returns {Promise<{ jigs: object[], plates: { file: string, parts: string[] }[], findings: object[], parts: object[] }>}
194
+ * jigs: each with its kind, name, mark, what it is for, grams, margin and what printcheck says of each part
195
+ */
196
+ export async function writeJigs(s, { write = true } = {}) {
197
+ const { jigs, findings } = jigsOf(s), { check } = printerFor(s.project), dir = paths.exports(s.project), base = `${s.name}.jigs`;
198
+ if (write && fs.existsSync(dir)) for (const f of fs.readdirSync(dir)) if (f.startsWith(base) && f.endsWith('.3mf')) fs.rmSync(path.join(dir, f));
199
+ const parts = [], rows = [];
200
+ for (const x of jigs) {
201
+ const made = jigParts(x), checks = [];
202
+ for (const p of made) {
203
+ const tris = triangles(p.solid), issues = printCheck(tris, check).filter((f) => f.level === 'fail' || f.level === 'warn');
204
+ checks.push({ part: p.name, count: p.count, issues: issues.map((f) => `${f.code}: ${f.text}`) });
205
+ const [lo, hi] = measureBoundingBox(p.solid);
206
+ for (let k = 0; k < p.count; k++) parts.push({ name: p.count > 1 ? `${p.name}-${k + 1}` : p.name, jig: x.name, tris: tris.map((t) => t.map((v) => [v[0] - lo[0], v[1] - lo[1], v[2] - lo[2]])), size: [hi[0] - lo[0], hi[1] - lo[1]] });
207
+ for (const f of issues) findings.push({ level: f.level, code: 'jig.print', text: `${p.name}: ${f.text}`, refs: { jig: x.name, check: f.code } });
208
+ }
209
+ const m = x.model;
210
+ rows.push({ kind: x.kind, name: x.name, mark: x.label, for: x.for, grams: m.grams, margin: m.margin, size: m.size, checks, findings: m.findings.map(({ level, code, text: t, values }) => ({ level, code, text: t, ...(values ? { values } : {}) })) });
211
+ }
212
+ const gap = Math.max(2, Math.ceil((check.print_gap + 2 * check.foot) / check.line - 1e-6) * check.line), beds = parts.length ? pack(parts, check.bed, gap) : [];
213
+ const plates = [];
214
+ for (const [n, b] of beds.entries()) {
215
+ const file = jigFile(s, n + 1, beds.length), half = check.bed / 2 - gap;
216
+ const objects = b.parts.map((p) => ({ name: p.name, parts: [{ name: p.name, triangles: p.tris.map((t) => t.map((v) => [v[0] + p.at[0] - half, v[1] + p.at[1] - half, v[2]])), slot: 1 }] }));
217
+ if (write) { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, await threemf(objects, { title: `${s.a.title || s.name}: jigs` })); }
218
+ plates.push({ file, parts: b.parts.map((p) => p.name), objects });
219
+ }
220
+ return { jigs: rows, plates: plates.map(({ objects, ...p }) => p), findings, parts: plates.flatMap((p) => p.objects) };
221
+ }
222
+
223
+ /** The jigs as lines for a person: each with its mark, what it is for, its grams and margin, and how it prints. */
224
+ export function jigsText(ref, r) {
225
+ const out = [`${ref}: ${r.jigs.length} jig${r.jigs.length === 1 ? '' : 's'}, marked with what each is for`];
226
+ for (const x of r.jigs) {
227
+ const what = x.kind === 'drill-guide' ? x.for.map((w) => `${w.label} (${w.items.join(', ')}: ${w.line}; bush ${mm(w.bush)} mm from end a, the sheet ${w.sheetText})`).join('; ')
228
+ : x.kind === 'tap-guide' ? x.for.map((w) => `${w.label} (${w.items.join(', ')}: ${w.line})`).join('; ')
229
+ : x.kind === 'length-stop' ? x.for.map((w) => `mark ${w.mark} (${w.items.join(', ')})`).join('; ')
230
+ : x.for.map((w) => w.text).join('; ');
231
+ const bad = x.checks.flatMap((c) => c.issues);
232
+ out.push(` ${x.name} [${x.mark}]: ${mm(x.grams)} g, ${mm(x.margin)}× at its load, ${bad.length ? `${bad.length} print issue${bad.length > 1 ? 's' : ''}` : 'prints clean'}: for ${what}`);
233
+ }
234
+ for (const p of r.plates) out.push(` plate ${p.file}: ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}`);
235
+ for (const f of r.findings) out.push(` [${f.level}] ${f.text}`);
236
+ return out.join('\n');
237
+ }
package/lib/joins.mjs ADDED
@@ -0,0 +1,259 @@
1
+ // Joins in assemblies (@rulecad/frames' joinModel): "joins": [{ "kind": "blind", "a": "y1.a", "b": "x1.back@120",
2
+ // "fitting", "screw", "note" }]. A join names an end of one beam item (a) and a place on another (b), and says how they
3
+ // are held. Before the items are built, each join puts its operations on both beams (a tap in a's end, an access hole
4
+ // or a clearance hole across b) and its screws into "fasten", so the screws are followed, checked and counted as any
5
+ // fasten's are. Once built, the checks: join.geometry (the end meets the face square and flush, where the join says,
6
+ // on a slot where the kind needs one), join.end (every beam end is joined or capped), join.stiffness (each join's
7
+ // spring for a frame's solve, saying whether it was measured on the joint rig, and when, or is an estimate),
8
+ // join.fitting (a kind whose fitting comes later), and join.drop (a beam held by one join with a mass on it, as on the
9
+ // joint rig: its drop, a prediction cad measured turns into the join's spring).
10
+ import { JOINS, JOIN_SCALE, joinModel } from '@rulecad/frames';
11
+ import { placeItems } from '@rulecad/model-link';
12
+ import { beamOf, beamPlace, framesContext } from './beams.mjs';
13
+ import { joinFitting, fittedStiffness } from './fittings.mjs';
14
+
15
+ const KEYS = ['kind', 'a', 'b', 'fitting', 'screw', 'brace', 'load', 'nut', 'note'];
16
+ const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
17
+ const mm = (x) => String(+Number(x).toFixed(2)), r3 = (x) => +x.toFixed(3);
18
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
19
+ 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]];
20
+
21
+ /** The working figures of the join checks, each with what it rests on. */
22
+ export const JOIN_CHECK = {
23
+ flush: { value: 0.05, unit: 'mm', rule: 'An end meets a face flush when it stands off it, or runs into it, by no more than this: far under a cut\'s tolerance, so a gap a person can see is a failure', kind: 'default', source: 'A working figure of @rulecad/cad, the same as fasten\'s holes on one axis', checked: '2026-11-16' },
24
+ place: { value: 0.05, unit: 'mm', rule: 'An end is where its join says, on the face, when its centre is within this of the address', kind: 'default', source: 'A working figure of @rulecad/cad', checked: '2026-11-16' },
25
+ square: { value: 0.5, unit: '°', rule: 'An end meets a face square when its axis is within this of the face\'s normal: a beam cut square to ±0.5 mm across 20 mm is about 1.4° out, so this holds the drawing, not the saw', kind: 'default', source: 'A working figure of @rulecad/cad', checked: '2026-11-16' },
26
+ };
27
+
28
+ // "y1.a" into its item and the rest
29
+ const split = (n) => { const s = String(n).trim(), i = s.indexOf('.'); return i < 0 ? [s, ''] : [s.slice(0, i), s.slice(i + 1)]; };
30
+ // (one place written two ways: a face's first slot with or without its number, top@250 and top.1@250, a and a.1)
31
+ const placeOf = (p) => String(p).trim().replace(/\s+/g, '').replace(/\.1(?=@|$)/, '');
32
+ const sameAt = (p, q) => placeOf(p) === placeOf(q);
33
+
34
+ /**
35
+ * An assembly's joins worked out before its items are built: each join's operations added to its beams' ops, and its
36
+ * screws added to "fasten" (each marked with its join). Refused by name: a join that is not { kind, a, b }, an end or
37
+ * a place on an item that is not a beam, a join of a beam to itself, and what joinModel refuses.
38
+ * @param {object} a the assembly as read @param {(x: any) => number} num its expressions
39
+ * @returns {{ a: object, joins: object[] }} the assembly with the joins' operations and screws in, and each join worked out
40
+ */
41
+ export function expandJoins(a, num, context = framesContext(), material = 'pla') {
42
+ const list = a.joins;
43
+ if (list == null) return { a, joins: [] };
44
+ if (!Array.isArray(list)) throw new Error(`joins is a list: [{ "kind": "blind", "a": "y1.a", "b": "x1.back@120" }] (got ${shown(list)})`);
45
+ if (!list.length) return { a, joins: [] };
46
+ const given = { sets: context?.sets ?? {} }; // (a bought fitting of the workspace's own, beside the kit's)
47
+ const items = a.items || [], beams = new Map(items.filter((it) => it.beam).map((it) => [it.id, it])), models = new Map();
48
+ const modelOf = (id) => { if (!models.has(id)) models.set(id, beamOf(beams.get(id), num, context).model); return models.get(id); };
49
+ const extra = new Map(), fasten = [], joins = [], first = (a.fasten || []).length, added = [], ids = new Set(items.map((it) => it.id));
50
+ list.forEach((j, i) => {
51
+ const what = `join ${i + 1}`;
52
+ if (!j || typeof j !== 'object' || Array.isArray(j)) throw new Error(`${what} is { "kind", "a", "b" } (got ${shown(j)})`);
53
+ for (const k of Object.keys(j)) if (!KEYS.includes(k)) throw new Error(`${what}: a join has no "${k}": it takes ${KEYS.join(', ')}`);
54
+ if (!JOINS[j.kind]) throw new Error(`${what}: kind is one of ${Object.keys(JOINS).join(', ')} (got ${shown(j.kind)})`);
55
+ const ends = {};
56
+ for (const side of ['a', 'b']) {
57
+ if (typeof j[side] !== 'string' || !j[side].includes('.')) throw new Error(`${what}: ${side} is ${side === 'a' ? 'a beam\'s end, as y1.a' : 'a place on a beam, as x1.back@120 (or an end, x1.b)'} (got ${shown(j[side])})`);
58
+ const [id, rest] = split(j[side]);
59
+ if (!beams.has(id)) throw new Error(`${what}: ${side} is on a beam item of this assembly, and ${id} is ${items.some((it) => it.id === id) ? 'not a beam' : 'not an item'} (beams: ${[...beams.keys()].join(', ') || 'none'})`);
60
+ ends[side] = { id, rest };
61
+ }
62
+ if (ends.a.id === ends.b.id) throw new Error(`${what}: a and b are on one beam, ${ends.a.id}: a join is between two beams`);
63
+ const mitre = j.kind === 'mitre' ? mitreOf(what, beams.get(ends.a.id), ends.a.rest, beams.get(ends.b.id), ends.b.rest, num) : null;
64
+ let m;
65
+ try { m = joinModel(j.kind, { beam: modelOf(ends.a.id), end: ends.a.rest }, { beam: modelOf(ends.b.id), address: ends.b.rest }, { ...(j.screw != null ? { screw: j.screw } : {}), ...(j.fitting != null ? { fitting: j.fitting } : {}), ...(mitre ? { mitre } : {}), given }); }
66
+ catch (e) { throw new Error(`${what}: ${String(e.message).replace(/^(joinModel|beamAnchor): /, '')}`); }
67
+ for (const [side, ops] of [['a', m.a.ops], ['b', m.b.ops]]) { const id = ends[side].id; if (ops.length) extra.set(id, [...(extra.get(id) || []), ...ops]); }
68
+ const label = j.note || `${j.kind} join of ${j.a} to ${j.b}`, mine = [];
69
+ for (const k of ['brace', 'load', 'nut']) if (j[k] != null && !(m.fitting?.printed && j.fitting === 'printed')) throw new Error(`${what}: ${k} is for a printed fitting: give "fitting": "printed" on a ${Object.keys(JOINS).filter((x) => JOINS[x].printed).join(', ')} join, or leave ${k} out`);
70
+ // a printed fitting: its item, placed from where the beams are, and a fasten for each leg into its beam's slot
71
+ let fitted = null;
72
+ if (m.fitting?.printed && j.fitting === 'printed') {
73
+ fitted = joinFitting(j, i, { ia: beams.get(ends.a.id), ib: beams.get(ends.b.id), A: modelOf(ends.a.id), B: modelOf(ends.b.id), m, ends, place: beamPlace }, num, context, material, ids);
74
+ added.push(fitted.item);
75
+ for (const x of fitted.fasten) { mine.push(first + fasten.length); fasten.push(x); }
76
+ m.stiffness = fittedStiffness(m.stiffness, fitted.model);
77
+ } else if (m.fitting?.bought && m.fitting.fits) {
78
+ // a bought one: its set's item placed the same way, its screws into the set's nuts (an inner or anchor connector's
79
+ // are part of it), its stiffness its set's (joinModel's)
80
+ fitted = joinFitting(j, i, { ia: beams.get(ends.a.id), ib: beams.get(ends.b.id), A: modelOf(ends.a.id), B: modelOf(ends.b.id), m, ends, place: beamPlace }, num, context, material, ids);
81
+ added.push(fitted.item);
82
+ for (const x of fitted.fasten) { mine.push(first + fasten.length); fasten.push(x); }
83
+ }
84
+ // the head: inside b's slot under its lips (blind), or on the lips of the slot across b (end-tap), or on a plain face
85
+ const lips = j.kind === 'blind' ? { item: ends.b.id, slot: m.b.slot, inside: true } : m.b.across?.slot ? { item: ends.b.id, slot: m.b.across.slot, inside: false } : null;
86
+ for (const sc of m.screws) { mine.push(first + fasten.length); fasten.push({ screw: sc.screw, through: [ends.b.id], into: ends.a.id, at: [`${ends.a.id}.${sc.bore}`], note: label, join: i, ...(lips ? { lips } : {}) }); }
87
+ joins.push({ index: i, kind: j.kind, a: j.a, b: j.b, items: [ends.a.id, ends.b.id], end: ends.a.rest, address: ends.b.rest, label, fitting: j.fitting ?? null, model: m, fasten: mine, ...(fitted ? { fitted: { item: fitted.item.id, model: fitted.model } } : {}) });
88
+ });
89
+ // each beam's own ops first; a join's op where the beam has none like it at that place (a tap at a and at a.1 are one)
90
+ const withOps = items.map((it) => {
91
+ const add = extra.get(it.id);
92
+ if (!add) return it;
93
+ const own = it.beam.ops || [], ops = [...own];
94
+ for (const op of add) if (!ops.some((g) => g?.op === op.op && (sameAt(g.at, op.at) || (op.op === 'tap' && String(g.at).trim()[0] === op.at[0])))) ops.push(op);
95
+ return { ...it, beam: { ...it.beam, ops } };
96
+ });
97
+ return { a: { ...a, items: [...withOps, ...added], ...(fasten.length ? { fasten: [...(a.fasten || []), ...fasten] } : {}) }, joins };
98
+ }
99
+
100
+ // A mitre's cuts from where the two beams are: the angle from square that halves the corner, the face each sees the
101
+ // corner on, and the outside of the corner, where each beam's length is measured. Both beams placed by their ends.
102
+ function mitreOf(what, ia, ea, ib, eb, num) {
103
+ const fa = beamPlace(ia, num), fb = beamPlace(ib, num);
104
+ if (!fa || !fb) throw new Error(`${what}: a mitre join is cut from where the beams meet: place ${!fa ? ia.id : ib.id} by its ends (from, to)`);
105
+ if (!/^[ab]$/.test(ea)) throw new Error(`${what}: a mitre join cuts a whole end: a is ${ia.id}.a or ${ia.id}.b (got ${ia.id}.${ea})`);
106
+ const col = (f, k) => [f[k], f[4 + k], f[8 + k]], body = (f, e) => col(f, 2).map((c) => (e === 'a' ? c : -c)); // (along the beam, away from the corner)
107
+ const da = body(fa, ea), db = body(fb, eb), n = cross(da, db), nl = Math.hypot(...n), phi = (Math.acos(Math.max(-1, Math.min(1, dot(da, db)))) * 180) / Math.PI;
108
+ if (nl < 1e-9) throw new Error(`${what}: ${ia.id} and ${ib.id} lie along one line, so there is no corner to mitre: a splice joins them end to end`);
109
+ const side = (f, other) => {
110
+ const back = col(f, 0), top = col(f, 1), u = n.map((c) => c / nl);
111
+ if (Math.abs(Math.abs(dot(u, top)) - 1) < 1e-6) return { about: 'top', long: dot(back, other) > 0 ? 'front' : 'back' };
112
+ if (Math.abs(Math.abs(dot(u, back)) - 1) < 1e-6) return { about: 'back', long: dot(top, other) > 0 ? 'bottom' : 'top' };
113
+ return null;
114
+ };
115
+ const a = side(fa, db), b = side(fb, da);
116
+ if (!a || !b) throw new Error(`${what}: the corner of ${ia.id} and ${ib.id} lies across ${!a ? ia.id : ib.id}'s faces, not square to one: turn it with roll so a face lies in the corner's plane`);
117
+ return { angle: +(90 - phi / 2).toFixed(6), a, b };
118
+ }
119
+
120
+ // What a join's spring rests on, in words: the joint rig's measurement and its date, or an estimate until it is measured
121
+ function restsOn(k) {
122
+ const b = k.measured?.bending, t = k.measured?.twist;
123
+ if (b && t) return `measured on the joint rig on ${b}${t !== b ? ` (twist on ${t})` : ''}`;
124
+ if (b) return `bending measured on the joint rig on ${b}; twist an estimate until the rig measures it`;
125
+ if (t) return `twist measured on the joint rig on ${t}; bending an estimate until the rig measures it`;
126
+ return 'an estimate, until the joint rig (issue 264) measures it';
127
+ }
128
+
129
+ /** The ends of each beam item a join or an item placed at it covers: Set of "x1.a". */
130
+ function covered(s) {
131
+ const out = new Set();
132
+ for (const j of s.joins) {
133
+ out.add(`${j.items[0]}.${j.end[0]}`);
134
+ if (/^[ab]$/.test(j.address)) out.add(`${j.items[1]}.${j.address}`);
135
+ }
136
+ for (const it of s.a.items || []) if (typeof it.at === 'string') { const m = /^([\w-]+)\.([ab])(\.|$)/.exec(it.at.trim()); if (m) out.add(`${m[1]}.${m[2]}`); }
137
+ return out;
138
+ }
139
+
140
+ /**
141
+ * A built assembly's join findings: join.geometry for each join, its model's own findings (join.fitting), join.stiffness
142
+ * for each, and join.end over the beams. @param {object} s a built assembly @param {Function} f the findings' sink
143
+ */
144
+ export function joinChecks(s, f) {
145
+ if (!s.joins?.length) return;
146
+ const worlds = placeItems(s.motion, s.jointValues);
147
+ const ids = s.motion.items.map((x) => x[0]);
148
+ const world = (n, what) => {
149
+ const { item, frame: r } = s.motion.address(n, what), W = worlds[item];
150
+ const pt = (p) => [0, 1, 2].map((k) => W[4 * k] * p[0] + W[4 * k + 1] * p[1] + W[4 * k + 2] * p[2] + W[4 * k + 3]);
151
+ const dir = (v) => [0, 1, 2].map((k) => W[4 * k] * v[0] + W[4 * k + 1] * v[1] + W[4 * k + 2] * v[2]);
152
+ return { at: pt([r[3], r[7], r[11]]), axis: dir([r[2], r[6], r[10]]), ref: dir([r[0], r[4], r[8]]) };
153
+ };
154
+ const { flush, place, square } = Object.fromEntries(Object.entries(JOIN_CHECK).map(([k, v]) => [k, v.value]));
155
+ for (const j of s.joins) {
156
+ const m = j.model, [ai, bi] = j.items, refs = { join: j.index, kind: j.kind, a: j.a, b: j.b };
157
+ for (const x of m.findings) f(x.level, `${j.label}: ${x.text.startsWith(`${m.says}: `) ? x.text.slice(m.says.length + 2) : x.text}`, x.level === 'fail' || x.level === 'warn' ? `${j.label}: ${x.code.split('.')[1]}` : null, { code: x.code, refs: { ...refs, ...x.refs } });
158
+ // where it meets: from the bore the screw goes in where there is one, else the end's centre
159
+ const A = world(`${ai}.${m.a.bores[0] ?? j.end[0]}`, `join ${j.index + 1}`), B = world(`${bi}.${j.address}`, `join ${j.index + 1}`);
160
+ if (m.b.end == null) {
161
+ const n = B.axis, gap = dot(sub(A.at, B.at), n), off = sub(sub(A.at, B.at), n.map((c) => c * gap)), along = dot(off, B.ref), aside = Math.hypot(...off.map((c, k) => c - B.ref[k] * along));
162
+ const angle = (Math.acos(Math.max(-1, Math.min(1, -dot(A.axis, n)))) * 180) / Math.PI, wrong = [];
163
+ const values = { gap: r3(gap), along: r3(along), across: r3(aside), angle: +angle.toFixed(2) };
164
+ const face = `${bi}'s ${m.b.place} face`, end = `${ai}'s end ${j.end}`;
165
+ if (Math.abs(gap) > flush) wrong.push(gap > 0 ? `${end} stands ${mm(gap)} mm off ${face}: a gap of ${mm(gap)} mm, where it meets flush. Move ${ai} ${mm(gap)} mm toward ${bi}` : `${end} runs ${mm(-gap)} mm into ${face}: move ${ai} ${mm(-gap)} mm back, so it meets the face flush`);
166
+ if (angle > square) wrong.push(`${end} meets ${face} ${mm(+angle.toFixed(2))}° from square`);
167
+ if (Math.hypot(along, aside) > place) wrong.push(`${end} is ${along ? `${mm(Math.abs(along))} mm ${along > 0 ? 'toward' : 'away from'} ${bi}'s end b` : ''}${along && aside > place ? ' and ' : ''}${aside > place ? `${mm(aside)} mm across ${m.b.slot ? 'the slot\'s centre line' : 'the face'}` : ''} from ${j.b}${aside <= place && m.b.distance != null ? `: it meets ${bi} ${mm(m.b.distance + along)} mm from its end a, so the join says ${bi}.${m.b.place.split('.')[0]}@${mm(m.b.distance + along)}, or ${ai} moves` : ''}`);
168
+ if (wrong.length) f('fail', `${j.label}: ${wrong.join('; ')}`, `${j.label}: geometry`, { code: 'join.geometry', at: A.at.map(r3), between: [A.at.map(r3), B.at.map(r3)], values, refs });
169
+ else if (!m.findings.some((x) => x.code === 'join.geometry')) f('pass', `${j.label}: ${end} meets ${face} square and flush at ${mm(m.b.distance)} mm from ${bi}'s end a${m.b.slot && JOINS[j.kind].slot ? ', on the slot\'s centre line' : ''}`, null, { code: 'join.geometry', at: A.at.map(r3), values, refs });
170
+ } else {
171
+ // end to end (a splice): the ends meet face to face on one axis; at a corner (mitre, cube, a node): the axes meet
172
+ const gap = Math.hypot(...sub(A.at, B.at)), angle = (Math.acos(Math.max(-1, Math.min(1, -dot(A.axis, B.axis)))) * 180) / Math.PI;
173
+ if (j.kind === 'splice') {
174
+ const ok = gap <= flush && angle <= square, values = { gap: r3(gap), angle: +angle.toFixed(2) };
175
+ f(ok ? 'pass' : 'fail', `${j.label}: ${ok ? `${ai}'s end ${j.end} meets ${bi}'s end ${j.address} face to face on one axis` : `${ai}'s end ${j.end} and ${bi}'s end ${j.address} are ${mm(gap)} mm apart${angle > square ? ` and ${mm(+angle.toFixed(2))}° off one axis` : ''}, where a splice meets end to end`}`, ok ? null : `${j.label}: geometry`, { code: 'join.geometry', at: A.at.map(r3), between: [A.at.map(r3), B.at.map(r3)], values, refs });
176
+ } else {
177
+ const w = cross(A.axis, B.axis), wl = Math.hypot(...w), d = sub(B.at, A.at), miss = wl < 1e-9 ? Math.hypot(...cross(d, A.axis)) : Math.abs(dot(d, w)) / wl;
178
+ const reach = Math.max(...[ai, bi].map((id) => { const o = s.objects.find((x) => x.id === id)?.beam; return o ? Math.hypot(o.profile.width, o.profile.height) : 0; }));
179
+ const ok = wl > 1e-9 && miss <= place && gap <= reach + flush, values = { miss: r3(miss), gap: r3(gap), angle: +angle.toFixed(2) };
180
+ f(ok ? 'pass' : 'fail', `${j.label}: ${ok ? `the axes of ${ai} and ${bi} meet at the corner, their ends ${mm(gap)} mm apart` : wl <= 1e-9 ? `${ai} and ${bi} lie along one line, where a ${j.kind} join meets at a corner` : miss > place ? `the axes of ${ai} and ${bi} pass ${mm(miss)} mm apart, where a ${j.kind} join's meet at the corner` : `${ai}'s end ${j.end} and ${bi}'s end ${j.address} are ${mm(gap)} mm apart, more than the beams' ${mm(reach)} mm across: they do not meet`}`, ok ? null : `${j.label}: geometry`, { code: 'join.geometry', at: A.at.map(r3), between: [A.at.map(r3), B.at.map(r3)], values, refs });
181
+ }
182
+ }
183
+ // the spring this join puts at a's end in a frame's solve: measured on the joint rig with its date, or an estimate
184
+ // until it is, and it says which
185
+ const k = m.stiffness;
186
+ if (k.bought) {
187
+ const set = k.bought.set, own = k.bought.own;
188
+ f('info', `${j.label}: taken as ${(k.bending / 1e6).toFixed(3)} N·m/mrad in bending and ${(k.twist / 1e6).toFixed(2)} N·m/mrad in twist at ${ai}'s end ${j.end}, ${own ? `${set}'s own figures from its rule set (${k.kind}: ${k.bought.rule})` : `the ${j.kind} join's ${k.measured?.bending ? 'figures' : 'estimate'}, as ${set} gives none`}: ${restsOn(k)}`, null,
189
+ { code: 'join.stiffness', values: { bending: k.bending, twist: k.twist }, refs: { ...refs, ...(j.fitted ? { item: j.fitted.item } : {}), set, kind_of_value: k.kind, measured: k.measured, end: k.end, rests: k.rests } });
190
+ continue;
191
+ }
192
+ if (k.fitting) {
193
+ const fm = k.fitting, shared = fm.shareKind === 'measured';
194
+ f('info', `${j.label}: taken as ${(k.bending / 1e6).toFixed(3)} N·m/mrad in bending, ${shared ? `${j.fitted.item}'s own by finite elements (${(fm.fe / 1e6).toFixed(3)}) times the ${+fm.share.toFixed(3)} a printed ${j.kind} join keeps of it, measured on the joint rig on ${k.measured.bending}` : `${j.fitted.item}'s own by finite elements`} (${fm.linear} N/mm at its screw under ${fm.load} N, ${fm.margin} times under its plastic's strength, ${fm.grams} g), and ${(k.twist / 1e6).toFixed(2)} N·m/mrad in twist at ${ai}'s end ${j.end}: ${shared ? `twist ${k.measured.twist ? `measured on the joint rig on ${k.measured.twist}` : 'an estimate until the rig measures it'}` : 'the slot nuts and lips are not in either, so both are an estimate of the joint until the joint rig (issue 264) measures it'}`, null,
195
+ { code: 'join.stiffness', values: { bending: k.bending, twist: k.twist }, refs: { ...refs, item: j.fitted.item, kind_of_value: shared && k.measured.twist ? 'measured' : 'estimate', measured: k.measured, end: k.end, rests: k.rests } });
196
+ continue;
197
+ }
198
+ f('info', `${j.label}: taken as ${(k.bending / 1e6).toFixed(2)} N·m/mrad in bending and ${(k.twist / 1e6).toFixed(2)} N·m/mrad in twist at ${ai}'s end ${j.end}${k.printed ? ', a printed fitting\'s share of a bought one\'s' : ''}${k.scale !== 1 ? `, scaled ${+k.scale.toFixed(2)}× for the profile's size` : ''}: ${restsOn(k)}`, null,
199
+ { code: 'join.stiffness', values: { bending: k.bending, twist: k.twist }, refs: { ...refs, kind_of_value: k.kind, measured: k.measured, end: k.end, rests: k.rests } });
200
+ }
201
+ dropChecks(s, f, worlds);
202
+ // every beam end joined or capped
203
+ const ends = covered(s), beams = s.objects.filter((o) => o.beam && !o.unplaced && ids.includes(o.id)), open = [];
204
+ for (const o of beams) for (const e of ['a', 'b']) if (!ends.has(`${o.id}.${e}`)) open.push(`${o.id}.${e}`);
205
+ if (open.length) f('warn', `${open.length} beam end${open.length > 1 ? 's are' : ' is'} neither joined nor capped: ${open.join(', ')}. Give each a join, or an item at the end (an end cap or a foot, ${'"at": "' + open[0] + '"'})`, `${open.length} open end${open.length > 1 ? 's' : ''}`, { code: 'join.end', values: { open: open.length }, refs: { ends: open } });
206
+ else f('pass', `every beam end is joined or capped (${beams.length * 2} ends)`, null, { code: 'join.end' });
207
+ }
208
+
209
+ /**
210
+ * join.drop: a beam held by one join at one end and by nothing else, a mass hung on it (on the beam, or on an item placed
211
+ * on it), is a cantilever from that join, as on the joint rig. Its drop under the mass is the beam's own bending and the
212
+ * join's turning: d = F L³ / (3 E I) + F L² / k, L from b's face to the load along the beam, E I the beam's across the
213
+ * load, k the join's bending spring. Each is a prediction cad measured takes (<beam>.drop=<mm>): the measured drop less
214
+ * the beam's own gives the join's spring, F L² / (d - F L³ / 3 E I), written to the rule the spring came from.
215
+ * @param {object} s a built assembly @param {Function} f the findings' sink @param {number[][]} worlds each item's place
216
+ */
217
+ function dropChecks(s, f, worlds) {
218
+ const loads = (s.motion.loads || []).map((l, i) => ({ ...l, at: s.a.loads?.[i]?.at })).filter((l) => l.mass != null), ids = s.motion.items.map((x) => x[0]);
219
+ if (!loads.length) return;
220
+ const items = s.a.items || [], G = s.motion.gravity, g = Math.hypot(...G) || 1, down = G.map((c) => c / g);
221
+ const pt = (W, p) => [0, 1, 2].map((r) => W[4 * r] * p[0] + W[4 * r + 1] * p[1] + W[4 * r + 2] * p[2] + W[4 * r + 3]);
222
+ const dir = (W, v) => [0, 1, 2].map((r) => W[4 * r] * v[0] + W[4 * r + 1] * v[1] + W[4 * r + 2] * v[2]);
223
+ for (const j of s.joins) {
224
+ const [id] = j.items, e = j.end[0], other = e === 'a' ? 'b' : 'a';
225
+ // held by this join alone: in no other join, as a or b
226
+ if (s.joins.some((x) => x !== j && x.items.includes(id))) continue;
227
+ const on = new Set([id, ...items.filter((it) => typeof it.at === 'string' && it.at.trim().startsWith(`${id}.`)).map((it) => it.id)]);
228
+ const mine = loads.filter((l) => on.has(ids[l.item]));
229
+ if (!mine.length) continue;
230
+ const beam = s.objects.find((o) => o.id === id)?.beam, W = worlds[ids.indexOf(id)], fig = beam?.figures, mat = beam?.material;
231
+ const E = mat?.modulus, Ix = fig?.inertiaX?.value, Iy = fig?.inertiaY?.value, k = j.model.stiffness.bending;
232
+ if (!(E > 0 && Ix > 0 && Iy > 0 && W)) { f('info', `${j.label}: ${id} hangs from this join alone, but its profile gives no second moments or its material no modulus, so its drop is not predicted`, null, { code: 'join.drop', refs: { join: j.index, beam: id } }); continue; }
233
+ const len = beam.length, root = pt(W, [0, 0, e === 'a' ? 0 : len]), tip = pt(W, [0, 0, e === 'a' ? len : 0]);
234
+ const u = [0, 1, 2].map((c) => (tip[c] - root[c]) / len), sx = dir(W, [1, 0, 0]), sy = dir(W, [0, 1, 0]);
235
+ for (const l of mine) {
236
+ const P = pt(worlds[l.item], [l.frame[3], l.frame[7], l.frame[11]]), L = [0, 1, 2].reduce((a, c) => a + (P[c] - root[c]) * u[c], 0);
237
+ const across = down.map((c, q) => c - u[q] * [0, 1, 2].reduce((a, r) => a + down[r] * u[r], 0)), share = Math.hypot(...across);
238
+ const F = l.mass * 9.80665 * share, dx = [0, 1, 2].reduce((a, c) => a + across[c] * sx[c], 0) / (share || 1), dy = [0, 1, 2].reduce((a, c) => a + across[c] * sy[c], 0) / (share || 1);
239
+ if (!(L > 0) || !(share > 1e-6)) continue;
240
+ const beamDrop = ((F * L ** 3) / (3 * E)) * (dx * dx / Iy + dy * dy / Ix), joinDrop = (F * L * L) / k, drop = beamDrop + joinDrop;
241
+ const rule = writesTo(j), name = `${id}.drop`, where = l.at ?? `${id}`;
242
+ const trust = restsOn(j.model.stiffness);
243
+ f('info', `${j.label}: ${id} hangs from it alone, so ${l.mass} kg at ${where}, ${mm(L)} mm out from ${j.items[1]}'s face, drops it ${n3(drop)} mm: ${n3(beamDrop)} mm the beam's own bending (E ${E} MPa, I ${Math.round(dx * dx > 0.5 ? Iy : Ix)} mm⁴) and ${n3(joinDrop)} mm the join turning on its ${(k / 1e6).toFixed(3)} N·m/mrad spring (${trust}). Measure it with a dial indicator and write it back: cad measured ${s.project}/${s.name} ${name}=<mm>, and the spring goes to ${rule.rule}`, null,
244
+ { code: 'join.drop', at: P.map(r3), values: { drop: n3(drop), beam: n3(beamDrop), join: n3(joinDrop), force: n3(F), arm: n3(L), bending: k },
245
+ predict: { name, figure: `drop of ${id} at ${where} under ${l.mass} kg`, value: n3(drop), unit: 'mm', rig: { force: F, arm: L, beam: beamDrop, spring: k, rule: rule.rule, per: rule.per, unit: rule.unit, what: rule.what, join: j.label } },
246
+ refs: { join: j.index, kind: j.kind, beam: id, rule: rule.rule } });
247
+ }
248
+ }
249
+ }
250
+ const n3 = (x) => +Number(x).toFixed(3);
251
+
252
+ // The rule a join's measured spring is written to, and what to multiply the spring by to get it: a bought fitting's own
253
+ // bending_stiffness; a printed fitting's share of its finite-element figure; else the kind's figure for a 20 mm profile
254
+ function writesTo(j) {
255
+ const k = j.model.stiffness, key = j.kind.replace(/-/g, '_');
256
+ if (k.bought) return { rule: `${k.bought.set}.bending_stiffness`, per: 1, unit: 'N mm/rad', what: `${k.bought.set}'s bending stiffness, holding a beam's end` };
257
+ if (k.fitting) return { rule: `joins.${key}_printed_share`, per: 1 / k.fitting.fe, unit: '', what: `a ${j.kind} join with a printed fitting, as a share of the fitting's own bending stiffness by finite elements (${(k.fitting.fe / 1e6).toFixed(3)} N·m/mrad for ${k.fitting.name})` };
258
+ return { rule: `joins.${key}_bending`, per: 1 / ((k.scale ?? 1) * (k.printed ? JOIN_SCALE.printed.value : 1)), unit: 'N mm/rad', what: `a ${j.kind} join's bending stiffness, for a 20 mm series profile` };
259
+ }
package/lib/list.mjs CHANGED
@@ -13,14 +13,14 @@ import path from 'node:path';
13
13
  import { volume } from './mesh.mjs';
14
14
  import { wiresFor } from './assembly.mjs';
15
15
  import { cutListOf, cutListData } from './beams.mjs';
16
- import { cutListText } from '@rulecad/frames';
16
+ import { cutListText, printedCost } from '@rulecad/frames';
17
17
 
18
18
  const n = (x, d = 1) => Number(x.toFixed(d));
19
19
 
20
20
  export function materialOf(project) {
21
21
  let name = 'pla';
22
22
  try { name = String(readJson(path.join(paths.project(project), 'project.json')).material || 'pla').toLowerCase().split(/\s/)[0]; } catch {}
23
- try { return { name, density: loadRuleSet(name).rules.density.value }; } catch { return { name, density: 1.25, assumed: true }; }
23
+ try { const set = loadRuleSet(name); return { name, density: set.rules.density.value, ...(set.rules.cost ? { cost: set.rules.cost } : {}) }; } catch { return { name, density: 1.25, assumed: true }; }
24
24
  }
25
25
 
26
26
  // Every printed thing in the assembly, once for each copy: its volume, grams and minutes
@@ -41,8 +41,9 @@ export function shoppingList(s) {
41
41
  const mat = materialOf(s.project), printed = printedParts(s), bought = new Map(), fasteners = new Map();
42
42
  for (const o of s.objects) if (o.bought && !o.unplaced) {
43
43
  // (a beam by its profile and length: one line for each length cut, lib/beams.mjs)
44
- const len = o.bought.length != null ? Number(o.bought.length.toFixed(2)) : null, key = `${o.bought.set}|${o.bought.variant ?? ''}|${len ?? ''}`;
45
- const line = bought.get(key) ?? { set: o.bought.set, variant: o.bought.variant, part: o.bought.part, ...(len != null ? { length: len } : {}), qty: 0, grams: o.bought.mass != null ? o.bought.mass * 1000 : null, items: [] };
44
+ // (a panel by its sheet and size: lib/panels.mjs)
45
+ const len = o.bought.length != null ? Number(o.bought.length.toFixed(2)) : null, size = o.bought.size ?? null, key = `${o.bought.set}|${o.bought.variant ?? ''}|${len ?? ''}|${size ?? ''}`;
46
+ const line = bought.get(key) ?? { set: o.bought.set, variant: o.bought.variant, part: o.bought.part, ...(len != null ? { length: len } : {}), ...(size ? { size } : {}), qty: 0, grams: o.bought.mass != null ? o.bought.mass * 1000 : null, ...(o.bought.cost ? { cost: o.bought.cost.value, currency: o.bought.cost.unit } : {}), items: [] };
46
47
  line.qty++; line.items.push(o.id); bought.set(key, line);
47
48
  }
48
49
  // fasten.count: the hardware a fasten placed (a component's too), one part a piece; a motor's mounting screws; and a fit
@@ -53,6 +54,8 @@ export function shoppingList(s) {
53
54
  let grams = null; try { grams = screwModel(m.thread, { length: m.length, head: m.head, anyLength: true }).mass; } catch {}
54
55
  add(m.name, m.count, `${m.item} on ${m.other} (its mount, a fit that fastens)`, { kind: 'screw', thread: m.thread, length: m.length, head: m.head, grams });
55
56
  }
57
+ // what a printed fitting takes besides its screws: a hinge's pin and its nut, a catch's magnet and strike (lib/fittings.mjs)
58
+ for (const o of s.objects) if (o.fitting?.hardware && !o.unplaced) for (const h of o.fitting.hardware) add(h.name, h.count ?? 1, `${o.id} (${h.why ?? 'its fitting'})`, { kind: h.kind, thread: h.thread ?? null, length: h.length ?? null, head: h.head ?? null, grams: null });
56
59
  for (const x of s.fits) if (x.fastener && x.fasten == null) add(x.fastener, x.count != null ? x.num(x.count) : 1, x.note || `${x.a} / ${x.b}`);
57
60
  // Rounded up to whole packs (packs.pack), the spares said
58
61
  let pack = null; try { const r = loadRuleSet('packs').rules.pack; pack = { size: r.value, rule: 'packs.pack', kind: r.kind }; } catch {}
@@ -64,13 +67,19 @@ export function shoppingList(s) {
64
67
  const printedGrams = printed.reduce((t, p) => t + p.grams, 0), boughtGrams = boughtList.reduce((t, b) => t + (b.grams ?? 0) * b.qty, 0), unknown = boughtList.filter((b) => b.grams == null).map((b) => b.set);
65
68
  const cut = cutListData(cutListOf(s));
66
69
  const fixingsGrams = fixings.reduce((t, f) => t + (f.mass ?? 0), 0);
67
- return { bought: boughtList, fasteners: fixings, wires: [...wires.values()], printed, cut, totals: { printedGrams: n(printedGrams), boughtGrams: n(boughtGrams), fixingsGrams: n(fixingsGrams), machineGrams: n(printedGrams + boughtGrams + fixingsGrams), ...(pack && fixings.some((f) => f.packs) ? { pack } : {}), minutes: n(printed.reduce((t, p) => t + p.minutes, 0), 0), material: mat.name, ...(mat.assumed ? { densityAssumed: true } : {}), ...(unknown.length ? { noMassFor: unknown } : {}) } };
70
+ // what it costs, where prices are given: the bought items' by their sets, the printed parts' plastic by the material's
71
+ // price a kilogram; fixings and bars are not priced, and the list says which lines have no price
72
+ const priced = boughtList.filter((b) => b.cost != null), currencies = [...new Set(priced.map((b) => b.currency))];
73
+ const plastic = printedGrams > 0 ? printedCost(printedGrams, { name: mat.name, rules: mat.cost ? { cost: mat.cost } : {} }) : null;
74
+ const cost = priced.length || plastic ? { bought: priced.length && currencies.length === 1 ? n(priced.reduce((t, b) => t + b.cost * b.qty, 0), 2) : null, currency: currencies.length === 1 ? currencies[0] : plastic?.unit ?? null, ...(currencies.length > 1 ? { currencies } : {}),
75
+ unpriced: [...new Set(boughtList.filter((b) => b.cost == null).map((b) => b.set))], printed: plastic ? n(plastic.value, 2) : null, ...(plastic ? { printedUnit: plastic.unit, printedRule: plastic.rule } : {}) } : null;
76
+ return { bought: boughtList, fasteners: fixings, wires: [...wires.values()], printed, cut, ...(cost ? { cost } : {}), totals: { printedGrams: n(printedGrams), boughtGrams: n(boughtGrams), fixingsGrams: n(fixingsGrams), machineGrams: n(printedGrams + boughtGrams + fixingsGrams), ...(pack && fixings.some((f) => f.packs) ? { pack } : {}), minutes: n(printed.reduce((t, p) => t + p.minutes, 0), 0), material: mat.name, ...(mat.assumed ? { densityAssumed: true } : {}), ...(unknown.length ? { noMassFor: unknown } : {}) } };
68
77
  }
69
78
 
70
79
  export function listText(ref, l) {
71
80
  const out = [`${ref}: what it takes to build`];
72
81
  const row = (a) => out.push(a.join(' '));
73
- if (l.bought.length) { out.push('', 'Bought'); for (const b of l.bought) row([` ${String(b.qty).padStart(3)} ×`, `${b.set}${b.variant ? ` (${b.variant})` : ''}${b.length != null ? ` x ${b.length} mm` : ''}`, `a ${b.part}`, b.grams != null ? `${b.grams} g each` : 'mass not given', b.items.join(', ')]); }
82
+ if (l.bought.length) { out.push('', 'Bought'); for (const b of l.bought) row([` ${String(b.qty).padStart(3)} ×`, `${b.set}${b.variant ? ` (${b.variant})` : ''}${b.length != null ? ` x ${b.length} mm` : ''}${b.size ? ` cut ${b.size[0]} x ${b.size[1]} mm` : ''}`, `a ${b.part}`, b.grams != null ? `${b.grams} g each` : 'mass not given', ...(b.cost != null ? [`${b.cost} ${b.currency} each`] : []), b.items.join(', ')]); }
74
83
  if (l.cut) { out.push('', `Cut list (kerf ${l.cut.rules.kerf.value} mm, trim ${l.cut.rules.trim.value} mm; a sheet for each mark: cad beams ${ref})`, ...cutListText(l.cut)); }
75
84
  if (l.fasteners.length) {
76
85
  out.push('', 'Fasteners');
@@ -80,5 +89,12 @@ export function listText(ref, l) {
80
89
  if (l.wires.length) { out.push('', 'Wire'); for (const w of l.wires) row([` ${w.length} mm of`, w.gauge ?? 'gauge not given', `in ${w.runs.join(', ')}`]); }
81
90
  if (l.printed.length) { out.push('', `Printed (${l.totals.material})`); for (const p of l.printed) row([` ${String(p.grams).padStart(7)} g`, `about ${p.minutes} min`, `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}`]); }
82
91
  out.push('', `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.fixingsGrams ? `${l.totals.fixingsGrams} g of fixings, ` : ''}${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`);
92
+ if (l.cost) {
93
+ const c = l.cost, parts = [];
94
+ if (c.bought != null) parts.push(`${c.bought} ${c.currency} bought${c.unpriced.length ? ` (no price given for ${c.unpriced.join(', ')})` : ''}`);
95
+ else if (c.currencies) parts.push(`bought items priced in ${c.currencies.join(' and ')}, not added together`);
96
+ if (c.printed != null) parts.push(`${c.printed} ${c.printedUnit} of ${l.totals.material} printed (the plastic alone)`);
97
+ out.push(`Cost: ${parts.join(', ')}; fixings and bars are not priced. Prices are each set's, on the date it was checked`);
98
+ }
83
99
  return out.join('\n');
84
100
  }