@rulecad/frames 0.0.1 → 0.1.8

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/cutsheet.mjs ADDED
@@ -0,0 +1,118 @@
1
+ // A beam's cut-and-drill sheet, as SVG: what a person at the saw and the drill needs, to scale. The section seen from
2
+ // end a, each face named and the tapped bores marked; a view of each face that has work on it, that face up, end a on
3
+ // the left; every operation dimensioned from end a to 0.1 mm; and a numbered list of the operations, each tap with its
4
+ // thread and depth. Units: mm, the sheet drawn in mm too (it prints to scale at 100%).
5
+ import { outline } from './profile.mjs';
6
+ import { CUT_DEFAULTS } from './cutlist.mjs';
7
+
8
+ const mm = (x) => String(+Number(x).toFixed(2));
9
+ const d1 = (x) => Number(x).toFixed(1);
10
+ const f = (x) => String(+Number(x).toFixed(3));
11
+ const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
12
+ const INK = '#1a1a1a', THIN = '#666', METAL = '#dde3ea', CUT = '#c03a2b';
13
+ const SCALES = [1, 2, 5, 10, 20, 50, 100];
14
+ // Each face's view: looking at it from outside, end a on the left, and which way in the section is up the page
15
+ // (the face frame's y: top +x, bottom -x, front +y, back -y), and how wide the face is
16
+ const FACE_VIEW = { top: { up: [1, 0], wide: 'width' }, bottom: { up: [-1, 0], wide: 'width' }, front: { up: [0, 1], wide: 'height' }, back: { up: [0, -1], wide: 'height' } };
17
+ const OPPOSITE = { top: 'bottom', bottom: 'top', front: 'back', back: 'front' };
18
+ const DIR = { top: [0, 1], bottom: [0, -1], front: [-1, 0], back: [1, 0] };
19
+
20
+ function pen() {
21
+ const out = [];
22
+ return {
23
+ out,
24
+ line: (a, b, c, d, s = INK, w = 0.25, dash = '') => out.push(`<line x1="${f(a)}" y1="${f(b)}" x2="${f(c)}" y2="${f(d)}" stroke="${s}" stroke-width="${w}"${dash ? ` stroke-dasharray="${dash}"` : ''}/>`),
25
+ circle: (x, y, r, s = INK, fill = 'none') => out.push(`<circle cx="${f(x)}" cy="${f(y)}" r="${f(r)}" fill="${fill}" stroke="${s}" stroke-width="0.25"/>`),
26
+ path: (d, fill = 'none', s = INK, w = 0.25) => out.push(`<path d="${d}" fill="${fill}" fill-rule="evenodd" stroke="${s}" stroke-width="${w}" stroke-linejoin="round"/>`),
27
+ text: (x, y, t, { anchor = 'start', size = 3, turn = 0, weight = '' } = {}) => out.push(`<text x="${f(x)}" y="${f(y)}"${turn ? ` transform="rotate(${turn} ${f(x)} ${f(y)})"` : ''} text-anchor="${anchor}" font-size="${size}"${weight ? ` font-weight="${weight}"` : ''} font-family="system-ui, sans-serif" fill="${INK}">${esc(t)}</text>`),
28
+ };
29
+ }
30
+
31
+ /**
32
+ * A beam's cut-and-drill sheet, to scale: its section from end a with the faces named, a view of each face with work
33
+ * on it (that face up), each operation dimensioned from end a to 0.1 mm, and the operations listed in order, each tap
34
+ * with its thread and depth.
35
+ * @param {object} b a beam's model (beamModel)
36
+ * @param {{ mark?: string, items?: string[], grams?: number | null }} [o] the beam's mark on the cut list, the items it is, its mass each
37
+ * @returns {{ svg: string, scale: number, faces: string[], dimensions: { op: number, distance: number, text: string }[] }}
38
+ * scale: the beam is drawn 1:scale; faces: the views drawn; dimensions: each operation's figure from end a, as on the sheet
39
+ */
40
+ export function beamSheet(b, o = {}) {
41
+ if (b?.kind !== 'beam') throw new Error(`beamSheet: give a beam's model (beamModel) (got ${b === undefined ? 'nothing' : typeof b})`);
42
+ const p = b.profile, L = b.length, mark = o.mark ?? null, items = o.items ?? [], grams = o.grams ?? b.weight?.sheet ?? b.mass;
43
+ const ops = b.ops.map((x, i) => ({ ...x, n: i + 1 }));
44
+ // the views: each face with work on it or a mitre seen from it, else the top
45
+ const faces = Object.keys(FACE_VIEW).filter((k) => ops.some((x) => x.face === k || (x.op === 'mitre' && x.about === k)));
46
+ if (!faces.length) faces.push('top');
47
+ const k = SCALES.find((s) => L / s <= 200) ?? Math.ceil(L / 200), s = 1 / k; // the beam's scale, 1:k
48
+ const big = Math.max(p.width, p.height), ks = [4, 2, 1].find((z) => big * z <= 44) ?? 0.5; // the section's, ks:1
49
+ const x0 = 78, W = Math.max(297, x0 + L * s + 24), { out, line, circle, path, text } = pen();
50
+ // heading
51
+ text(10, 12, `${mark ? `Mark ${mark}: ` : ''}${p.name} x ${d1(L)} mm`, { size: 5, weight: 'bold' });
52
+ text(10, 18.5, [items.length ? `${items.length} off: ${items.join(', ')}` : null, p.title, grams != null ? `${mm(grams)} g each` : null, b.material?.name].filter(Boolean).join(' · '), { size: 3 });
53
+ text(10, 23.5, `Beam 1:${k}, section ${ks >= 1 ? `${ks}:1` : `1:${1 / ks}`}. All in mm, measured from end a. Cut to ±${mm(p.supply.cutTolerance ?? CUT_DEFAULTS.tolerance.value)}.`, { size: 3 });
54
+ // the section from end a: top up, front on the right (looking from a toward b)
55
+ const cx = 38, cy = 58, X = (x) => cx - x * ks, Y = (y) => cy - y * ks, loops = outline(p).loops;
56
+ path(loops.map((l) => `M ${l.map(([x, y]) => `${f(X(x))} ${f(Y(y))}`).join(' L ')} Z`).join(' '), METAL);
57
+ text(cx, Y(p.height / 2) - 2, 'top', { anchor: 'middle', size: 2.6 }); text(cx, Y(-p.height / 2) + 4.5, 'bottom', { anchor: 'middle', size: 2.6 });
58
+ text(X(p.width / 2) - 1.5, cy + 1, 'back', { anchor: 'end', size: 2.6 }); text(X(-p.width / 2) + 1.5, cy + 1, 'front', { anchor: 'start', size: 2.6 });
59
+ text(cx, cy + big * ks / 2 + 11, 'section at end a,', { anchor: 'middle', size: 2.6 }); text(cx, cy + big * ks / 2 + 14.5, 'seen from a, top up', { anchor: 'middle', size: 2.6 });
60
+ let ty = cy + big * ks / 2 + 20;
61
+ for (const t of ops.filter((x) => x.op === 'tap')) for (const bn of t.bores) {
62
+ const bo = b.bores.find((x) => x.name === bn); if (!bo) continue;
63
+ if (t.end === 'a') circle(X(bo.at[0]), Y(bo.at[1]), (t.major / 2) * ks, CUT);
64
+ text(cx, ty, `(${t.n}) ${bn}: tap ${t.thread} x ${mm(t.depth)} deep`, { anchor: 'middle', size: 2.6 }); ty += 4;
65
+ }
66
+ // each face's view
67
+ const dimensions = [];
68
+ let y = 40;
69
+ for (const face of faces) {
70
+ const v = FACE_VIEW[face], w = p[v.wide], h = w * s < 6 ? 6 / s : w, top = y, mid = y + (h * s) / 2, U = (pt) => mid - ((pt[0] * v.up[0] + pt[1] * v.up[1]) * h / w) * s, Z = (z) => x0 + z * s;
71
+ text(x0, top - 3, `${face} face up: seen from the ${face}, end a on the left${h !== w ? ` (across drawn ${mm(h / w)} times its size)` : ''}`, { size: 3, weight: 'bold' });
72
+ // the outline, with any mitre seen
73
+ const corner = (end, side) => { // where the outline's edge on this side (+1 the upper, -1 the lower) meets the end
74
+ const m = ops.find((x) => x.op === 'mitre' && x.end === end);
75
+ if (!m) return end === 'a' ? 0 : L;
76
+ const seen = m.about === face || m.about === OPPOSITE[face], u = DIR[m.long][0] * v.up[0] + DIR[m.long][1] * v.up[1];
77
+ const c = seen ? ((u > 0) === (side > 0) ? 0 : m.cut) : face === m.long ? 0 : m.cut;
78
+ return end === 'a' ? c : L - c;
79
+ };
80
+ const yT = top, yB = top + h * s, poly = [[corner('a', 1), yT], [corner('b', 1), yT], [corner('b', -1), yB], [corner('a', -1), yB]];
81
+ path(`M ${poly.map(([z, yy]) => `${f(Z(z))} ${f(yy)}`).join(' L ')} Z`, METAL);
82
+ for (const pl of b.places.filter((q) => q.face === face && q.slot)) line(Z(0) - 3, U(pl.at), Z(L) + 3, U(pl.at), THIN, 0.18, '4 1 1 1');
83
+ text(Z(0) - 2, mid + 1, 'a', { anchor: 'end', size: 3.2, weight: 'bold' }); text(Z(L) + 2, mid + 1, 'b', { size: 3.2, weight: 'bold' });
84
+ // the work on this face
85
+ const here = ops.filter((x) => x.face === face);
86
+ for (const x of here) {
87
+ const zc = Z(x.distance), uc = U(x.anchor.origin);
88
+ if (x.op === 'access' || x.op === 'drill') circle(zc, uc, Math.max((x.diameter / 2) * s, 0.4), CUT);
89
+ if (x.op === 'counterbore') { circle(zc, uc, Math.max((x.seat.diameter / 2) * s, 0.6), CUT); circle(zc, uc, Math.max((x.diameter / 2) * s, 0.4), CUT); }
90
+ if (x.op === 'pocket' && x.size) path(`M ${f(zc - x.size[0] * s / 2)} ${f(uc - x.size[1] * s / 2)} h ${f(x.size[0] * s)} v ${f(x.size[1] * s)} h ${f(-x.size[0] * s)} Z`, 'none', CUT);
91
+ if (x.op === 'pocket' && x.outline) path(`M ${x.outline.map(([a, c]) => `${f(zc + a * s)} ${f(uc - c * s)}`).join(' L ')} Z`, 'none', CUT);
92
+ if (x.op === 'notch') path(`M ${f(zc - x.length * s / 2)} ${f(uc - x.width * s / 2)} h ${f(x.length * s)} v ${f(x.width * s)} h ${f(-x.length * s)} Z`, 'none', CUT);
93
+ text(zc + 1, uc - Math.max((x.diameter ?? 2) / 2 * s, 0.6) - 0.8, `(${x.n})`, { size: 2.2 });
94
+ }
95
+ // dimensions from end a: a leader down from each, its figure turned to read up the page, the length last
96
+ const yd = yB + 3, marks = [...here.map((x) => ({ n: x.n, z: x.distance, from: U(x.anchor.origin) })), { n: null, z: Math.max(corner('b', 1), corner('b', -1)), from: yB }];
97
+ line(Z(0), yB, Z(0), yd + 3, THIN, 0.18); text(Z(0) + 1, yd + 3.5, '0', { size: 2.6, turn: 90 });
98
+ let last = Z(0);
99
+ for (const m of marks.sort((a, c) => a.z - c.z)) {
100
+ const at = Math.max(Z(m.z), last + 3.2); last = at;
101
+ line(Z(m.z), m.from, Z(m.z), yd, THIN, 0.18, m.n ? '1 0.6' : ''); line(Z(m.z), yd, at, yd + 2, THIN, 0.18); line(at, yd + 2, at, yd + 3, THIN, 0.18);
102
+ const t = d1(m.z); text(at + 1, yd + 3.5, t, { size: 2.6, turn: 90 });
103
+ if (m.n) dimensions.push({ op: m.n, distance: m.z, text: t });
104
+ }
105
+ y = yd + 26;
106
+ }
107
+ // the operations, in order from end a
108
+ y = Math.max(y, ty + 4);
109
+ text(10, y, 'Operations, in order from end a', { size: 3.4, weight: 'bold' }); y += 5.5;
110
+ for (const x of ops) {
111
+ const where = x.end ? `end ${x.end}` : `${x.place ?? x.face}, ${d1(x.distance)} from a`;
112
+ text(10, y, `${x.n}.`, { size: 3 }); text(17, y, `${x.op} · ${where}`, { size: 3, weight: 'bold' }); text(80, y, x.line, { size: 3 }); y += 5;
113
+ }
114
+ text(10, y + 3, 'Deburr every cut and hole. Check each length against its figure before drilling.', { size: 2.6 });
115
+ const H = y + 10;
116
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${f(W)}mm" height="${f(H)}mm" viewBox="0 0 ${f(W)} ${f(H)}"><rect width="100%" height="100%" fill="#fff"/>${out.join('')}</svg>\n`;
117
+ return { svg, scale: k, faces, dimensions };
118
+ }
package/door.d.mts ADDED
@@ -0,0 +1,127 @@
1
+ /**
2
+ * A printed hinge for a door over a bay: the frame's leaf lies on the hinge beam's face, two screws into slot nuts on
3
+ * its slot, its two knuckles risen over the beam's outer edge; the door's leaf lies on the door's outer face, its knuckle
4
+ * between them, two screws through the door into nuts; a bought cap screw is the pin. The door stands off the face by
5
+ * the frame leaf, a head and the clearance, so it passes over the heads; its edge on the hinge side stops a knuckle and
6
+ * the clearance from the axis. Sized from a named load across the pin by beam formulas to about twice the margin. The
7
+ * frame's leaf prints as it lies, the door's leaf face down; the pin's hole lies as a teardrop.
8
+ * @param {string | object} profile the hinge beam's @param {{ sheet: number, face?: string, thread?: string, nut?: string, pin?: string, screw?: string, load?: number, printer?: object, material?: string | object, given?: object }} o
9
+ * sheet: the door's thickness; pin: the pin's thread (default M3); screw: the thread through the door (default M3)
10
+ * @returns {object} its model: standoff (the door's inner face over the beam's), axis [y, z], edge (the door's hinge-side edge, y), screws, hardware, grams, margin
11
+ */
12
+ export function hingeModel(profile: string | object, o?: {
13
+ sheet: number;
14
+ face?: string;
15
+ thread?: string;
16
+ nut?: string;
17
+ pin?: string;
18
+ screw?: string;
19
+ load?: number;
20
+ printer?: object;
21
+ material?: string | object;
22
+ given?: object;
23
+ }): object;
24
+ /**
25
+ * A hinge's leaves: part 'frame' (as it prints, which is as it lies) or 'door' (face down to print); pose 'fit' puts
26
+ * the door's leaf where it sits with the door closed. @param {object} m @param {{ part?: 'frame' | 'door', pose?: 'print' | 'fit', printer?: object, ops?: object }} [o] @returns {object}
27
+ */
28
+ export function hinge(m: object, o?: {
29
+ part?: "frame" | "door";
30
+ pose?: "print" | "fit";
31
+ printer?: object;
32
+ ops?: object;
33
+ }): object;
34
+ /**
35
+ * A printed pull handle for a door: a grip between two feet, screwed from inside the door into a pilot in each foot,
36
+ * room under the grip for the fingers. Sized from a named pull by beam formulas to about twice the margin. It prints
37
+ * on its side, its outline the first layer, its pilots lying as teardrops.
38
+ * @param {{ sheet: number, thread?: string, span?: number, load?: number, printer?: object, material?: string | object }} o
39
+ * sheet: the door's thickness, for the screws' length; span: between the screws (default 64)
40
+ * @returns {object} its model
41
+ */
42
+ export function handleModel(o?: {
43
+ sheet: number;
44
+ thread?: string;
45
+ span?: number;
46
+ load?: number;
47
+ printer?: object;
48
+ material?: string | object;
49
+ }): object;
50
+ /** A handle's solid: on its side to print, or fitted (pose 'fit', its feet on the door at z = 0). @param {object} m @param {{ pose?: 'print' | 'fit', printer?: object, ops?: object }} [o] @returns {object} */
51
+ export function handle(m: object, o?: {
52
+ pose?: "print" | "fit";
53
+ printer?: object;
54
+ ops?: object;
55
+ }): object;
56
+ /**
57
+ * A printed turn-button latch: a post on the latch beam's face, screwed into a slot nut through its middle, with a tab
58
+ * on top that turns over the door's edge to hold it shut. Shown at rest, turned over the door. It prints tab down.
59
+ * @param {string | object} profile @param {{ sheet: number, standoff: number, edge?: number, face?: string, thread?: string, nut?: string, load?: number, printer?: object, material?: string | object, given?: object }} o
60
+ * standoff: the door's inner face over the beam's (a hinge's); edge: the door's edge, from the slot's line (default a clip's)
61
+ * @returns {object} its model
62
+ */
63
+ export function latchModel(profile: string | object, o?: {
64
+ sheet: number;
65
+ standoff: number;
66
+ edge?: number;
67
+ face?: string;
68
+ thread?: string;
69
+ nut?: string;
70
+ load?: number;
71
+ printer?: object;
72
+ material?: string | object;
73
+ given?: object;
74
+ }): object;
75
+ /** A latch's solid: tab down to print, or fitted and turned over the door (pose 'fit'). @param {object} m @param {{ pose?: 'print' | 'fit', printer?: object, ops?: object }} [o] @returns {object} */
76
+ export function latch(m: object, o?: {
77
+ pose?: "print" | "fit";
78
+ printer?: object;
79
+ ops?: object;
80
+ }): object;
81
+ /**
82
+ * A printed magnet catch: a block on a beam's face under the door's edge, screwed into a slot nut on a step lower than
83
+ * its tower, a disc magnet pressed into the tower's top; a steel washer stuck to the door's inner face over it is the
84
+ * strike. The tower's top stops the washer's thickness and a half millimetre under the door. It prints on its side.
85
+ * @param {string | object} profile @param {{ standoff: number, edge?: number, magnet?: number[], face?: string, thread?: string, nut?: string, printer?: object, material?: string | object, given?: object }} o
86
+ * standoff: the door's (a hinge's); edge: the door's edge from the slot's line (default the head's room); magnet: [diameter, thickness]
87
+ * @returns {object} its model
88
+ */
89
+ export function magnetCatchModel(profile: string | object, o?: {
90
+ standoff: number;
91
+ edge?: number;
92
+ magnet?: number[];
93
+ face?: string;
94
+ thread?: string;
95
+ nut?: string;
96
+ printer?: object;
97
+ material?: string | object;
98
+ given?: object;
99
+ }): object;
100
+ /** A magnet catch's solid: on its side to print, or fitted. @param {object} m @param {{ pose?: 'print' | 'fit', tongues?: boolean, printer?: object, ops?: object }} [o] @returns {object} */
101
+ export function magnetCatch(m: object, o?: {
102
+ pose?: "print" | "fit";
103
+ tongues?: boolean;
104
+ printer?: object;
105
+ ops?: object;
106
+ }): object;
107
+ export namespace DOOR_DEFAULTS {
108
+ namespace pin {
109
+ export { text as rule };
110
+ export { kind };
111
+ export { source };
112
+ export { CHECKED as checked };
113
+ export { unit };
114
+ export { value };
115
+ }
116
+ namespace door { }
117
+ namespace load { }
118
+ namespace knuckles { }
119
+ namespace clear { }
120
+ namespace pull { }
121
+ namespace span { }
122
+ namespace finger { }
123
+ namespace magnet { }
124
+ namespace open { }
125
+ }
126
+ declare const CHECKED: "2026-11-17";
127
+ export {};
package/door.mjs ADDED
@@ -0,0 +1,254 @@
1
+ // Printed parts for a door on a frame: a hinge (a leaf screwed into a beam's slot, a leaf screwed through the door, a
2
+ // bought screw for its pin), a handle, a turn-button latch and a magnet catch. The door lies over its bay at a
3
+ // standoff from the beams' faces, so its hinge leaf's screw heads pass under it; its hinge's axis lies over the
4
+ // beam's outer edge at the door's outer face, so the door swings out and away from the frame and never into it.
5
+ //
6
+ // A hinge's frame (fitted): x along its axis (0 at its middle), y across the hinge beam's face toward the door (0 on
7
+ // the slot's centre line), z out of the face (0 on the face). The latch and the catch use the same frame on their
8
+ // beam. A handle's: y along it between its feet, x across, z out of the door's face. Units: mm, N, grams, degrees.
9
+ import jscad from '@jscad/modeling';
10
+ import { hole, fixingModel, nutModel, washerModel } from '@rulecad/fixings';
11
+ import { FITTING_DEFAULTS, pfig, printerOf, options, profileOf, slotSide, roundConcave, ccw, combine, sold, screwOf } from './fitting.mjs';
12
+ import { partSetup, loadOk, weigh, closingFindings, sheetThickness, sidePart, sideToFit, bendT, PANEL_DEFAULTS } from './panel.mjs';
13
+
14
+ const { polygon, cylinder } = jscad.primitives, { extrudeLinear } = jscad.extrusions, { union } = jscad.booleans, { hull } = jscad.hulls;
15
+ const { translate, transform } = jscad.transforms;
16
+ const CHECKED = '2026-11-17';
17
+ const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
18
+ const shown = (v) => { const s = v === undefined ? 'nothing' : JSON.stringify(v) ?? String(v); return s.length > 80 ? `${s.slice(0, 77)}...` : s; };
19
+ const mm = (x) => String(+Number(x).toFixed(2));
20
+ const r3 = (x) => +x.toFixed(3);
21
+ const an = (t) => `${/^(M|[aeiou8])/i.test(String(t)) ? 'an' : 'a'} ${t}`; // (an M5, a 6-32)
22
+ const up = (x, step) => Math.ceil(x / step - 1e-9) * step;
23
+ const finding = (level, text, code, extra = {}) => ({ level, text, code, ...extra });
24
+ const rule = (value, unit, text, kind, source) => ({ value, ...(unit ? { unit } : {}), rule: text, kind, source, checked: CHECKED });
25
+ const prism = (loop, h) => extrudeLinear({ height: h }, polygon({ points: ccw(loop) }));
26
+ const short = (p) => p.name.replace(/^profile-/, '');
27
+ const want = () => FITTING_DEFAULTS.margin.value;
28
+ const arc = (cx, cy, r, a0, a1, n = 16) => Array.from({ length: n + 1 }, (_, i) => { const a = a0 + ((a1 - a0) * i) / n; return [cx + r * Math.cos(a), cy + r * Math.sin(a)]; });
29
+
30
+ /** The working figures of the door's parts, each with what it rests on. */
31
+ export const DOOR_DEFAULTS = {
32
+ pin: rule('M4', '', 'A hinge\'s pin is a bought cap screw of this thread through its knuckles, held by a lock nut', 'default', 'A working figure of @rulecad/frames: M4 is sold long enough for a hinge whose two slot nuts sit side by side'),
33
+ door: rule('M3', '', 'The thread of the screws through the door: into a hinge leaf\'s nuts, a handle\'s pilots', 'default', 'A working figure of @rulecad/frames'),
34
+ load: rule(50, 'N', 'The design load at one hinge where none is given: the door\'s weight and a hand leaning on the open door, its share at one hinge, across the pin', 'default', 'A working figure of @rulecad/frames, so every hinge is sized and compared at one named load'),
35
+ knuckles: rule(3, '', 'A hinge has three knuckles: two on the frame\'s leaf, one on the door\'s between them', 'default', 'A working figure of @rulecad/frames'),
36
+ clear: rule(1, 'mm', 'Room between a door (or its leaf) and what it passes: a head, the frame\'s leaf, a knuckle', 'default', 'A working figure of @rulecad/frames'),
37
+ pull: rule(100, 'N', 'The design pull on a handle where none is given: a firm pull on a door that sticks', 'default', 'A working figure of @rulecad/frames'),
38
+ span: rule(64, 'mm', 'A handle\'s screws are this far apart: a common pitch for furniture handles', 'community', 'Furniture handle makers\' hole pitches of 64, 96 and 128 mm; not checked against one standard'),
39
+ finger: rule(25, 'mm', 'Room under a handle\'s grip for the fingers', 'estimate', 'A working figure of @rulecad/frames'),
40
+ magnet: rule([10, 3], 'mm', 'A magnet catch\'s disc magnet, diameter and thickness: a common size; give the one you have', 'estimate', 'A working figure of @rulecad/frames: its pull is not checked, as no figure from a maker is held'),
41
+ open: rule(120, '°', 'How far a door opens where nothing else is said', 'default', 'A working figure of @rulecad/frames: past square, short of laying it back on the frame'),
42
+ };
43
+
44
+ // ---------- a hinge ----------
45
+ /**
46
+ * A printed hinge for a door over a bay: the frame's leaf lies on the hinge beam's face, two screws into slot nuts on
47
+ * its slot, its two knuckles risen over the beam's outer edge; the door's leaf lies on the door's outer face, its knuckle
48
+ * between them, two screws through the door into nuts; a bought cap screw is the pin. The door stands off the face by
49
+ * the frame leaf, a head and the clearance, so it passes over the heads; its edge on the hinge side stops a knuckle and
50
+ * the clearance from the axis. Sized from a named load across the pin by beam formulas to about twice the margin. The
51
+ * frame's leaf prints as it lies, the door's leaf face down; the pin's hole lies as a teardrop.
52
+ * @param {string | object} profile the hinge beam's @param {{ sheet: number, face?: string, thread?: string, nut?: string, pin?: string, screw?: string, load?: number, printer?: object, material?: string | object, given?: object }} o
53
+ * sheet: the door's thickness; pin: the pin's thread (default M3); screw: the thread through the door (default M3)
54
+ * @returns {object} its model: standoff (the door's inner face over the beam's), axis [y, z], edge (the door's hinge-side edge, y), screws, hardware, grams, margin
55
+ */
56
+ export function hingeModel(profile, o = {}) {
57
+ const what = 'hingeModel';
58
+ options(what, o ?? {}, ['sheet', 'face', 'thread', 'nut', 'pin', 'screw', 'load', 'printer', 'material', 'given']);
59
+ const T = sheetThickness(what, o.sheet), given = o.given ?? {}, p = profileOf(what, profile, given), k = partSetup(what, o);
60
+ loadOk(what, o.load, 'the force across the pin at one hinge');
61
+ const sd = slotSide(what, p, o.face ?? 'top', o.thread, o.nut, k.fit, given), sc = screwOf(what, sd.thread, 'button', k.pr), clear = DOOR_DEFAULTS.clear.value;
62
+ const pin = o.pin ?? DOOR_DEFAULTS.pin.value, dsc = o.screw ?? DOOR_DEFAULTS.door.value;
63
+ let pfx, dfx; try { pfx = fixingModel(pin); dfx = screwOf(what, dsc, 'button', k.pr); } catch (e) { throw new Error(`${what}: pin and screw are threads, as 'M3' (got ${shown(pin)}, ${shown(dsc)}): ${String(e.message).replace(/^\w+: /, '')}`); }
64
+ const ph = screwOf(what, pin, 'cap', k.pr).hd, R = r3(up((ph / 2) * Math.SQRT2 + 2 * k.line, 0.1)), c = sd.cell / 2, ya = -c;
65
+ if (ya + R > -(sc.dk / 2 + FITTING_DEFAULTS.reach.value) + 1e-9) throw new Error(`${what}: on ${short(p)}'s ${mm(sd.cell)} mm face a ${mm(R)} mm knuckle over its edge leaves no room for ${an(sd.thread)} head on the slot's line: a smaller pin`);
66
+ const endBy = Math.max(FITTING_DEFAULTS.end.value * sc.hd, sc.dk / 2 + FITTING_DEFAULTS.reach.value);
67
+ // the frame's leaf: as thin as its thread lets it, then thick enough that a screw sold fits the slot nut
68
+ const least = Math.max(up(FITTING_DEFAULTS.least.value * sc.major, k.layer), 2 * k.layer), fits = sold(least, k.layer, [sd], sd.thread), tl = fits ? fits.t : least;
69
+ const kh = fixingModel(sd.thread).figures.button_head_height?.value ?? sc.major, g = r3(up(tl + kh + clear, k.layer)), za = r3(g + T), v0 = r3(ya + R + clear);
70
+ const F = o.load ?? DOOR_DEFAULTS.load.value, n = DOOR_DEFAULTS.knuckles.value, gapK = r3(2 * k.fit);
71
+ // the knuckles' length: the two risers bent at their roots by F at the pin's height, to about twice the margin
72
+ // (and long enough that its two screws' slot nuts sit side by side in the slot)
73
+ const nutLen = Math.max(...sd.nuts.map((x) => x.length)), apart = (q) => n * q + (n - 1) * gapK - 2 * endBy;
74
+ let kl = up(Math.max(2 * R + 2, 8), 0.5), stress = 0, margin = 0;
75
+ for (let i = 0; i < 60; i++) { stress = r3((6 * F * za) / (2 * kl * (2 * R) ** 2)); margin = r3(k.S / stress); if (margin >= want() && apart(kl) >= nutLen + 1 - 1e-9) break; kl += 0.5; }
76
+ const L = r3(n * kl + (n - 1) * gapK), dEnd = Math.max(FITTING_DEFAULTS.end.value * dfx.hd, dfx.dk / 2 + FITTING_DEFAULTS.reach.value);
77
+ // the screws through the door stand past the frame's leaf, so their nuts under the door clear its heads
78
+ const dn0 = nutModel(dsc), yd = r3(up(Math.max(endBy, v0 + dEnd) + clear + dn0.flats / Math.sqrt(3), 0.5)), dLeaf = r3(up(yd + dEnd - v0, 0.5));
79
+ const nutH = nutModel(pin, { kind: 'lock' }).height, lengths = [...(pfx.figures.lengths?.value ?? [])].sort((a, b) => a - b), pinLen = lengths.find((x) => x >= L + nutH + 0.5 - 1e-9 && x <= L + nutH + pfx.major + 1e-9) ?? null;
80
+ const dnut = nutModel(dsc), dLen = [...(fixingModel(dsc).figures.lengths?.value ?? [])].sort((a, b) => a - b).find((x) => x >= R + T + dnut.height - 1e-9 && x <= R + T + dnut.height + fixingModel(dsc).major + 1e-9) ?? null;
81
+ const xs = [-(L / 2 - dEnd), L / 2 - dEnd].map(r3), frameX = [-(L / 2 - endBy), L / 2 - endBy].map(r3);
82
+ const m = { kind: 'fitting', fitting: 'hinge', name: `hinge-${short(p)}-${sd.thread.toLowerCase()}-${mm(T)}mm`, title: `printed door hinge for ${short(p)}, a ${mm(T)} mm door, ${sd.thread} into the slot`,
83
+ profile: p.name, face: sd.face, thread: sd.thread, head: 'button', sheet: T, pin, screw: dsc, length: L, knuckle: kl, knuckles: n, gap: gapK, radius: R, leaf: tl, standoff: g, axis: [ya, za], edge: v0, doorLeaf: dLeaf, plate: r3(endBy), headRoom: r3(sc.dk / 2),
84
+ parts: ['frame', 'door'], frameScrews: frameX, doorScrews: xs,
85
+ screws: frameX.map((x) => ({ leaf: 'frame', thread: sd.thread, head: 'button', grip: tl, at: [x, 0, tl], axis: [0, 0, -1], nut: sd.nut.name, nutKind: sd.nut.nutKind, length: fits?.lengths[0] ?? null })),
86
+ door: xs.map((x) => ({ leaf: 'door', thread: dsc, head: 'button', at: [x, yd, r3(za + R)], axis: [0, 0, -1], length: dLen, nut: dnut.name })),
87
+ hardware: [{ kind: 'screw', name: `${pfx.thread}x${pinLen ?? '?'} cap`, thread: pfx.thread, length: pinLen, head: 'cap', count: 1, why: 'the pin' }, { kind: 'nut', name: nutModel(pin, { kind: 'lock' }).name, thread: pfx.thread, count: 1, why: 'on the pin' }],
88
+ load: { force: F, what: `${F} N across the pin, ${mm(za)} mm off the beam's face` }, stress, margin, size: { length: L, knuckle: kl, standoff: g, leaf: tl, radius: R },
89
+ volume: 0, grams: 0, material: k.mat.name, printer: k.pr.name, findings: [],
90
+ rests: [{ name: `${k.mat.name}.strength`, value: k.S }, ...['pin', 'door', 'load', 'knuckles', 'clear'].map((x) => ({ name: `DOOR_DEFAULTS.${x}`, value: DOOR_DEFAULTS[x].value, kind: DOOR_DEFAULTS[x].kind }))] };
91
+ const vf = jscad.measurements.measureVolume(hinge(m, { part: 'frame', printer: k.pr })), vd = jscad.measurements.measureVolume(hinge(m, { part: 'door', printer: k.pr }));
92
+ m.volume = r3(vf + vd); m.grams = r3((m.volume * k.density) / 1000); m.leafGrams = { frame: r3((vf * k.density) / 1000), door: r3((vd * k.density) / 1000) };
93
+ m.findings.push(fits ? finding('pass', `${sd.thread}x${fits.lengths[0]} button into the slot: through the ${mm(tl)} mm leaf, its tip between ${mm(fits.windows[0].lo)} (its nut's thread engaged) and ${mm(fits.windows[0].hi)} mm under the face`, 'fitting.screw', { values: { lengths: fits.lengths, windows: fits.windows } })
94
+ : finding('warn', `no ${sd.thread} button screw sold engages its slot nut fully through the leaf: the fasten check chooses`, 'fitting.screw', {}));
95
+ m.findings.push(finding(pinLen ? 'pass' : 'warn', pinLen ? `the pin: ${an(pfx.thread)}x${pinLen} cap screw through ${mm(L)} mm of knuckles and ${an(pfx.thread)} lock nut` : `no ${pfx.thread} cap screw sold reaches through ${mm(L)} mm of knuckles and its lock nut`, 'fitting.pin', { values: { length: pinLen, knuckles: L } }));
96
+ m.findings.push(finding('info', `the door stands ${mm(g)} mm off the face (the ${mm(tl)} mm leaf, a ${mm(kh)} mm button head and ${mm(clear)} mm), its axis ${mm(-ya)} mm outside the slot's line at the door's outer face, ${mm(za)} mm up, its hinge-side edge ${mm(v0 - ya)} mm from the axis: so it swings out and away from the frame, up to 180°`, 'fitting.swing', { values: { standoff: g, axis: [ya, za], edge: v0 } }));
97
+ closingFindings(m, { S: k.S, sizeText: `${mm(L)} mm long, ${n} knuckles of ${mm(kl)} mm round ${an(pfx.thread)} pin, ${mm(R)} mm in radius; the frame's leaf ${mm(tl)} mm thick, the door's ${mm(R)} mm, ${mm(dLeaf)} mm onto the door`, marginText: `under ${m.load.what}, the frame's two risers bend at their roots to ${mm(stress)} MPa`, pose: 'the frame\'s leaf as it lies, the door\'s leaf face down, the pin\'s hole a teardrop' });
98
+ return m;
99
+ }
100
+
101
+ /**
102
+ * A hinge's leaves: part 'frame' (as it prints, which is as it lies) or 'door' (face down to print); pose 'fit' puts
103
+ * the door's leaf where it sits with the door closed. @param {object} m @param {{ part?: 'frame' | 'door', pose?: 'print' | 'fit', printer?: object, ops?: object }} [o] @returns {object}
104
+ */
105
+ export function hinge(m, o = {}) {
106
+ if (m?.fitting !== 'hinge') throw new Error(`hinge: give a hinge's model (hingeModel), not ${shown(m)}`);
107
+ const part = o.part ?? 'frame';
108
+ if (!['frame', 'door'].includes(part)) throw new Error(`hinge: part is frame or door (got ${shown(o.part)})`);
109
+ const pr = printerOf('hinge', o.printer), fx = { printer: pr }, [ya, za] = m.axis, R = m.radius, L = m.length, kl = m.knuckle, gk = m.gap, tl = m.leaf;
110
+ const seg = (i) => [-L / 2 + i * (kl + gk), -L / 2 + i * (kl + gk) + kl], along = (g, x0, x1) => translate([x0, 0, 0], transform([0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1], extrudeLinear({ height: x1 - x0 }, g)));
111
+ const sec = (pts) => polygon({ points: ccw(pts) }), pinAt = (zc, toward) => hole(m.pin, { kind: 'clearance', into: '+x', depth: L + 2, at: [-L / 2 - 1, toward * ya, zc], ...fx });
112
+ if (part === 'frame') {
113
+ // its plate on the face; at each outer knuckle a riser from the plate to the knuckle, its root toward the slot rounded
114
+ const plate = sec([[ya - R, 0], [m.plate, 0], [m.plate, tl], [ya - R, tl]]);
115
+ // (its root's round no wider than the room left before the heads on the slot's line, so they seat flat)
116
+ const rr = Math.max(0.2, Math.min(2, -(m.headRoom ?? 0) - (ya + R) - 0.5));
117
+ const riser = sec(roundConcave(ccw([[ya - R, 0], [ya + R + rr, 0], [ya + R + rr, tl], [ya + R, tl], [ya + R, za], ...arc(ya, za, R, 0, Math.PI, 16).slice(1, -1), [ya - R, za]]), rr, null, 8));
118
+ const parts = [along(plate, -L / 2, L / 2), ...[0, m.knuckles - 1].map((i) => along(riser, ...seg(i)))];
119
+ const holes = [pinAt(za, 1), ...m.frameScrews.map((x) => hole(m.thread, { kind: 'clearance', into: '-z', depth: tl + 2, at: [x, 0, tl + 1], ...fx }))];
120
+ return Object.assign(combine(parts, holes, o.ops), { model: m });
121
+ }
122
+ // the door's leaf, drawn in its print frame (X = x, Y = -y, Z = za + R - z): its plate on the bed, its knuckle a
123
+ // round standing on it, the pin's hole a teardrop pointing up
124
+ const y0 = -ya, yE = -(m.edge + m.doorLeaf), [m0, m1] = seg(1);
125
+ const plate = sec([[yE, 0], [-m.edge, 0], [-m.edge, R], [yE, R]]), neck = sec([[-m.edge, 0], [y0 + R, 0], ...arc(y0, R, R, 0, Math.PI, 24), [-m.edge, R]]); // (its outer lower corner square, so nothing hangs over the bed)
126
+ const parts = [along(plate, -L / 2, L / 2), along(neck, m0, m1)];
127
+ const holes = [hole(m.pin, { kind: 'clearance', into: '+x', depth: L + 2, at: [-L / 2 - 1, y0, R], ...fx }), ...m.door.map((s) => hole(m.screw, { kind: 'clearance', into: '+z', depth: R + 2, at: [s.at[0], -s.at[1], -1], ...fx }))];
128
+ const g = combine(parts, holes, o.ops);
129
+ return Object.assign(o.pose === 'fit' ? transform([1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, za + R, 1], g) : g, { model: m });
130
+ }
131
+
132
+ // ---------- a handle ----------
133
+ /**
134
+ * A printed pull handle for a door: a grip between two feet, screwed from inside the door into a pilot in each foot,
135
+ * room under the grip for the fingers. Sized from a named pull by beam formulas to about twice the margin. It prints
136
+ * on its side, its outline the first layer, its pilots lying as teardrops.
137
+ * @param {{ sheet: number, thread?: string, span?: number, load?: number, printer?: object, material?: string | object }} o
138
+ * sheet: the door's thickness, for the screws' length; span: between the screws (default 64)
139
+ * @returns {object} its model
140
+ */
141
+ export function handleModel(o = {}) {
142
+ const what = 'handleModel';
143
+ options(what, o ?? {}, ['sheet', 'thread', 'span', 'load', 'printer', 'material']);
144
+ const T = sheetThickness(what, o.sheet), k = partSetup(what, o), th = o.thread ?? DOOR_DEFAULTS.door.value, span = o.span ?? DOOR_DEFAULTS.span.value;
145
+ if (!(isNum(span) && span >= 30 && span <= 300)) throw new Error(`${what}: span is between the screws, in mm, from 30 to 300 (got ${shown(o.span)})`);
146
+ loadOk(what, o.load, 'the pull on the handle');
147
+ const sc = screwOf(what, th, 'button', k.pr), fx = fixingModel(th), F = o.load ?? DOOR_DEFAULTS.pull.value, b = r3(up(Math.max(12, fx.major * 3), 0.5));
148
+ const pilot = fx.figures.pilot_depth?.value ?? 2 * fx.major, foot = r3(up(Math.max(2 * fx.major + 2 * k.line * 3, 8), 0.5)), finger = DOOR_DEFAULTS.finger.value;
149
+ const M = (F * span) / 4, hb = r3(Math.max(up(bendT(M, b, k.S, want()), 0.5), 6)), H = r3(finger + hb), stress = r3((6 * M) / (b * hb * hb)), margin = r3(k.S / stress);
150
+ const x0 = -span / 2 - foot / 2, x1 = span / 2 + foot / 2, r = r3(Math.min(hb / 2, finger / 3));
151
+ const loop = roundConcave(ccw([[x0, 0], [-span / 2 + foot / 2, 0], [-span / 2 + foot / 2, finger], [span / 2 - foot / 2, finger], [span / 2 - foot / 2, 0], [x1, 0], [x1, H], [x0, H]]), r, null, 10).map(([x, y]) => [r3(x), r3(y)]);
152
+ const lengths = [...(fx.figures.lengths?.value ?? [])].sort((a, z) => a - z), len = lengths.find((x) => x >= T + Math.min(pilot, 1.5 * fx.major) - 1e-9 && x <= T + Math.min(pilot + 2, H - 1) + 1e-9) ?? null;
153
+ const m = { kind: 'fitting', fitting: 'handle', name: `handle-${Math.round(span)}-${th.toLowerCase()}`, title: `printed door handle, ${mm(span)} mm between its screws, ${th}`, thread: th, sheet: T, span, width: b, height: H, grip: hb, finger, foot, section: loop, pilot: r3(Math.min(pilot + 2, H - 1)),
154
+ screws: [-span / 2, span / 2].map((y) => ({ thread: th, head: 'button', at: [0, y, -T], axis: [0, 0, 1], length: len, into: 'pilot' })),
155
+ load: { force: F, what: `${F} N pulling the grip's middle` }, stress, margin, size: { span, height: H, grip: hb, width: b }, volume: 0, grams: 0, material: k.mat.name, printer: k.pr.name, findings: [],
156
+ rests: [{ name: `${k.mat.name}.strength`, value: k.S }, ...['span', 'finger', 'pull'].map((x) => ({ name: `DOOR_DEFAULTS.${x}`, value: DOOR_DEFAULTS[x].value, kind: DOOR_DEFAULTS[x].kind }))] };
157
+ weigh(m, handle(m, { printer: k.pr }), k.density);
158
+ m.findings.push(finding(len ? 'pass' : 'warn', len ? `${th}x${len} button from inside the door, through its ${mm(T)} mm into each foot's pilot` : `no ${th} button screw sold fits through the door into the feet: the fasten check chooses`, 'fitting.screw', { values: { length: len } }));
159
+ closingFindings(m, { S: k.S, sizeText: `${mm(H)} mm high, ${mm(b)} mm wide, ${mm(finger)} mm under the grip for the fingers, its grip ${mm(hb)} mm deep`, marginText: `under ${m.load.what}, the grip bends to ${mm(stress)} MPa`, pose: 'on its side, its outline the first layer' });
160
+ return m;
161
+ }
162
+ /** A handle's solid: on its side to print, or fitted (pose 'fit', its feet on the door at z = 0). @param {object} m @param {{ pose?: 'print' | 'fit', printer?: object, ops?: object }} [o] @returns {object} */
163
+ export function handle(m, o = {}) {
164
+ if (m?.fitting !== 'handle') throw new Error(`handle: give a handle's model (handleModel), not ${shown(m)}`);
165
+ const pr = printerOf('handle', o.printer), g = sidePart({ loop: m.section, width: m.width, holes: [-m.span / 2, m.span / 2].map((y) => ({ thread: m.thread, y, depth: m.pilot, from: 'face', kind: 'pilot' })), pr, ops: o.ops });
166
+ // fitted: the print frame's X runs along the handle (fitted y), Z across it (fitted x)
167
+ return Object.assign(o.pose === 'fit' ? transform(sideToFit(m.width), g) : g, { model: m });
168
+ }
169
+
170
+ // ---------- a latch and a magnet catch ----------
171
+ /**
172
+ * A printed turn-button latch: a post on the latch beam's face, screwed into a slot nut through its middle, with a tab
173
+ * on top that turns over the door's edge to hold it shut. Shown at rest, turned over the door. It prints tab down.
174
+ * @param {string | object} profile @param {{ sheet: number, standoff: number, edge?: number, face?: string, thread?: string, nut?: string, load?: number, printer?: object, material?: string | object, given?: object }} o
175
+ * standoff: the door's inner face over the beam's (a hinge's); edge: the door's edge, from the slot's line (default a clip's)
176
+ * @returns {object} its model
177
+ */
178
+ export function latchModel(profile, o = {}) {
179
+ const what = 'latchModel';
180
+ options(what, o ?? {}, ['sheet', 'standoff', 'edge', 'face', 'thread', 'nut', 'load', 'printer', 'material', 'given']);
181
+ const T = sheetThickness(what, o.sheet), given = o.given ?? {}, p = profileOf(what, profile, given), k = partSetup(what, o);
182
+ if (!(isNum(o.standoff) && o.standoff >= 0)) throw new Error(`${what}: standoff is the door's inner face over the beam's face, in mm (a hinge's standoff) (got ${shown(o.standoff)})`);
183
+ loadOk(what, o.load, 'the door pushing out at the latch');
184
+ const sd = slotSide(what, p, o.face ?? 'top', o.thread, o.nut, k.fit, given), sc = screwOf(what, sd.thread, 'button', k.pr), clear = DOOR_DEFAULTS.clear.value;
185
+ const rp = r3(up(sc.dk / 2 + FITTING_DEFAULTS.reach.value, 0.5)), edge = o.edge ?? r3(rp + clear), grip = PANEL_DEFAULTS.grip.value, reach = r3(edge + grip);
186
+ if (edge < rp + clear - 1e-9) throw new Error(`${what}: the door's edge ${mm(edge)} mm from the slot's line runs into the latch's ${mm(rp)} mm post: ${mm(rp + clear)} mm or more`);
187
+ const F = o.load ?? PANEL_DEFAULTS.load.value, M = F * (reach - rp), tt0 = Math.max(up(bendT(M, 2 * rp, k.S, want()), k.layer), 4 * k.layer);
188
+ const post = r3(o.standoff + T + 0.5), fits = sold(r3(post + tt0), k.layer, [sd], sd.thread), H = fits ? fits.t : r3(post + tt0), tt = r3(H - post);
189
+ const stress = r3((6 * M) / (2 * rp * tt * tt)), margin = r3(k.S / stress);
190
+ const m = { kind: 'fitting', fitting: 'latch', name: `latch-${short(p)}-${sd.thread.toLowerCase()}-${mm(T)}mm`, title: `printed turn-button latch for ${short(p)}, a ${mm(T)} mm door, ${sd.thread}`, profile: p.name, face: sd.face, thread: sd.thread, head: 'button',
191
+ sheet: T, standoff: o.standoff, edge, post, height: H, tab: tt, radius: rp, reach,
192
+ screws: [{ thread: sd.thread, head: 'button', grip: H, at: [0, 0, H], axis: [0, 0, -1], nut: sd.nut.name, nutKind: sd.nut.nutKind, length: fits?.lengths[0] ?? null }],
193
+ load: { force: F, what: `${F} N of the door pushing out under the tab` }, stress, margin, size: { height: H, tab: tt, reach }, volume: 0, grams: 0, material: k.mat.name, printer: k.pr.name, findings: [],
194
+ rests: [{ name: `${k.mat.name}.strength`, value: k.S }, { name: 'PANEL_DEFAULTS.load', value: F, kind: PANEL_DEFAULTS.load.kind }] };
195
+ weigh(m, latch(m, { printer: k.pr }), k.density);
196
+ m.findings.push(fits ? finding('pass', `${sd.thread}x${fits.lengths[0]} button through its ${mm(H)} mm into the slot nut: the latch turns on it, done up until the tab just drags`, 'fitting.screw', { values: { lengths: fits.lengths } }) : finding('warn', `no ${sd.thread} button screw sold fits through the latch into its nut`, 'fitting.screw', {}));
197
+ closingFindings(m, { S: k.S, sizeText: `a ${mm(2 * rp)} mm post ${mm(post)} mm high (the door's standoff, its ${mm(T)} mm and 0.5 mm), a ${mm(tt)} mm tab reaching ${mm(reach)} mm from the slot's line over the door's edge at ${mm(edge)} mm`, marginText: `under ${m.load.what}, the tab bends to ${mm(stress)} MPa`, pose: 'tab down, its post up' });
198
+ return m;
199
+ }
200
+ /** A latch's solid: tab down to print, or fitted and turned over the door (pose 'fit'). @param {object} m @param {{ pose?: 'print' | 'fit', printer?: object, ops?: object }} [o] @returns {object} */
201
+ export function latch(m, o = {}) {
202
+ if (m?.fitting !== 'latch') throw new Error(`latch: give a latch's model (latchModel), not ${shown(m)}`);
203
+ const pr = printerOf('latch', o.printer), H = m.height, rp = m.radius, tt = m.tab, r0 = 0.6;
204
+ // print frame: z = H - z(fit), y = -y(fit); the tab a stadium on the bed, the post standing on it with a 45° collar
205
+ const tab = polygon({ points: ccw([...arc(0, 0, rp, 0, Math.PI, 16), ...arc(0, -(m.reach - rp), rp, Math.PI, 2 * Math.PI, 16)]) }); // (along -Y: toward the door once fitted)
206
+ // (the post a little inside the tab's width, its root a 45° collar out to it)
207
+ const post = translate([0, 0, tt], cylinder({ radius: rp - r0, height: H - tt, center: [0, 0, (H - tt) / 2], segments: 40 }));
208
+ const collar = hull(translate([0, 0, tt], cylinder({ radius: rp, height: 0.01, segments: 40 })), translate([0, 0, tt + r0], cylinder({ radius: rp - r0, height: 0.01, segments: 40 })));
209
+ const g = combine([extrudeLinear({ height: tt }, tab), post, collar], [hole(m.thread, { kind: 'clearance', into: '+z', depth: H + 2, at: [0, 0, -1], printer: pr })], o.ops);
210
+ return Object.assign(o.pose === 'fit' ? transform([1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, H, 1], g) : g, { model: m });
211
+ }
212
+
213
+ /**
214
+ * A printed magnet catch: a block on a beam's face under the door's edge, screwed into a slot nut on a step lower than
215
+ * its tower, a disc magnet pressed into the tower's top; a steel washer stuck to the door's inner face over it is the
216
+ * strike. The tower's top stops the washer's thickness and a half millimetre under the door. It prints on its side.
217
+ * @param {string | object} profile @param {{ standoff: number, edge?: number, magnet?: number[], face?: string, thread?: string, nut?: string, printer?: object, material?: string | object, given?: object }} o
218
+ * standoff: the door's (a hinge's); edge: the door's edge from the slot's line (default the head's room); magnet: [diameter, thickness]
219
+ * @returns {object} its model
220
+ */
221
+ export function magnetCatchModel(profile, o = {}) {
222
+ const what = 'magnetCatchModel';
223
+ options(what, o ?? {}, ['standoff', 'edge', 'magnet', 'face', 'thread', 'nut', 'printer', 'material', 'given']);
224
+ const given = o.given ?? {}, p = profileOf(what, profile, given), k = partSetup(what, o);
225
+ if (!(isNum(o.standoff) && o.standoff > 0)) throw new Error(`${what}: standoff is the door's inner face over the beam's face, in mm, above 0 (a hinge's standoff) (got ${shown(o.standoff)})`);
226
+ const [dm, hm] = o.magnet ?? DOOR_DEFAULTS.magnet.value;
227
+ if (!(isNum(dm) && isNum(hm) && dm > 0 && hm > 0)) throw new Error(`${what}: magnet is [diameter, thickness] in mm (got ${shown(o.magnet)})`);
228
+ const sd = slotSide(what, p, o.face ?? 'top', o.thread, o.nut, k.fit, given), sc = screwOf(what, sd.thread, 'button', k.pr), w = sd.cell, wall = r3(up(3 * k.line, 0.1));
229
+ const washers = ['M3', 'M4', 'M5', 'M6', 'M8', 'M10'].map((t) => { try { return washerModel(t); } catch { return null; } }).filter(Boolean), strike = washers.find((x) => x.diameter >= dm - 1e-9) ?? washers.at(-1);
230
+ const top = r3(o.standoff - strike.thickness - 0.5), least = Math.max(up(FITTING_DEFAULTS.least.value * sc.major, k.layer), 2 * k.layer), fits = sold(least, k.layer, [sd], sd.thread), step = fits ? fits.t : least;
231
+ const kh = fixingModel(sd.thread).figures.button_head_height?.value ?? sc.major;
232
+ if (top < hm + 2 * k.layer) throw new Error(`${what}: a ${mm(o.standoff)} mm standoff leaves ${mm(top)} mm under the strike, too little for a ${mm(hm)} mm magnet and a floor`);
233
+ if (step + kh + DOOR_DEFAULTS.clear.value > o.standoff + 1e-9) throw new Error(`${what}: the screw's head on its ${mm(step)} mm step stands ${mm(step + kh)} mm off the face, into a ${mm(o.standoff)} mm standoff`);
234
+ const y0 = r3(up(Math.max(sc.dk / 2 + FITTING_DEFAULTS.reach.value, o.edge ?? 0), 0.5)), y1 = r3(y0 + dm + 2 * wall), endBy = r3(up(Math.max(FITTING_DEFAULTS.end.value * sc.hd, sc.dk / 2 + FITTING_DEFAULTS.reach.value), 0.5));
235
+ const loop = roundConcave(ccw([[-endBy, 0], [y1, 0], [y1, top], [y0, top], [y0, step], [-endBy, step]]), Math.min(2, (top - step) / 2), null, 8).map(([y, z]) => [r3(y), r3(z)]);
236
+ const m = { kind: 'fitting', fitting: 'magnet-catch', name: `magnet-catch-${short(p)}-${mm(dm)}x${mm(hm)}`, title: `printed magnet catch for ${short(p)}, a ${mm(dm)} x ${mm(hm)} mm magnet`, profile: p.name, face: sd.face, thread: sd.thread, head: 'button', width: w,
237
+ standoff: o.standoff, top, step, magnet: [dm, hm], pocket: r3((y0 + y1) / 2), section: loop, strike: strike.name, tongue: { slot: sd.slot.name, ...sd.tongue, nut: sd.nut.name },
238
+ screws: [{ thread: sd.thread, head: 'button', grip: step, at: [0, 0, step], axis: [0, 0, -1], nut: sd.nut.name, nutKind: sd.nut.nutKind, length: fits?.lengths[0] ?? null }],
239
+ hardware: [{ kind: 'magnet', name: `${mm(dm)} x ${mm(hm)} mm disc magnet`, count: 1, why: 'pressed into the catch' }, { kind: 'washer', name: strike.name, thread: strike.thread, count: 1, why: 'stuck to the door\'s inner face over the magnet, the strike' }],
240
+ load: { force: 0, what: 'the magnet\'s pull, not checked' }, stress: 0, margin: Infinity, size: { top, step, magnet: [dm, hm] }, volume: 0, grams: 0, material: k.mat.name, printer: k.pr.name, findings: [],
241
+ rests: [{ name: 'DOOR_DEFAULTS.magnet', value: [dm, hm], kind: DOOR_DEFAULTS.magnet.kind }] };
242
+ weigh(m, magnetCatch(m, { printer: k.pr }), k.density);
243
+ m.findings.push(fits ? finding('pass', `${sd.thread}x${fits.lengths[0]} button into the slot through its ${mm(step)} mm step, its head ${mm(o.standoff - step - kh)} mm under the door`, 'fitting.screw', { values: { lengths: fits.lengths } }) : finding('warn', `no ${sd.thread} button screw sold fits through the step into its nut`, 'fitting.screw', {}));
244
+ m.findings.push(finding('info', `${m.title}: its tower ${mm(top)} mm off the face (the standoff less the ${strike.name}'s ${mm(strike.thickness)} mm and 0.5 mm), the magnet's pocket ${mm(hm)} mm deep at ${mm(m.pocket)} mm from the slot's line; the magnet's pull is not checked (an estimate: no maker's figure is held)`, 'fitting.size', { values: { ...m.size } }));
245
+ m.findings.push(finding('info', 'it is drawn to print on its side, its section the first layer, the magnet\'s pocket a teardrop: no supports', 'fitting.printable', { values: { pose: 'on its side' } }));
246
+ m.findings.push(finding('info', `it weighs ${mm(m.grams)} g of ${m.material} (${mm(m.volume)} mm³)`, 'fitting.mass', { values: { grams: m.grams, volume: m.volume } }));
247
+ return m;
248
+ }
249
+ /** A magnet catch's solid: on its side to print, or fitted. @param {object} m @param {{ pose?: 'print' | 'fit', tongues?: boolean, printer?: object, ops?: object }} [o] @returns {object} */
250
+ export function magnetCatch(m, o = {}) {
251
+ if (m?.fitting !== 'magnet-catch') throw new Error(`magnetCatch: give a magnet catch's model (magnetCatchModel), not ${shown(m)}`);
252
+ const pr = printerOf('magnetCatch', o.printer), g = sidePart({ loop: m.section, width: m.width, tongue: o.tongues === false ? null : { at: 0, ...m.tongue }, holes: [{ thread: m.thread, y: 0, top: m.step }], pockets: [{ y: m.pocket, top: m.top, d: m.magnet[0] + pfig(pr, 'fit'), depth: m.magnet[1] }], pr, ops: o.ops });
253
+ return Object.assign(o.pose === 'fit' ? transform(sideToFit(m.width), g) : g, { model: m });
254
+ }