@rulecad/cad 0.7.56 → 0.7.58

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,111 @@
1
+ // Generated frames in assemblies (@rulecad/frames' generate.mjs): "frame": { "kind": "box", "inside": [300, 300, 350],
2
+ // "profile": "2020-misumi-hfs5", "join": "blind", "feet": "levelling" } at the top of an assembly expands, before
3
+ // anything else is worked out, into beam items placed by their ends, joins, the fittings at the ends no join covers,
4
+ // panels where asked and, for a gantry, its moving beam on a sliding joint with a pose at each end of its travel. The
5
+ // expansion is what the rest of cad sees, so its joins, fastens, cut list and frame checks are a hand-drawn frame's.
6
+ // cad frame <project>/<assembly> --expand writes it into the assembly, where it can be edited by hand.
7
+ import { frameModel, FRAME_KINDS } from '@rulecad/frames';
8
+ import { beamPlace, framesContext } from './beams.mjs';
9
+ import { givenFor } from './frames.mjs';
10
+
11
+ /** The keys of "frame" that ask for a generated frame; the rest (supports, limit, rack ..) say how it is solved. */
12
+ export const FRAME_GEN_KEYS = ['kind', 'inside', 'outside', 'profile', 'join', 'feet', 'caps', 'braces', 'panels', 'shelves'];
13
+ const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
14
+ const r3 = (x) => +x.toFixed(3);
15
+
16
+ /**
17
+ * The frame an assembly asks for, worked out: @rulecad/frames' frameModel over its expressions and the workspace's
18
+ * profile sets. Null where "frame" names no kind. Refused by name: generator keys without a kind, and what frameModel
19
+ * refuses. @param {object} a the assembly as read @param {(x: any) => number} num its expressions
20
+ * @returns {object | null}
21
+ */
22
+ export function frameOf(a, num, context = framesContext()) {
23
+ const f = a.frame;
24
+ if (!f || typeof f !== 'object' || Array.isArray(f)) return null;
25
+ if (f.kind == null) {
26
+ const stray = FRAME_GEN_KEYS.filter((k) => f[k] != null);
27
+ if (stray.length) throw new Error(`frame: ${stray.join(', ')} ask${stray.length === 1 ? 's' : ''} for a generated frame, and it names no kind: give "kind": ${Object.keys(FRAME_KINDS).join(', ')}`);
28
+ return null;
29
+ }
30
+ const o = {};
31
+ for (const k of FRAME_GEN_KEYS.slice(1)) if (f[k] != null) o[k] = f[k];
32
+ for (const k of ['inside', 'outside']) if (o[k] != null) { if (!Array.isArray(o[k])) throw new Error(`frame: ${k} is [width, depth, height] in mm (got ${shown(o[k])})`); o[k] = o[k].map((x) => num(x)); }
33
+ if (o.panels?.thickness != null) o.panels = { ...o.panels, thickness: num(o.panels.thickness) };
34
+ let m;
35
+ try { m = frameModel(f.kind, { ...o, given: givenFor(context, f.profile) }); } catch (e) { throw new Error(`frame: ${String(e.message).replace(/^frameModel: /, '')}`); }
36
+ // a portal lies in one plane: standing on its two feet, a foot holds an upright's end from moving and not from turning,
37
+ // so nothing holds it out of that plane and it tips over sideways under any load. It checks clean once its feet are
38
+ // held down (bolted to a bench or a wall), so where nothing says how it is held, it is refused here, before any check
39
+ if (m.kind === 'portal' && f.supports == null) {
40
+ const feet = m.beams.filter((b) => Math.min(b.from[2], b.to[2]) < 1e-6).map((b) => `"${b.id}.${b.from[2] <= b.to[2] ? 'a' : 'b'}": "fixed"`);
41
+ throw new Error(`frame: a portal stands in one plane (x-z) on its two feet, and a foot stops an upright's end moving but not turning, so nothing holds the portal out of that plane: on its feet alone it tips over sideways (frame.buckling fails it, frame.rack finds it free along y). Say how its feet are held down, bolted to a bench or a wall: "supports": { ${feet.join(', ')} }; or, to stand free, generate a table or a box`);
42
+ }
43
+ return m;
44
+ }
45
+
46
+ /**
47
+ * The items, joins, joint and poses a generated frame adds, in the assembly's own words.
48
+ * @param {object} m frameOf's @param {object} a the assembly @param {(x: any) => number} num
49
+ * A printed foot is screwed into its upright's end: the end tapped (the beam's ops) and a fasten of the foot's screw.
50
+ * @returns {{ items: object[], joins: object[], fasten: object[], joints: object[], poses: Record<string, object> | null }}
51
+ */
52
+ export function frameParts(m, a, num) {
53
+ const profile = m.profile, items = [], fasten = [];
54
+ for (const b of m.beams) items.push({ id: b.id, beam: { profile }, from: b.from, to: b.to });
55
+ for (const e of m.ends) {
56
+ items.push(e.fitting ? { id: e.id, fitting: { kind: e.fitting, profile }, at: e.at } : { id: e.id, bought: e.bought, at: e.at });
57
+ if (!e.tap) continue;
58
+ const [beamId] = e.at.split('.'), bi = items.find((x) => x.id === beamId);
59
+ bi.beam.ops = [...(bi.beam.ops ?? []), { ...e.tap }];
60
+ fasten.push({ screw: e.screw, through: [e.id], into: beamId, at: [`${e.id}.b1`], note: `${e.id} screwed into ${beamId}'s end ${e.tap.at}` });
61
+ }
62
+ for (const p of m.panels) items.push({ id: p.id, panel: { sheet: p.sheet, thickness: p.thickness, bay: p.bay, out: p.out, nut: p.nut } });
63
+ const joints = [];
64
+ let poses = null;
65
+ if (m.moving) {
66
+ // the moving beam on a sliding joint from its track's top face: both anchors where g's bottom meets the track at the
67
+ // start of its travel, z along the travel, x up, so g lies with its top up and its length across
68
+ const g = m.moving, track = items.find((x) => x.id === g.track), F = beamPlace(track, num), h = m.width / 2;
69
+ const col = (k) => [F[k], F[4 + k], F[8 + k]], o = [F[3], F[7], F[11]], dot = (u, v) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
70
+ const local = (v, point = true) => { const d = point ? v.map((c, k) => c - o[k]) : v; return [0, 1, 2].map((k) => r3(dot(col(k), d))); };
71
+ const meet = [track.from[0], g.from[1], g.from[2] - h];
72
+ items.splice(m.beams.length, 0, { id: g.id, beam: { profile, length: g.length } });
73
+ joints.push({ id: 'gantry', type: 'prismatic', parent: { item: track.id, at: local(meet), axis: local(g.along, false), ref: local([0, 0, 1], false) }, child: { item: g.id, at: [0, -h, r3(track.from[0] - g.from[0])], axis: [1, 0, 0], ref: [0, 1, 0] }, min: 0, max: g.travel, label: 'Gantry' });
74
+ poses = { 'gantry-front': { gantry: 0 }, 'gantry-back': { gantry: g.travel } };
75
+ }
76
+ return { items, joins: m.joins.map((j) => ({ ...j })), fasten, joints, poses };
77
+ }
78
+
79
+ /**
80
+ * An assembly with its generated frame expanded: the frame's items before its own, its joins before its own, a
81
+ * gantry's joint and poses, and "frame" left with only how it is solved. Refused by name: an item of the assembly's
82
+ * own with a name the frame gives (z1, x1, cap-z1-b ..).
83
+ * @param {object} a @param {(x: any) => number} num
84
+ * @returns {{ a: object, frame: object | null }} the assembly as expanded, and frameOf's model
85
+ */
86
+ export function expandFrame(a, num, context = framesContext()) {
87
+ const m = frameOf(a, num, context);
88
+ if (!m) return { a, frame: null };
89
+ const parts = frameParts(m, a, num), own = new Set((a.items || []).map((it) => it?.id));
90
+ const clash = parts.items.filter((it) => own.has(it.id)).map((it) => it.id);
91
+ if (clash.length) throw new Error(`frame: the ${m.kind} names its parts ${parts.items.slice(0, 3).map((x) => x.id).join(', ')} .., and this assembly already has ${clash.join(', ')}: rename ${clash.length > 1 ? 'them' : 'it'}, or write the frame out (cad frame --expand) and edit it there`);
92
+ if (parts.joints.length && (a.joints || []).some((j) => j.id === 'gantry')) throw new Error('frame: a gantry\'s moving beam slides on a joint named gantry, and this assembly already has one: rename it');
93
+ const rest = Object.fromEntries(Object.entries(a.frame).filter(([k]) => !FRAME_GEN_KEYS.includes(k)));
94
+ const out = { ...a, items: [...parts.items, ...(a.items || [])], joins: [...parts.joins, ...(a.joins || [])] };
95
+ if (parts.fasten.length) out.fasten = [...parts.fasten, ...(a.fasten || [])];
96
+ if (parts.joints.length) out.joints = [...parts.joints, ...(a.joints || [])];
97
+ if (parts.poses && !a.poses) out.poses = parts.poses;
98
+ if (Object.keys(rest).length) out.frame = rest; else delete out.frame;
99
+ return { a: out, frame: m };
100
+ }
101
+
102
+ /** The frame in words: its size, its beams by length, its joins and its ends. @param {object} m frameOf's @returns {string[]} */
103
+ export function frameText(m) {
104
+ const s = (v) => v.map((x) => +x.toFixed(2)).join(' x ');
105
+ const size = m.kind === 'portal' ? (v) => s([v[0], v[2]]) : s;
106
+ const lines = [`a ${m.kind} of ${m.profile} (${m.width} mm), joined ${m.join.kind}${m.join.fitting ? ` (${m.join.fitting})` : ''}: ${m.arrangement === 'face' ? 'the upright beams run through and the rest butt against their faces' : 'every beam butts into a corner node'}`,
107
+ `inside ${size(m.inside)} mm, outside ${size(m.outside)} mm${m.shelves ? `; ${m.shelves} shelves, each bay ${+m.bay.toFixed(2)} mm clear` : ''}${m.lift ? `; the bottom ring stands ${+m.lift.toFixed(2)} mm up the uprights, so its joins' holes clear the feet's tapped ends` : ''}`];
108
+ for (const l of m.lengths) lines.push(` ${l.count} x ${+l.length.toFixed(2)} mm: ${l.ids.join(', ')}`);
109
+ lines.push(`${m.joins.length} joins (${[...new Set(m.joins.map((j) => j.kind))].join(', ')}); ${m.ends.length} end fittings${m.ends.length ? ` (${[...new Set(m.ends.map((e) => e.fitting ?? e.bought))].join(', ')})` : ''}${m.panels.length ? `; ${m.panels.length} panels` : ''}${m.moving ? `; g rides ${m.moving.track} through ${m.moving.travel} mm on the joint gantry` : ''}`);
110
+ return lines;
111
+ }
@@ -0,0 +1,94 @@
1
+ // frame.heat: a frame that runs warm. Its beams grow with the air round them by their alloy's expansion, so a frame
2
+ // squared and measured at the workshop's temperature is larger when it runs in a warm enclosure; and each printed
3
+ // fitting is held to its plastic's softening point (the heat deflection temperature its set gives), at the air's
4
+ // temperature or at a heater's where it is within that heater's reach.
5
+ // "frame": { "heat": { "air": 45, "built": 20, "heaters": [{ "name": "bed", "at": [150, 150, 60], "temperature": 60, "reach": 40 }] } }
6
+ // Growth: ΔL = α L ΔT, with ΔT = air - built, for each beam and for the frame's extent each way.
7
+ import { placeItems } from '@rulecad/model-link';
8
+ import { peekRuleSet } from './rules.mjs';
9
+
10
+ const n3 = (x, d = 3) => String(Number(Number(x).toFixed(d)));
11
+ const shown = (v) => JSON.stringify(v) ?? String(v);
12
+
13
+ /** The working figures of frame.heat, each with what it rests on. */
14
+ export const FRAME_HEAT = {
15
+ expansion: { value: 23.4e-6, unit: '1/K', rule: 'How much an aluminium beam grows for each degree it warms, a share of its length, where its alloy\'s set gives no expansion: the figure for 6063, taken for the 6000 series extrusions the profiles are made of', kind: 'community', source: '6063 aluminium alloy, Wikipedia\'s table (2.34e-5 /K); 6063-T5 suppliers\' sheets give 23.4 µm/m °C over 20 to 100 °C (Alliance, Aerospace Metals) and Hydro\'s EN AW-6063 sheet 23.5, found by search and not each opened', checked: '2026-11-17' },
16
+ built: { value: 20, unit: '°C', rule: 'The air a frame is built, squared and measured in, where the assembly does not say', kind: 'default', source: 'A working figure of @rulecad/cad: a room', checked: '2026-11-17' },
17
+ margin: { value: 10, unit: '°C', rule: 'A printed fitting within this many degrees under its plastic\'s softening point is warned of: the heat deflection temperature is measured under a light load (0.45 MPa), and a fitting under its working load creeps sooner', kind: 'estimate', source: 'A working figure of @rulecad/cad, without a test behind it', checked: '2026-11-17' },
18
+ };
19
+
20
+ // frame.heat as written, checked by name: null where it is not given
21
+ function heatOf(s) {
22
+ const h = s.a.frame?.heat;
23
+ if (h == null) return null;
24
+ if (typeof h !== 'object' || Array.isArray(h)) throw new Error(`frame.heat is { "air": 45, "built": 20, "heaters": [...] }: degrees C (got ${shown(h)})`);
25
+ for (const k of Object.keys(h)) if (!['air', 'built', 'heaters'].includes(k)) throw new Error(`frame.heat has no "${k}": it takes air, built and heaters`);
26
+ const deg = (v, what) => { const x = s.num(v); if (!(Number.isFinite(x) && x > -100 && x < 500)) throw new Error(`frame.heat.${what} is a temperature in degrees C (got ${shown(v)})`); return x; };
27
+ const air = h.air != null ? deg(h.air, 'air') : null, built = h.built != null ? deg(h.built, 'built') : FRAME_HEAT.built.value;
28
+ if (h.heaters != null && !Array.isArray(h.heaters)) throw new Error(`frame.heat.heaters is a list of { name, at, temperature, reach } (got ${shown(h.heaters)})`);
29
+ const heaters = (h.heaters ?? []).map((x, i) => {
30
+ const what = `frame.heat.heaters ${i + 1}`;
31
+ if (!x || typeof x !== 'object' || !Array.isArray(x.at) || x.at.length !== 3) throw new Error(`${what} is { name, at: [x, y, z], temperature, reach } (got ${shown(x)})`);
32
+ const reach = s.num(x.reach);
33
+ if (!(reach > 0)) throw new Error(`${what}: reach is how far from its middle a part is taken at its temperature, mm above 0 (got ${shown(x.reach)})`);
34
+ return { name: x.name ?? `heater ${i + 1}`, at: x.at.map((v) => s.num(v)), temperature: deg(x.temperature, `heaters ${i + 1}.temperature`), reach };
35
+ });
36
+ if (air == null && !heaters.length) throw new Error('frame.heat gives neither air nor heaters: give the air round the frame when it runs ("air": 45), a heater, or both');
37
+ return { air, built, heaters, airGiven: air != null };
38
+ }
39
+
40
+ // The nearest point of an item's drawn parts to a point, and how far: its bounding box as drawn
41
+ function nearest(s, id, P) {
42
+ const tri = s.parts.filter((p) => p.item === id).flatMap((p) => p.triangles ?? []).flat();
43
+ if (!tri.length) return null;
44
+ const lo = [0, 1, 2].map((k) => Math.min(...tri.map((v) => v[k]))), hi = [0, 1, 2].map((k) => Math.max(...tri.map((v) => v[k])));
45
+ return Math.hypot(...[0, 1, 2].map((k) => Math.max(lo[k] - P[k], 0, P[k] - hi[k])));
46
+ }
47
+
48
+ /**
49
+ * frame.heat on a built assembly: the beams' growth from built to running air, and each printed fitting's temperature
50
+ * against its plastic's softening point. Nothing where frame.heat is not given. @param {object} s @param {Function} f
51
+ */
52
+ export function frameHeatChecks(s, f) {
53
+ let h;
54
+ try { h = heatOf(s); } catch (e) { f('fail', e.message, 'frame.heat: refused', { code: 'frame.heat' }); return; }
55
+ if (!h) return;
56
+ // the beams grow
57
+ const beams = s.objects.filter((o) => o.beam && !o.unplaced);
58
+ if (beams.length && h.airGiven) {
59
+ const placed = placeItems(s.motion, s.jointValues), at = Object.fromEntries(s.motion.items.map((x, i) => [x[0], placed[i]])), dT = h.air - h.built, ends = [];
60
+ const rows = beams.map((o) => {
61
+ const W = at[o.id], m = o.beam.material ?? o.beam.profile.material, own = m?.figures?.expansion?.value, alpha = typeof own === 'number' ? own : FRAME_HEAT.expansion.value;
62
+ if (W) { const A = [W[3], W[7], W[11]], d = [W[2], W[6], W[10]]; ends.push(A, A.map((x, k) => x + d[k] * o.beam.length)); }
63
+ return { id: o.id, length: o.beam.length, alpha, from: typeof own === 'number' ? `${m.name}.expansion` : 'FRAME_HEAT.expansion', grows: alpha * o.beam.length * dT };
64
+ });
65
+ const alpha = Math.max(...rows.map((x) => x.alpha)), size = [0, 1, 2].map((k) => (ends.length ? Math.max(...ends.map((p) => p[k])) - Math.min(...ends.map((p) => p[k])) : 0)), grows = size.map((x) => alpha * x * dT);
66
+ const most = rows.reduce((a, b) => (Math.abs(b.grows) > Math.abs(a.grows) ? b : a)), kinds = [...new Set(rows.map((x) => x.from))];
67
+ f('info', `at ${n3(h.air, 1)} °C the frame is ${n3(Math.abs(dT), 1)} °C ${dT >= 0 ? 'warmer' : 'cooler'} than the ${n3(h.built, 1)} °C it was built in, so it ${dT >= 0 ? 'grows' : 'shrinks'} by ${size.map((x, k) => (x > 1e-6 ? `${n3(Math.abs(grows[k]), 3)} mm over the ${n3(x, 0)} mm its beams span in ${'xyz'[k]}` : null)).filter(Boolean).join(', ')}; the longest beam, ${most.id} (${n3(most.length, 0)} mm), by ${n3(Math.abs(most.grows), 3)} mm. A frame of one alloy grows alike every way, so it stays square; a rail or rod of another metal on it grows by its own figure, and the difference bows or slides it`,
68
+ null, { code: 'frame.heat', values: { air: h.air, built: h.built, change: dT, expansion: alpha, size: size.map((x) => +x.toFixed(2)), grows: grows.map((x) => +x.toFixed(4)), beams: rows.map((x) => ({ id: x.id, grows: +x.grows.toFixed(4) })) }, refs: { expansion: kinds, built: s.a.frame.heat.built != null ? 'frame.heat.built' : 'FRAME_HEAT.built' } });
69
+ }
70
+ // each printed fitting against its plastic's softening point
71
+ const rows = [];
72
+ for (const o of s.objects) {
73
+ if (!o.fitting || o.unplaced || o.fitting.bought) continue;
74
+ const mat = o.fitting.material ?? 'pla';
75
+ let soft = null; try { soft = peekRuleSet(mat).rules?.softening ?? null; } catch {}
76
+ let temp = h.air ?? h.built, by = h.airGiven ? 'the air' : 'the room', near = null;
77
+ for (const x of h.heaters) { const d = nearest(s, o.id, x.at); if (d != null && d <= x.reach && x.temperature > temp) { temp = x.temperature; by = `${x.name}, ${n3(d, 1)} mm away`; near = x.name; } }
78
+ rows.push({ id: o.id, fitting: o.fitting.name, mat, soft, temp, by, near });
79
+ }
80
+ const margin = FRAME_HEAT.margin.value, out = [];
81
+ for (const r of rows) {
82
+ if (typeof r.soft?.value !== 'number') { f('info', `${r.id}: ${r.mat} gives no softening point, so ${n3(r.temp, 1)} °C (${r.by}) is not checked against it: give its set a softening rule`, null, { code: 'frame.heat', refs: { item: r.id, material: r.mat } }); continue; }
83
+ const spare = r.soft.value - r.temp, level = spare <= 0 ? 'fail' : spare < margin ? 'warn' : 'pass';
84
+ const x = { ...r, spare, level };
85
+ if (level === 'pass') { out.push(x); continue; }
86
+ f(level, `${r.id} (${r.fitting}, ${r.mat.toUpperCase()}) works at ${n3(r.temp, 1)} °C (${r.by}), ${level === 'fail' ? `${n3(-spare, 1)} °C over` : `only ${n3(spare, 1)} °C under`} its ${n3(r.soft.value, 1)} °C softening point (${r.soft.rule.split(':')[0]}): it ${level === 'fail' ? 'softens and creeps under its load' : 'creeps under its load sooner than the figure says'}. Print it in a plastic that softens higher, or move it from the heat`,
87
+ `${r.id}: ${level === 'fail' ? 'too hot' : 'near softening'}`, { code: 'frame.heat', values: { temperature: r.temp, softening: r.soft.value, spare: +spare.toFixed(2), margin }, refs: { item: r.id, material: r.mat, heater: r.near, softening: `${r.mat}.softening`, rule: r.soft.kind } });
88
+ }
89
+ if (out.length) {
90
+ const low = out.reduce((a, b) => (b.spare < a.spare ? b : a));
91
+ f('pass', `${out.length === rows.length ? (out.length > 1 ? 'every printed fitting' : 'its printed fitting') : `${out.length} printed fitting${out.length > 1 ? 's' : ''}`} stay${out.length > 1 && out.length !== rows.length ? '' : 's'} at least ${margin} °C under its plastic's softening point: the nearest is ${low.id} (${low.mat.toUpperCase()}), ${n3(low.temp, 1)} °C (${low.by}) against ${n3(low.soft.value, 1)} °C`, null,
92
+ { code: 'frame.heat', values: { fittings: out.length, spare: +low.spare.toFixed(2), margin }, refs: { item: low.id, items: out.map((x) => x.id), softening: `${low.mat}.softening` } });
93
+ }
94
+ }
@@ -0,0 +1,277 @@
1
+ // Printed beams in a frame: which beams of a frame could be printed in a plastic, and the beam coupon's predictions.
2
+ //
3
+ // beam.printable. With "frame": { "printed": "petg" } (or { material, walls, infill }), each beam of the solved frame
4
+ // is tried printed in that plastic: the kit's printable profile of its size (profile-2020-printed for a 20 mm square
5
+ // beam), lying down (spliced where it is longer than the bed, its strength then PRINTED_DEFAULTS.splice_share of the
6
+ // whole beam's) and standing up where it fits the printer's height, its section and modulus those printing gives it
7
+ // (@rulecad/frames printedOf: walls and infill, the plastic's figures for its pose, or the beam coupon's where
8
+ // measured). The frame is solved again with that one beam printed, every other beam as it is, and the printed beam is
9
+ // held to the limits the frame's own checks use: every sag (each load's point, each named point, each guide and the
10
+ // beam along its length) against its limit; its stress against its plastic's strength with twice the margin; Euler's
11
+ // load with twice the margin; its sustained stress against the creep limit (beam.creep); its sag as it creeps (the
12
+ // frame solved again with the beam's modulus at PRINTED_DEFAULTS.creep_modulus of it) against the same limits; and
13
+ // where the task's moves excite the frame, its lowest mode at twice their rate. A sag the frame as drawn already misses
14
+ // (frame.deflection fails there in the beams' own material) is no fault of printing: there the printed beam is held to
15
+ // the drawn frame's own sag, within DRAWN_SLACK of it (the kit's choice), so it fails only where printing it makes that
16
+ // sag worse, and the findings name each such point. Each is a margin, 1 where it just
17
+ // holds; the least is the beam's. Those that pass alone are then printed together and solved once more, and any that
18
+ // fail together are put back to the beam's own material, the one that misses most first. Every figure rests on the
19
+ // printed section's estimates (walls, infill, creep) until the beam coupon is measured, and on the joins' springs as
20
+ // they are (estimates made for metal beams): each finding says so.
21
+ //
22
+ // beam.coupon. A printed beam held only by two supports of "frame": { "supports" } with a mass on it is the beam
23
+ // coupon: its sag under the mass, and the mass it breaks at, are predictions cad measured takes (<beam>.sag=<mm>,
24
+ // <beam>.break=<kg>), and the figure measured goes to the plastic's set: the modulus a printed beam bends at
25
+ // (beam_modulus, or beam_modulus_z for one printed standing up) and the stress it breaks at (beam_strength, _z).
26
+ // Units: mm, N, N·mm, MPa, kg.
27
+ import { frame as solveFrame, subdivide } from '@rulecad/fea/frame';
28
+ import { PRINTED_SERIES, PRINTED_DEFAULTS, JOINS, beamCreep, printerFigures } from '@rulecad/frames';
29
+ import { beamOf } from './beams.mjs';
30
+
31
+ const G = 9.80665;
32
+ 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]];
33
+ const add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]], scale = (a, k) => [a[0] * k, a[1] * k, a[2] * k];
34
+ const n3 = (x, d = 3) => String(+Number(x).toFixed(d)), r3 = (x) => (x == null || !Number.isFinite(x) ? null : +Number(x).toFixed(3)), r4 = (p) => p.map((x) => +Number(x).toFixed(3));
35
+ const fig = (x) => String(+Number(x).toPrecision(3));
36
+ const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
37
+ const PRINT_KEYS = ['material', 'walls', 'infill', 'pose'];
38
+ const DRAWN_SLACK = 0.02; // a printed beam may add 2% to a sag the frame as drawn already misses (the kit's choice, so that a beam far from it is not blamed for it)
39
+ const said = { deflection: 'its sag', stress: 'its stress', buckling: 'buckling', creep: 'its sustained stress (creep)', creepSag: 'its sag as it creeps', frequency: 'its lowest mode' };
40
+
41
+ /**
42
+ * The frame's "printed" option held to its shape: the plastic every beam is tried in, by name ("petg"), or
43
+ * { material, walls, infill, pose }. Undefined passes (the check is not asked for). Refused by name.
44
+ * @param {any} x @returns {{ material: string, walls?: number, infill?: number, pose?: 'lying' | 'standing' } | null}
45
+ */
46
+ export function printedOption(x) {
47
+ if (x == null) return null;
48
+ const o = typeof x === 'string' ? { material: x } : x;
49
+ if (!o || typeof o !== 'object' || Array.isArray(o)) throw new Error(`frame.printed is the plastic each beam is tried printed in, "petg", or { "material": "petg", "walls": 3, "infill": 0.4, "pose": "lying" } (got ${shown(x)})`);
50
+ for (const k of Object.keys(o)) if (!PRINT_KEYS.includes(k)) throw new Error(`frame.printed has no "${k}": it takes ${PRINT_KEYS.join(', ')}`);
51
+ if (typeof o.material !== 'string' || !o.material) throw new Error(`frame.printed.material names a plastic's set, such as pla or petg (got ${shown(o.material)})`);
52
+ if (o.pose != null && !['lying', 'standing'].includes(o.pose)) throw new Error(`frame.printed.pose is lying or standing, or left out to try both (got ${shown(o.pose)})`);
53
+ return o;
54
+ }
55
+
56
+ // each element's start along its beam, as sagAlong reads it
57
+ function stamp(fm, model, res) {
58
+ for (const e of res.elements) if (e.of != null) { const b = fm.beams.get(e.of), el = model.elements.find((q) => q.id === e.id); e._from = dot(sub(fm.nodes[el.a], b.A), b.u); }
59
+ return res;
60
+ }
61
+
62
+ // A beam of the frame as a printed one in a pose: its model from the printable profile of its size (or itself, where
63
+ // it is printed already), and the figures the solve takes. Null with why where it cannot be.
64
+ function candidate(b, opts, pose, cache) {
65
+ let pm, profile;
66
+ if (b.m.printed) { if (pose !== b.m.printed.pose) return null; pm = b.m; profile = b.m.profile.name; }
67
+ else {
68
+ const w = b.m.profile.width, h = b.m.profile.height;
69
+ if (!(Math.abs(w - h) < 1e-6 && PRINTED_SERIES[w])) return { why: `${b.id} is a ${fig(w)} x ${fig(h)} mm section, and the kit prints square ones of ${Object.keys(PRINTED_SERIES).join(', ')} mm (profile-2020-printed and its like)` };
70
+ profile = `profile-${w}${w}-printed`;
71
+ const printed = { pose, ...(opts.walls != null ? { walls: opts.walls } : {}), ...(opts.infill != null ? { infill: opts.infill } : {}) };
72
+ const key = `${profile}|${n3(b.L)}|${pose}`;
73
+ if (!cache.has(key)) cache.set(key, beamOf({ id: b.id, beam: { profile, length: b.L, material: opts.material, printed } }, (x) => x).model);
74
+ pm = cache.get(key);
75
+ }
76
+ const P = printerFigures('frame.printed', null), bed = pm.printed.bed, height = P.n('bed');
77
+ if (pose === 'standing' && b.L > height + 1e-9) return null;
78
+ const spliced = pose === 'lying' && b.L > bed + 1e-9, F = pm.figures, E = pm.material.modulus, nu = pm.profile.material?.poisson ?? 0.36;
79
+ const share = spliced ? PRINTED_DEFAULTS.splice_share.value : 1, A = F.area.value;
80
+ return { b, pm, pose, spliced, profile, E, strength: pm.printed.strength * share, creepLimit: pm.printed.creep.limit * share, grams: pm.mass,
81
+ section: { A, Iy: F.inertiaX.value, Iz: F.inertiaY.value, J: F.torsion.value, Wy: F.modulusX.value, Wz: F.modulusY.value },
82
+ material: { E, G: E / (2 * (1 + nu)), density: pm.mass > 0 ? (pm.mass / 1000 / b.L) / (A * 1e-6) : 0 } };
83
+ }
84
+
85
+ // The frame's model with these beams printed (and their modulus times k, for creep)
86
+ const swapped = (base, cands, k = 1) => ({ ...base, sections: { ...base.sections, ...Object.fromEntries(cands.map((c) => [c.b.id, c.section])) },
87
+ materials: { ...base.materials, ...Object.fromEntries(cands.map((c) => [c.b.id, { ...c.material, E: c.material.E * k, G: c.material.G * k }])) } });
88
+
89
+ // a beam's own sag along its length, as a target
90
+ const alongOf = (b, ctx) => ({ what: `${b.id} along its length`, beam: b, from: 0, to: b.L, limit: ctx.limitFor(b, null) });
91
+
92
+ // The frame as drawn (no beam printed): its sag at every target, and each beam along its length, in every case, keyed
93
+ // "what|case". Where one is past its limit the frame already misses it, printed or not.
94
+ function drawnSags(fm, ctx, targets) {
95
+ const solver = solveFrame(fm.model), out = new Map(), all = [...targets, ...[...fm.beams.values()].map((b) => alongOf(b, ctx))];
96
+ for (const cs of fm.cases) {
97
+ const res = stamp(fm, fm.model, solver.statics({ loads: fm.nodeLoads(cs.values) }));
98
+ for (const t of all) out.set(`${t.what}|${cs.label}`, t.node ? ctx.sagAt(res, t.node(cs.values), fm.down) : ctx.sagAlong(res, t.beam, t.from, t.to, fm.down).sag);
99
+ }
100
+ const missed = [];
101
+ for (const t of all) { let worst = 0; for (const cs of fm.cases) worst = Math.max(worst, out.get(`${t.what}|${cs.label}`)); if (worst > t.limit.value + 1e-12) missed.push({ what: t.what, sag: worst, limit: t.limit }); }
102
+ return { sags: out, missed };
103
+ }
104
+
105
+ /**
106
+ * Every margin of a frame with these beams printed, each 1 where it just holds: the sags against their limits (and
107
+ * each printed beam along its length), as it creeps too; per printed beam its stress, Euler's load and its sustained
108
+ * stress; and the lowest mode against the task's moves.
109
+ */
110
+ function evaluate(s, fm, ctx, cands, targets, drawn) {
111
+ const down = fm.down, margin = ctx.margin, model = swapped(fm.model, cands), creepK = PRINTED_DEFAULTS.creep_modulus.value, creep = swapped(fm.model, cands, creepK);
112
+ const solver = solveFrame(model), creeper = solveFrame(creep);
113
+ const all = [...targets, ...cands.map((c) => alongOf(c.b, ctx))];
114
+ const sagOf = (t, res, values) => (t.node ? ctx.sagAt(res, t.node(values), down) : ctx.sagAlong(res, t.beam, t.from, t.to, down).sag);
115
+ let def = null, creepSag = null;
116
+ const per = new Map(cands.map((c) => [c.b.id, { stress: 0, compression: 0, case: null }]));
117
+ for (const cs of fm.cases) {
118
+ const loads = fm.nodeLoads(cs.values), res = stamp(fm, model, solver.statics({ loads })), cr = stamp(fm, creep, creeper.statics({ loads }));
119
+ for (const t of all) {
120
+ // where the frame as drawn already misses this sag, the printed beam is held to the drawn frame's own figure
121
+ const base = drawn.get(`${t.what}|${cs.label}`) ?? 0, missed = base > t.limit.value + 1e-12, lim = missed ? base * (1 + DRAWN_SLACK) : t.limit.value;
122
+ const sag = sagOf(t, res, cs.values), long = sagOf(t, cr, cs.values), m = sag > 1e-12 ? lim / sag : Infinity, ml = long > 1e-12 ? lim / long : Infinity;
123
+ if (!def || m < def.margin) def = { margin: m, sag, limit: t.limit, what: t.what, case: cs.label, drawn: missed ? base : null };
124
+ if (!creepSag || ml < creepSag.margin) creepSag = { margin: ml, sag: long, limit: t.limit, what: t.what, case: cs.label, drawn: missed ? base : null };
125
+ }
126
+ for (const e of res.elements) { const p = per.get(e.of); if (!p) continue; if (e.stress && e.stress.peak > p.stress) { p.stress = e.stress.peak; p.case = cs.label; } if (e.axial < -p.compression) p.compression = -e.axial; }
127
+ }
128
+ let freq = null;
129
+ const moves = ctx.excitesOf(s).filter((x) => x.kind === 'move');
130
+ if (moves.length) {
131
+ const need = Math.max(...moves.map((x) => x.Hz)) * margin;
132
+ for (const cs of fm.cases) { const low = solveFrame(subdivide({ ...model, masses: fm.nodeMasses(cs.values) }, 4)).modes({ count: 1 }).frequencies[0]; if (!freq || low < freq.low) freq = { low, need, margin: low / need, case: cs.label }; }
133
+ }
134
+ const out = new Map();
135
+ for (const c of cands) {
136
+ const p = per.get(c.b.id), I = Math.min(c.section.Iy, c.section.Iz), Pcr = (Math.PI ** 2 * c.E * I) / c.b.L ** 2;
137
+ const m = { deflection: def?.margin ?? Infinity, creepSag: creepSag?.margin ?? Infinity, stress: p.stress > 0 ? c.strength / p.stress / margin : Infinity,
138
+ buckling: p.compression > 1e-9 ? Pcr / p.compression / margin : Infinity, creep: p.stress > 0 ? c.creepLimit / p.stress : Infinity, ...(freq ? { frequency: freq.margin } : {}) };
139
+ const governs = Object.entries(m).reduce((q, x) => (x[1] < q[1] ? x : q));
140
+ out.set(c.b.id, { c, margins: m, least: governs[1], governs: governs[0], stress: p.stress, compression: p.compression, euler: Pcr, def, creepSag, freq });
141
+ }
142
+ return out;
143
+ }
144
+
145
+ // The joins on a beam a printed one would not take as drawn: a blind, end-tap or anchor join screws into its end, and a
146
+ // printed beam has inserts there, no bore to tap or pocket; a join whose screw heads or nuts ride in a slot of the beam's
147
+ // face needs that face slotted, and a printable profile has one slot, on top
148
+ const INTO_END = ['blind', 'end-tap', 'anchor'];
149
+ function joinsToChange(fm, b) {
150
+ const out = [];
151
+ for (const x of fm.joins) {
152
+ const kind = x.j.kind;
153
+ if (x.A === b && INTO_END.includes(kind)) out.push({ join: x.j.index, label: x.j.label, why: `${x.j.label} screws into its end ${x.e}, where a printed beam has an insert, no bore to tap or pocket` });
154
+ else if (x.B === b && JOINS[kind]?.slot && String(x.j.address ?? '').split(/[.@]/)[0] !== 'top') out.push({ join: x.j.index, label: x.j.label, why: `${x.j.label} lands on its ${String(x.j.address).split(/[.@]/)[0]} face, which a printed beam has closed` });
155
+ }
156
+ return out;
157
+ }
158
+
159
+ // what a margin is, in a few words
160
+ function sayMargin(r, k) {
161
+ const m = r.margins[k], x = (v) => (v === Infinity ? 'free' : `${n3(v, 2)}`);
162
+ // where the frame as drawn already misses the limit: the figure held to is its own sag plus DRAWN_SLACK
163
+ const held = (d) => `${fig(d.drawn * (1 + DRAWN_SLACK))} mm, the frame as drawn (${fig(d.drawn)} mm, already past its ${fig(d.limit.value)} mm there, printed or not) and ${DRAWN_SLACK * 100}% more`;
164
+ const sagSaid = (d) => (d.drawn != null ? fig(d.sag) : n3(d.sag));
165
+ if (k === 'deflection') return `${x(m)} on sag (${sagSaid(r.def)} mm at ${r.def.what} against ${r.def.drawn != null ? held(r.def) : `${n3(r.def.limit.value)} mm, ${r.def.limit.from}`})`;
166
+ if (k === 'creepSag') return `${x(m)} on sag as it creeps (${sagSaid(r.creepSag)} mm at ${r.creepSag.what}${r.creepSag.drawn != null ? ` against ${held(r.creepSag)}` : ''})`;
167
+ if (k === 'stress') return `${x(m)} on stress (${n3(r.stress, 2)} MPa against ${n3(r.c.strength, 1)} MPa${r.c.spliced ? ' as spliced' : ''}, twice the margin wanted)`;
168
+ if (k === 'buckling') return `${x(m)} on buckling (${n3(r.compression, 1)} N against Euler's ${n3(r.euler, 0)} N, twice wanted)`;
169
+ if (k === 'creep') return `${x(m)} on creep (${n3(r.stress, 2)} MPa held against ${n3(r.c.creepLimit, 2)} MPa)`;
170
+ return `${x(m)} on its lowest mode (${n3(r.freq.low, 1)} Hz against ${n3(r.freq.need, 1)} Hz, twice the task's moves)`;
171
+ }
172
+
173
+ /**
174
+ * beam.printable across a frame: each beam tried printed in the plastic frame.printed names, its margins against the
175
+ * frame's limits, the list of those that can be printed, and those printed together solved once more.
176
+ * @param {object} s a built assembly @param {object} fm frameModelOf's @param {Function} f the findings' sink @param {object} ctx frameChecks' helpers
177
+ */
178
+ export function printableCheck(s, fm, f, ctx) {
179
+ const opts = printedOption(s.a.frame.printed), down = fm.down;
180
+ const targets = [
181
+ ...fm.loads.map((l) => { const b = l.beam ?? l.mount.beam; return { what: l.where, node: (values) => fm.nodeAt(b, l.beam ? l.z : fm.mountStation(l.mount, values)), limit: ctx.limitFor(b, null) }; }),
182
+ ...fm.points.map((p) => ({ what: p.where, node: () => fm.nodeAt(p.beam, p.z), limit: ctx.limitFor(p.beam, null) })),
183
+ ...fm.guides.map((g) => ({ what: `guide ${g.id}`, beam: g.beam, from: g.from, to: g.to, limit: g.tolerance ? { value: g.tolerance.value, from: 'the rail\'s own parallelism' } : ctx.limitFor(g.beam, null) })),
184
+ ];
185
+ const rests = `the printed section's walls and infill, its plastic's figures and the creep shares (estimates until the beam coupon is measured)${fm.joins.length ? `, and ${ctx.restsJoins} as they are, made for metal beams` : ''}`;
186
+ const best = new Map(), none = [], cache = new Map(), drawn = drawnSags(fm, ctx, targets);
187
+ for (const b of fm.beams.values()) {
188
+ let pick = null, why = null;
189
+ for (const pose of opts.pose ? [opts.pose] : ['lying', 'standing']) {
190
+ const c = candidate(b, opts, pose, cache);
191
+ if (!c) continue;
192
+ if (c.why) { why = c.why; break; }
193
+ const r = evaluate(s, fm, ctx, [c], targets, drawn.sags).get(b.id);
194
+ if (!pick || r.least > pick.least * 1.01) pick = r; // (lying down, its stronger way, unless standing is clearly better)
195
+ }
196
+ if (!pick) { none.push({ b, why: why ?? `${b.id} prints neither way` }); continue; }
197
+ best.set(b.id, pick);
198
+ }
199
+ const plastic = opts.material.toUpperCase(), poseSaid = (c) => (c.pose === 'lying' ? `lying down${c.spliced ? `, spliced (${n3(c.b.L, 1)} mm, longer than the bed)` : ''}` : 'standing up');
200
+ for (const { b, why } of none) f('info', `${b.id} stays ${b.alloy ?? 'as it is'}: ${why}`, null, { code: 'beam.printable', between: [r4(b.A), r4(add(b.A, scale(b.u, b.L)))], refs: { beam: b.id, material: opts.material, printable: false } });
201
+ for (const r of best.values()) {
202
+ const c = r.c, b = c.b, ok = r.least >= 1, order = Object.keys(r.margins).filter((k) => r.margins[k] !== Infinity).sort((p, q) => r.margins[p] - r.margins[q]);
203
+ const change = b.m.printed ? [] : joinsToChange(fm, b), joinsSaid = change.length ? `. Its joins as drawn need changing to print it: ${change.map((x) => x.why).join('; ')}. A bracket or a gusset on its top slot takes it, its spring then a printed fitting's` : '';
204
+ r.change = change;
205
+ const text = ok
206
+ ? `${b.id} can be printed in ${plastic}, ${poseSaid(c)} (${c.profile}, ${n3(c.grams, 1)} g): its least margin is ${n3(r.least, 2)} times, ${said[r.governs]}. ${order.map((k) => sayMargin(r, k)).join('; ')}${joinsSaid}. It rests on ${rests}`
207
+ : `${b.id} needs ${b.alloy ?? 'its own material'}: printed in ${plastic}, ${poseSaid(c)} (${c.profile}), it misses by ${n3(1 / r.least, 2)} times on ${said[r.governs]}. ${order.map((k) => sayMargin(r, k)).join('; ')}. It rests on ${rests}`;
208
+ f(ok ? 'pass' : 'info', text, null, { code: 'beam.printable', at: r4(add(b.A, scale(b.u, b.L / 2))), between: [r4(b.A), r4(add(b.A, scale(b.u, b.L)))],
209
+ values: { margin: r3(r.least), misses: ok ? null : r3(1 / r.least), grams: r3(c.grams), modulus: c.E, strength: r3(c.strength), margins: Object.fromEntries(Object.entries(r.margins).map(([k, v]) => [k, r3(v)])), sag: r3(r.def?.sag), limit: r3(r.def?.limit.value), creepSag: r3(r.creepSag?.sag), drawnSag: r.def?.drawn != null ? +r.def.drawn.toPrecision(3) : null },
210
+ refs: { beam: b.id, material: opts.material, printable: ok, pose: c.pose, spliced: c.spliced, profile: c.profile, governs: r.governs, alloy: b.alloy, joins: change.map((x) => x.join), restsOn: 'estimate' } });
211
+ }
212
+ // those that pass alone, printed together: put back the one that misses most until all of them hold
213
+ let together = [...best.values()].filter((r) => r.least >= 1).map((r) => r.c), back = [], least = null;
214
+ while (together.length) {
215
+ const rs = evaluate(s, fm, ctx, together, targets, drawn.sags), worst = [...rs.values()].reduce((p, q) => (q.least < p.least ? q : p));
216
+ if (worst.least >= 1) { least = worst; break; }
217
+ back.push(worst.c.b.id); together = together.filter((c) => c !== worst.c);
218
+ }
219
+ const all = fm.beams.size, metal = [...fm.beams.keys()].filter((id) => !together.some((c) => c.b.id === id));
220
+ const changes = [...new Set(together.flatMap((c) => best.get(c.b.id).change ?? []).map((x) => x.join))];
221
+ const changeSaid = changes.length ? `. ${changes.length} of its joins need changing to a bracket or a gusset on a printed beam's top slot (each beam's finding says which)` : '';
222
+ const text = together.length === all
223
+ ? `every beam of the frame can be printed in ${plastic} (${all}), printed together and solved once more: the least margin is ${sayMargin(least, least.governs)}${['deflection', 'creepSag', 'frequency'].includes(least.governs) ? '' : ` at ${least.c.b.id}`}; ${n3(together.reduce((t, c) => t + c.grams, 0), 0)} g of ${plastic} in all`
224
+ : `${together.length} of the frame's ${all} beams can be printed in ${plastic}${together.length ? ` (${together.map((c) => c.b.id).join(', ')}), printed together and solved once more, the least margin ${sayMargin(least, least.governs)}` : ''}; ${metal.join(', ')} stay${metal.length === 1 ? 's' : ''} as ${metal.length === 1 ? 'it is' : 'they are'}${back.length ? `, of them ${back.join(', ')} passing alone but not printed with the rest` : ''}`;
225
+ const missedSaid = drawn.missed.length ? `. As drawn, unprinted, the frame already misses ${drawn.missed.map((x) => `${fig(x.sag)} mm at ${x.what} (against ${fig(x.limit.value)} mm)`).join(', ')} (frame.deflection says so): there a printed beam is held to the frame as drawn, within ${DRAWN_SLACK * 100}%, and blamed only where printing it makes that sag worse` : '';
226
+ f(together.length === all ? 'pass' : 'info', `${text}${changeSaid}${missedSaid}. It rests on ${rests}`, null, { code: 'beam.printable', values: { printable: together.length, beams: all, margin: r3(least?.least), grams: r3(together.reduce((t, c) => t + c.grams, 0)) },
227
+ refs: { material: opts.material, printable: together.map((c) => c.b.id), metal, back, governs: least?.governs ?? null, joins: changes, missed: drawn.missed.map((x) => x.what), poses: Object.fromEntries(together.map((c) => [c.b.id, c.pose])), restsOn: 'estimate' } });
228
+ }
229
+
230
+ /**
231
+ * beam.coupon, and beam.creep for each printed beam of the frame. A printed beam held only by two of frame.supports
232
+ * (no join on it) with masses on it is the beam coupon: its sag under each mass and the mass it breaks at are
233
+ * predictions cad measured takes, written to its plastic's set as the modulus and strength a printed beam has.
234
+ * @param {object} s a built assembly @param {object} fm frameModelOf's @param {Function} f the findings' sink @param {object} ctx frameChecks' helpers
235
+ */
236
+ export function couponChecks(s, fm, f, ctx) {
237
+ const drawn = ctx.results[0];
238
+ for (const b of fm.beams.values()) {
239
+ const p = b.m.printed;
240
+ if (!p) continue;
241
+ // beam.creep: its peak stress as drawn and in every pose, held for months
242
+ let stress = 0, where = null;
243
+ for (const r of ctx.results) for (const e of r.spring.elements) if (e.of === b.id && e.stress && e.stress.peak > stress) { stress = e.stress.peak; where = r.case.label; }
244
+ const c = beamCreep(b.m, { stress: r3(stress) });
245
+ f(c.level, `${b.id}: ${c.text.replace(/^[^:]+: /, '')}${fm.cases.length > 1 ? `, worst ${where}` : ''}`, c.level === 'fail' ? `${b.id}: creeps` : null, { code: 'beam.creep', at: r4(add(b.A, scale(b.u, b.L / 2))), values: c.values, refs: { ...c.refs, beam: b.id } });
246
+ // the coupon: two supports on it alone, no join, a mass on it
247
+ const sups = fm.supports.filter((x) => x.beam === b), loads = fm.loads.filter((l) => l.beam === b);
248
+ if (sups.length !== 2 || !sups.every((x) => x.said) || fm.joins.some((x) => x.A === b || x.B === b) || !loads.length) continue;
249
+ const mat = b.m.material.name, lying = p.pose === 'lying', z = lying ? '' : '_z', E = p.modulus, S = p.strength;
250
+ const solver = solveFrame(fm.model), peak = (res) => Math.max(0, ...res.elements.filter((e) => e.of === b.id && e.stress).map((e) => e.stress.peak));
251
+ const self = peak(solver.statics({ loads: [] }));
252
+ for (const l of loads) {
253
+ const one = fm.nodeLoads(drawn.case.values, l), res = solver.statics({ loads: one, gravity: [0, 0, 0] }), node = one[0].node, sag = ctx.sagAt(res, node, fm.down), perKg = peak(res) / l.kg;
254
+ const breaks = (S - self) / perKg, span = Math.abs(sups[0].z - sups[1].z);
255
+ const rests = `${mat}'s ${lying ? 'modulus along its layers' : 'modulus across its layers'} ${E} MPa${p.coupon?.modulus ? ` (${p.coupon.modulus}, ${p.modulusKind})` : ' (the plastic\'s data sheet: an estimate for a printed beam)'} and its printed section, ${n3(p.section.inertiaX, 0)} mm⁴ from ${p.walls} walls and ${Math.round(p.infill * 100)}% infill (an estimate)`;
256
+ f('info', `${b.id} is the beam coupon, printed ${lying ? 'lying down' : 'standing up'}, across ${n3(span, 1)} mm between ${sups.map((x) => x.where).join(' and ')}: ${n3(l.kg, 3)} kg at ${l.where} sags it ${n3(sag)} mm, from ${rests}. Read it with a dial and write it back: cad measured ${s.project}/${s.name} ${b.id}.sag=<mm>, and the modulus goes to ${mat}.beam_modulus${z}`, null,
257
+ { code: 'beam.coupon', at: r4(fm.nodes[node]), values: { sag: r3(sag), kg: l.kg, span: r3(span), modulus: E, inertia: p.section.inertiaX },
258
+ predict: { name: `${b.id}.sag`, figure: `sag of the beam coupon ${b.id} under ${l.kg} kg`, value: r3(sag), unit: 'mm', coupon: { rule: `${mat}.beam_modulus${z}`, kind: 'modulus', base: E, sag, unit: 'MPa', what: `${n3(l.kg, 3)} kg at ${l.where}, across ${n3(span, 1)} mm` } },
259
+ refs: { beam: b.id, rule: `${mat}.beam_modulus${z}`, pose: p.pose, kind: p.modulusKind } });
260
+ f('info', `${b.id}, the beam coupon: it breaks at about ${n3(breaks, 2)} kg hung at ${l.where}, where its stress reaches ${S} MPa (${p.coupon?.strength ? `${p.coupon.strength}, measured` : `${mat}'s strength ${lying ? 'along' : 'across'} its layers, ${p.strengthKind}`}). Last of all, pull it down there until it breaks (a luggage scale on the cord, its peak in kg), and write that: cad measured ${s.project}/${s.name} ${b.id}.break=<kg>, and the strength goes to ${mat}.beam_strength${z}`, null,
261
+ { code: 'beam.coupon', at: r4(fm.nodes[node]), values: { breaks: r3(breaks), strength: S, perKg: r3(perKg), self: r3(self) },
262
+ predict: { name: `${b.id}.break`, figure: `mass the beam coupon ${b.id} breaks at`, value: r3(breaks), unit: 'kg', coupon: { rule: `${mat}.beam_strength${z}`, kind: 'strength', base: S, perKg, self, unit: 'MPa', what: `hung at ${l.where}, across ${n3(span, 1)} mm` } },
263
+ refs: { beam: b.id, rule: `${mat}.beam_strength${z}`, pose: p.pose, kind: p.strengthKind } });
264
+ }
265
+ }
266
+ }
267
+
268
+ /**
269
+ * The figure a coupon's measurement gives, for cad measured: the modulus from a sag (the solve is linear in it, so the
270
+ * modulus is the one taken times the sag predicted over the sag measured), the strength from the mass it broke at (its
271
+ * stress then: its own weight's, plus the stress per kilogram times the mass).
272
+ * @param {{ kind: 'modulus' | 'strength', base: number, sag?: number, perKg?: number, self?: number }} c a beam.coupon prediction's coupon
273
+ * @param {number} predicted @param {number} measured
274
+ */
275
+ export function couponFigure(c, predicted, measured) {
276
+ return Number((c.kind === 'modulus' ? (c.base * (c.sag ?? predicted)) / measured : c.self + c.perKg * measured).toPrecision(4));
277
+ }
package/lib/frames.mjs CHANGED
@@ -6,8 +6,9 @@ import path from 'node:path';
6
6
  import crypto from 'node:crypto';
7
7
  import * as frames from '@rulecad/frames';
8
8
 
9
- // The workspace's own profile, slot and material sets (cad measure --profile writes a draft profile there, with its
10
- // outline in rules/outlines/), read once per change to the folder
9
+ // The workspace's own profile, slot, slot nut, material, thread and bought fitting sets, and its joins set (cad measure
10
+ // --profile writes a draft profile there, with its outline in rules/outlines/; cad measured writes a measured figure
11
+ // into a copy there), read once per change to the folder
11
12
  let seen = null;
12
13
  /**
13
14
  * What @rulecad/frames is handed from a workspace: its own rule sets by name, and the measured outlines beside them.
@@ -25,7 +26,8 @@ export function framesContext(dir) {
25
26
  for (const f of files) {
26
27
  try {
27
28
  const raw = fs.readFileSync(path.join(d, f), 'utf8'), s = JSON.parse(raw);
28
- if (into === sets ? s?.rules && typeof s.rules === 'object' && ['profile', 'slot', 'slot_nut', 'material', 'thread'].includes(s.part) : Array.isArray(s?.loops)) { into[s.name ?? f.slice(0, -5)] = s; text.push(raw); }
29
+ // (a plastic's or a metal's set has no part: it is a material by its density, and the beam coupon measures into it)
30
+ if (into === sets ? s?.rules && typeof s.rules === 'object' && (['profile', 'slot', 'slot_nut', 'material', 'thread', 'fitting', 'joins'].includes(s.part) || (s.part == null && typeof s.rules.density?.value === 'number')) : Array.isArray(s?.loops)) { into[s.name ?? f.slice(0, -5)] = s; text.push(raw); }
29
31
  } catch {} // (a broken set is cad rules check's to name)
30
32
  }
31
33
  }