@rulecad/cad 0.7.53 → 0.7.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/beams.mjs ADDED
@@ -0,0 +1,147 @@
1
+ // Beams in assemblies (@rulecad/frames).
2
+ //
3
+ // A beam item is a length of a profile: { "id": "x1", "beam": { "profile": "2020-misumi-hfs5", "length": 300 },
4
+ // "from": [0, 0, 0], "to": [300, 0, 0], "roll": 0 }, or placed with at and rotate as any item is. It is bought, so it is
5
+ // drawn faint (a reference), goes on cad list by profile and length, and is in the overlap check by its envelope.
6
+ // Its frame is the beam's own: end a at z = 0, end b at z = length, top +y, front -x. Placed by its ends, its z runs
7
+ // from to to, and at roll 0 its top faces up (+z), or +y when it stands upright (within 0.1° of z); roll turns it
8
+ // about its own axis, a toward b, right-handed.
9
+ // Its addresses are anchors (lib/assembly.mjs reads them through beamAnchor): x1.a, x1.b, x1.a.1, x1.top, x1.top@120,
10
+ // x1.top@-20, x1.top@50%, x1.top.2@120.
11
+ // Its operations ("ops": cut, mitre, tap, access, drill, counterbore, pocket, notch, deburr) are @rulecad/frames': each
12
+ // is cut into its preview, a mitre into its envelope too, and their findings (beam.op) are the beam's.
13
+ import * as frames from '@rulecad/frames';
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { beamModel, beam, beamAnchor, cutList, beamMarks, beamSheet } from '@rulecad/frames';
17
+ import { frame } from '@rulecad/model-link';
18
+ import { RULE_DIRS, paths } from './workspace.mjs';
19
+ import { named } from './parts.mjs';
20
+ import { referenceBuilt } from './bought.mjs';
21
+ import { framesContext as contextIn, givenFor } from './frames.mjs';
22
+
23
+ const KEYS = ['profile', 'length', 'printed', 'material', 'ops'];
24
+ const OP_NUMBERS = ['angle', 'depth', 'diameter', 'length', 'radius'];
25
+ const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
26
+ const mm = (x) => String(+Number(x).toFixed(2));
27
+ const strip = (e) => String(e?.message ?? e).replace(/^(beamModel|beamAnchor|profileModel|beam): /, '');
28
+ /** This workspace's frames sets (lib/frames.mjs framesContext over its rules/) */
29
+ export const framesContext = () => contextIn(RULE_DIRS[0]);
30
+
31
+ /**
32
+ * The beam an item names, its length worked out: { model, length }. A length may be an expression; left out, it is the
33
+ * distance from from to to. Refused by name: an unknown key, no profile, a printed beam (a later release), a length
34
+ * that disagrees with its ends, ends and at both given.
35
+ * @param {object} it the item @param {(x: any) => number} num the assembly's expressions @param {object} [context] framesContext()'s
36
+ */
37
+ export function beamOf(it, num, context = framesContext()) {
38
+ const what = `item ${it.id}`, b = it.beam;
39
+ if (!b || typeof b !== 'object' || Array.isArray(b)) throw new Error(`${what}: beam is { "profile", "length", "material" } (got ${shown(b)})`);
40
+ for (const k of Object.keys(b)) if (!KEYS.includes(k)) throw new Error(`${what}: a beam has no "${k}": it takes ${KEYS.join(', ')}`);
41
+ if (typeof b.profile !== 'string' || !b.profile) throw new Error(`${what}: beam.profile names a profile, such as 2020-misumi-hfs5 (got ${shown(b.profile)})`);
42
+ if (b.printed != null && typeof b.printed !== 'boolean') throw new Error(`${what}: beam.printed is true or false (got ${shown(b.printed)})`);
43
+ if (b.printed) throw new Error(`${what}: a printed beam ("printed": true) is a later release${b.ops?.length ? ', and its ops become features of the print then' : ''}: leave printed out for a bought beam of ${b.profile}`);
44
+ if (b.ops != null && !Array.isArray(b.ops)) throw new Error(`${what}: beam.ops is a list of operations, [{ "op": "tap", "at": "a" }] (got ${shown(b.ops)})`);
45
+ // an operation's numbers may be expressions, as a length is
46
+ const ops = (b.ops ?? []).map((o) => (o && typeof o === 'object' && !Array.isArray(o) ? Object.fromEntries(Object.entries(o).map(([k, v]) => [k, OP_NUMBERS.includes(k) && v != null ? num(v) : k === 'size' && Array.isArray(v) ? v.map(num) : v])) : o));
47
+ if (b.material != null && typeof b.material !== 'string') throw new Error(`${what}: beam.material is a material set's name, such as al6063-t5 (got ${shown(b.material)})`);
48
+ const ends = it.from != null || it.to != null;
49
+ if (ends && (it.from == null || it.to == null)) throw new Error(`${what}: a beam placed by its ends gives both: from (end a) and to (end b)`);
50
+ if (ends && (it.at != null || it.rotate != null)) throw new Error(`${what}: a beam is placed by its ends (from, to, roll) or by at and rotate, not both`);
51
+ if (!ends && it.roll != null) throw new Error(`${what}: roll turns a beam placed by its ends: give from and to, or turn it with rotate`);
52
+ if (ends && it.repeat) throw new Error(`${what}: a beam placed by its ends is one beam: give each its own item, or place it with at and repeat`);
53
+ for (const k of ['from', 'to']) if (ends && !(Array.isArray(it[k]) && it[k].length === 3)) throw new Error(`${what}: ${k} is a point, [x, y, z] (got ${shown(it[k])})`);
54
+ const span = ends ? Math.hypot(...[0, 1, 2].map((i) => num(it.to[i]) - num(it.from[i]))) : null;
55
+ if (b.length == null && span == null) throw new Error(`${what}: give the beam a length, or place it by its ends (from and to) so the length is theirs`);
56
+ const length = b.length != null ? num(b.length) : span;
57
+ if (!(Number.isFinite(length) && length > 0)) throw new Error(`${what}: a beam's length is above 0 mm (got ${shown(b.length ?? length)}${b.length == null ? ': its ends are at one point' : ''})`);
58
+ if (span != null && Math.abs(span - length) > 1e-3) throw new Error(`${what}: its length is ${mm(length)} mm, and its ends are ${mm(span)} mm apart: leave the length out, or move an end`);
59
+ const given = givenFor(context, b.profile);
60
+ let model;
61
+ try {
62
+ model = beamModel(frames.profileModel(b.profile, {}, given), { length, ...(b.material ? { material: b.material } : {}), ...(ops.length ? { ops } : {}), given });
63
+ } catch (e) { throw new Error(`${what}: ${strip(e)}`); }
64
+ return { model, length };
65
+ }
66
+
67
+ /**
68
+ * Where a beam placed by its ends goes: its frame as 12 numbers by rows (z from end a to end b, top up, turned by roll),
69
+ * or null for a beam placed by at and rotate.
70
+ * @param {object} it @param {(x: any) => number} num @returns {number[] | null}
71
+ */
72
+ export function beamPlace(it, num) {
73
+ if (it.from == null) return null;
74
+ const a = it.from.map(num), b = it.to.map(num), z = b.map((v, k) => v - a[k]), l = Math.hypot(...z), u = z.map((v) => v / l);
75
+ const up = Math.abs(u[2]) > Math.cos(0.1 * Math.PI / 180) ? [0, 1, 0] : [0, 0, 1], d = up[0] * u[0] + up[1] * u[1] + up[2] * u[2];
76
+ const yl = up.map((v, k) => v - d * u[k]), n = Math.hypot(...yl), y = yl.map((v) => v / n);
77
+ const x = [y[1] * u[2] - y[2] * u[1], y[2] * u[0] - y[0] * u[2], y[0] * u[1] - y[1] * u[0]]; // y × z
78
+ const r = (it.roll != null ? num(it.roll) : 0) * Math.PI / 180, c = Math.cos(r), s = Math.sin(r);
79
+ return frame(a, u, x.map((v, k) => c * v + s * y[k]));
80
+ }
81
+
82
+ /**
83
+ * An item with "beam", built as a bought reference: its preview solid as the part, its envelope for the overlap check,
84
+ * its named anchors (ends, end bores, faces at mid-length) for joints and fits, and its figures as values (x1.length).
85
+ * @param {object} it @param {(x: any) => number} num @param {string} id
86
+ */
87
+ export function beamBuilt(it, num, id, context = framesContext()) {
88
+ const { model: m, length } = beamOf(it, num, context);
89
+ const meta = { body: { label: `${m.profile.name} x ${mm(length)} mm` } };
90
+ const parts = named({ body: beam(m) }, meta), link = named({ body: beam(m, { display: 'link' }) }, meta)[0];
91
+ parts[0].collide = link.geometry; // (the overlap check measures the envelope: light, and a beam's slots hold nothing else)
92
+ const anchors = Object.fromEntries(Object.entries(m.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis, ref: a.ref }]));
93
+ const values = { length, width: m.profile.width, height: m.profile.height, area: m.area, ...(m.mass != null ? { mass: m.mass } : {}) };
94
+ const entries = Object.entries(m.profile.figures).filter(([, f]) => typeof f?.value === 'number').map(([k, f]) => ({ name: `${m.profile.name}.${k}`, value: f.value, unit: f.unit, rule: f.rule, kind: f.kind, source: f.source, checked: f.checked, set: m.profile.name }));
95
+ const grams = m.weight.sheet ?? m.mass; // (weighed by the sheet where it gives a mass per metre: a light section's drawn outline can be 10 to 20% heavy)
96
+ return referenceBuilt({ id, key: 'beam', objName: `beam:${m.profile.name}`, name: m.profile.name, parts, anchors, entries, values,
97
+ extra: { beam: m, bought: { set: m.profile.name, variant: null, part: 'beam', mass: grams != null ? grams / 1000 : null, length } } });
98
+ }
99
+
100
+ /**
101
+ * An anchor on a beam by its address (a, b, a.1, top, top@120, top@-20, top@50%, top.2@120), as a frame of 12 numbers in
102
+ * the beam's own frame. Past the beam's end, or a name it does not have: refused by name, with its length.
103
+ * @param {object} m the beam's model @param {string} address what follows the item's id @param {string} what who asks
104
+ */
105
+ export function beamAddress(m, address, what) {
106
+ let a;
107
+ try { a = beamAnchor(m, address); } catch (e) { throw new Error(`${what}: ${strip(e)}`); }
108
+ return frame(a.origin, a.axis, a.ref);
109
+ }
110
+
111
+ /** The assembly's beams, nested ones too, as { id, beam } for @rulecad/frames' cut list. @param {object} s a built assembly */
112
+ export const beamsIn = (s) => s.objects.filter((o) => o.beam && !o.unplaced).map((o) => ({ id: o.id, beam: o.beam }));
113
+
114
+ /** Each beam's mark: beams that are the same share one (A, B, ...), as the cut list and the sheets name them. @returns {Map<string, string>} item to mark */
115
+ export function marksOf(objects) {
116
+ const list = objects.filter((o) => o.beam && !o.unplaced), out = new Map();
117
+ if (list.length) for (const m of beamMarks(list.map((o) => ({ id: o.id, beam: o.beam })))) for (const id of m.items) out.set(id, m.mark);
118
+ return out;
119
+ }
120
+
121
+ /** The cut list of an assembly's beams (frames' cutList), or null where it has none. @param {object} s a built assembly */
122
+ export function cutListOf(s) { const b = beamsIn(s); return b.length ? cutList(b) : null; }
123
+
124
+ /** The cut list as the list and the build page keep it: no beam models, the numbers and words only. */
125
+ export const cutListData = (c) => c && { marks: c.marks.map(({ beam, ...m }) => m), stock: c.stock, totals: c.totals, rules: Object.fromEntries(Object.entries(c.rules).map(([k, r]) => [k, { value: r.value, unit: r.unit, kind: r.kind }])) };
126
+
127
+ /** The sheet files cad beams writes for an assembly, by mark: exports/<project>/<assembly>.beam-<mark>.svg */
128
+ export const sheetFile = (s, mark) => paths.exports(s.project, `${s.name}.beam-${mark}.svg`);
129
+
130
+ /**
131
+ * One cut-and-drill sheet per mark, written to exports/<project>/<assembly>.beam-<mark>.svg, old sheets of this
132
+ * assembly removed. @param {object} s a built assembly @returns {{ mark: string, file: string, items: string[], scale: number }[]}
133
+ */
134
+ export function writeBeamSheets(s) {
135
+ const c = cutListOf(s), dir = paths.exports(s.project), base = `${s.name}.beam-`;
136
+ if (fs.existsSync(dir)) for (const f of fs.readdirSync(dir)) if (f.startsWith(base) && f.endsWith('.svg')) fs.rmSync(path.join(dir, f));
137
+ if (!c) return [];
138
+ fs.mkdirSync(dir, { recursive: true });
139
+ return c.marks.map((m) => { const sh = beamSheet(m.beam, { mark: m.mark, items: m.items, grams: m.grams }), file = sheetFile(s, m.mark); fs.writeFileSync(file, sh.svg); return { mark: m.mark, file, items: m.items, scale: sh.scale }; });
140
+ }
141
+
142
+ /** Each beam's own findings (its mass beside the sheet's, its length beside the stock's), named by item; and the cut list's (frame.cut). */
143
+ export function beamFindings(s, f) {
144
+ for (const o of s.objects) if (o.beam && !o.unplaced) for (const x of o.beam.findings) f(x.level, `${o.id}: ${x.text}`, null, { code: x.code, ...(x.values ? { values: x.values } : {}), refs: { item: o.id, profile: o.beam.profile.name, length: o.beam.length, ...(x.rule ? { rule: x.rule } : {}) } });
145
+ const c = cutListOf(s);
146
+ if (c) for (const x of c.findings) f(x.level, x.text, null, { code: x.code, ...(x.values ? { values: x.values } : {}), refs: x.refs });
147
+ }
package/lib/bought.mjs CHANGED
@@ -101,5 +101,5 @@ export function boughtBuilt(spec, it, num, id) {
101
101
 
102
102
  // One line in the check for each bought item, so the shopping list and the wiring can read it
103
103
  export function boughtFindings(s, f) {
104
- for (const o of s.objects) if (o.bought) f('info', `${o.id}: ${o.bought.set}${o.bought.variant ? ` (${o.bought.variant})` : ''}, a ${o.bought.part}`, null, { code: 'bought.item', refs: { item: o.id, set: o.bought.set, variant: o.bought.variant, part: o.bought.part } });
104
+ for (const o of s.objects) if (o.bought) f('info', `${o.id}: ${o.bought.set}${o.bought.variant ? ` (${o.bought.variant})` : ''}${o.bought.length != null ? ` x ${Number(o.bought.length.toFixed(2))} mm` : ''}, a ${o.bought.part}`, null, { code: 'bought.item', refs: { item: o.id, set: o.bought.set, variant: o.bought.variant, part: o.bought.part, ...(o.bought.length != null ? { length: o.bought.length } : {}) } });
105
105
  }
package/lib/buildpage.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // What a machine's model link adds to the model, all read from the same assembly the checks read: the task (the pen, the
2
- // plane, the margins' figures), a step file, the wires' routes, and the build page (shopping list, plates, wiring sheet,
3
- // assembly steps, machine settings).
2
+ // plane, the margins' figures), a step file, the wires' routes, and the build page (shopping list with the beams' cut
3
+ // list, each beam's cut-and-drill sheet, plates, wiring sheet, assembly steps, machine settings).
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { sheetFrame } from '@rulecad/robots';
@@ -10,6 +10,7 @@ import { host } from './host.mjs';
10
10
  import { accuracyOf, sample, chainOf } from './task.mjs';
11
11
  import { machineOf } from './machine.mjs';
12
12
  import { shoppingList } from './list.mjs';
13
+ import { cutListOf, sheetFile } from './beams.mjs';
13
14
  import { wiresFor, wireRoutesOf } from './assembly.mjs';
14
15
  import { orderOf, isBuilt } from './order.mjs';
15
16
  import { platesOf } from './plates.mjs';
@@ -61,7 +62,9 @@ export async function buildData(s) {
61
62
  const plates = await guard(() => platesOf(s).then(({ bed, gap, plates: p, findings }) => ({ bed, gap, plates: p, findings })));
62
63
  const order = isBuilt(s) ? await guard(() => orderOf(s)) : null;
63
64
  const machine = s.task ? await guard(() => machineOf(s)) : null;
64
- return { build: { list, wires, plates, order, machine } };
65
+ // each mark's cut-and-drill sheet, by its file in the exports (cad beams writes them), and whether it is there yet
66
+ const beams = await guard(() => { const c = cutListOf(s); return c ? { sheets: c.marks.map((m) => ({ mark: m.mark, items: m.items, file: ['exports', s.project, path.basename(sheetFile(s, m.mark))].join('/'), written: fs.existsSync(sheetFile(s, m.mark)) })) } : null; });
67
+ return { build: { list, wires, plates, order, machine, beams } };
65
68
  }
66
69
 
67
70
  // The ledger, in the rules sheet's own rows: each prediction the bench can measure, the measurement once it's in
package/lib/design.mjs CHANGED
@@ -34,6 +34,7 @@ import * as shapes from '@rulecad/shapes';
34
34
  import * as flexures from '@rulecad/flexures';
35
35
  import * as gears from '@rulecad/gears';
36
36
  import * as motors from '@rulecad/motors';
37
+ import { designFrames, framesContext } from './frames.mjs';
37
38
  import { resolve as resolveWith } from '@rulecad/variables';
38
39
  import { engineId, packageVersion, materialise } from './versions.mjs';
39
40
  import { satisfies } from '@rulecad/versions';
@@ -128,12 +129,12 @@ const CACHE = paths.cache('builds'), CACHE_VERSION = 3;
128
129
  const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
129
130
  // What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
130
131
  // boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
131
- const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))), motorsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/motors'))), fixingsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/fixings')));
132
+ const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))), motorsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/motors'))), framesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/frames'))), fixingsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/fixings')));
132
133
  // (every module of a helper package but its tests: they change nothing a design builds)
133
134
  const helperSources = (dir) => fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs').sort().map((f) => source(pathToFileURL(path.join(dir, f)).href)).join('');
134
135
  const feaDir = path.dirname(createRequire(pathToFileURL(path.join(flexuresDir, 'package.json')).href).resolve('@rulecad/fea')); // (flexures' own, wherever npm put it)
135
136
  // (as one digest, so each build's key hashes a line and not a megabyte of source)
136
- const own = crypto.createHash('sha256').update(source(import.meta.url) + source('./fixings.mjs') + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(motorsDir) + helperSources(fixingsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling')).digest('hex'); // every shapes module, not just its entry
137
+ const own = crypto.createHash('sha256').update(source(import.meta.url) + source('./fixings.mjs') + source('./frames.mjs') + helperSources(framesDir) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(motorsDir) + helperSources(fixingsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling')).digest('hex'); // every shapes module, not just its entry
137
138
  // A lamina's slow stages (the physics, the flood's probe) are kept apart from the builds, keyed by the library's code
138
139
  // and their own inputs, so a build that changes only what comes after them (a strap, a check, a rule's words) has them
139
140
  // at once: .cache/stages/. A design in the sandbox can't write them, so the sandbox hands them back and the tool writes them
@@ -220,7 +221,9 @@ export async function build(d, set = {}, { mirror = false } = {}) {
220
221
  // label, a note or the version change nothing it builds, so they aren't in the key
221
222
  const ruleText = [...(object.uses || []).map((u) => JSON.stringify(sets[u] || loadRuleSet(u))), JSON.stringify(refs.extra)];
222
223
  const reads = { values, parts: object.parts, engine: object.engine, mirror: object.mirror };
223
- const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), reads, ruleText, files, Object.values(problems).map((p) => p.hash), set, display])).digest('hex');
224
+ // (v.frames reads the workspace's own profile sets: a build is made from them too, lib/frames.mjs)
225
+ const framed = framesContext(RULE_DIRS[0]);
226
+ const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, framed.hash, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), reads, ruleText, files, Object.values(problems).map((p) => p.hash), set, display])).digest('hex');
224
227
  const hit = path.join(CACHE, `${key}.json`);
225
228
  // (a build that called v.fixings is also made from the workspace's thread sets, its printer and material: it holds
226
229
  // while those stand, and is known by them too, so what is kept by a build's hash, an overlap, follows a changed pilot)
@@ -241,7 +244,7 @@ export async function build(d, set = {}, { mirror = false } = {}) {
241
244
  let parts, board = null, read, mechanism = null, fixings = null;
242
245
  const optional = Object.keys(object.mirror || {}); // inputs only the on-screen copy has: main may ask for them when they aren't there
243
246
  const stages = stageStore();
244
- if (!pcb && sandboxed() && host.name === 'node') ({ parts, read, mechanism, fixings } = await runSandboxed(d, values, object.parts || {}, booleans(object), optional, stages, fixed().context).catch((e) => { throw syntaxAt(e, d); }));
247
+ if (!pcb && sandboxed() && host.name === 'node') ({ parts, read, mechanism, fixings } = await runSandboxed(d, values, object.parts || {}, booleans(object), optional, stages, { frames: framed, fixings: fixed().context }).catch((e) => { throw syntaxAt(e, d); }));
245
248
  else {
246
249
  flexures.laminaCache(stages);
247
250
  const mod = await host.loadModule(d.js).catch((e) => { // a fresh copy after each edit
@@ -252,7 +255,7 @@ export async function build(d, set = {}, { mirror = false } = {}) {
252
255
  });
253
256
  if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
254
257
  const ops = await shapes.ops(booleans(object)), df = (await import('./fixings.mjs')).designFixings({ ...fixed().context, ops }); // (loaded when a design is run here: the sandbox's runner has its own)
255
- const w = watch(values, { shapes, flexures, gears, motors, fixings: df.fixings, ops, ...(pcb ? { pcb } : {}) }, optional);
258
+ const w = watch(values, { shapes, flexures, gears, motors, frames: designFrames(framed), fixings: df.fixings, ops, ...(pcb ? { pcb } : {}) }, optional);
256
259
  read = w.read;
257
260
  let made;
258
261
  try { ({ shapes: made, mechanism } = unpack(await mod.main(w.v))); } catch (e) { throw Object.assign(located(e, d.js, 'design.run'), { line: lineOf(e, pathToFileURL(d.js).href) || undefined }); }
package/lib/frames.mjs ADDED
@@ -0,0 +1,63 @@
1
+ // v.frames: @rulecad/frames as a design gets it, reading the workspace's own profile, slot and material sets (a profile
2
+ // measured with cad measure --profile, with its outline beside it) before the kit's. No files are read by designFrames:
3
+ // framesContext reads them for the build, and the sandbox's runner is handed what it found.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import * as frames from '@rulecad/frames';
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
11
+ let seen = null;
12
+ /**
13
+ * What @rulecad/frames is handed from a workspace: its own rule sets by name, and the measured outlines beside them.
14
+ * @param {string} dir the workspace's rules/ folder
15
+ * @returns {{ sets: Record<string, object>, outlines: Record<string, object>, hash: string }}
16
+ */
17
+ export function framesContext(dir) {
18
+ const out = path.join(dir, 'outlines');
19
+ const stamp = (d) => { try { return fs.readdirSync(d).filter((f) => f.endsWith('.json')).sort().map((f) => `${f}:${fs.statSync(path.join(d, f)).mtimeMs}`).join('|'); } catch { return ''; } };
20
+ const key = `${dir}|${stamp(dir)}|${stamp(out)}`;
21
+ if (seen?.key === key) return seen.context;
22
+ const sets = {}, outlines = {}, text = [];
23
+ for (const [d, into] of [[dir, sets], [out, outlines]]) {
24
+ let files = []; try { files = fs.readdirSync(d).filter((f) => f.endsWith('.json')).sort(); } catch {}
25
+ for (const f of files) {
26
+ try {
27
+ 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
+ } catch {} // (a broken set is cad rules check's to name)
30
+ }
31
+ }
32
+ const context = { sets, outlines, hash: crypto.createHash('sha256').update(text.join('\n')).digest('hex').slice(0, 24) };
33
+ seen = { key, context };
34
+ return context;
35
+ }
36
+
37
+ // profileModel's third argument for a profile by name: the workspace's sets, and its measured outline if it has one
38
+ export const givenFor = (context, profile, given = {}) => {
39
+ const name = typeof profile === 'string' ? (context.sets?.[profile] ? profile : context.sets?.[`profile-${profile}`] ? `profile-${profile}` : null) : null;
40
+ const outline = name && context.outlines?.[name];
41
+ return { ...given, sets: { ...(context.sets || {}), ...(given.sets || {}) }, ...(outline && !given.outline ? { outline } : {}) };
42
+ };
43
+
44
+ /**
45
+ * @rulecad/frames as a design gets it (v.frames): every export, with profileModel, slotModel, beamModel, beam, carrierModel
46
+ * and carrier reading the workspace's own rule sets (a profile measured with cad measure --profile, with its outline, or
47
+ * a slot measured by caliper on the slot coupon) before the kit's.
48
+ * @param {{ sets?: Record<string, object>, outlines?: Record<string, object> }} [context] framesContext()'s
49
+ * @returns {Record<string, any>}
50
+ */
51
+ export function designFrames(context = {}) {
52
+ const bound = { ...frames };
53
+ // (a name is looked up in given.sets before the kit's, with or without its profile- prefix)
54
+ bound.profileModel = (which, change = {}, given = {}) => frames.profileModel(which, change, givenFor(context, which, given));
55
+ bound.slotModel = (which, change = {}, given = {}) => frames.slotModel(which, change, { ...given, sets: { ...(context.sets || {}), ...(given.sets || {}) } });
56
+ bound.beamModel = (profile, o = {}) => frames.beamModel(typeof profile === 'string' ? bound.profileModel(profile, {}, o.given) : profile, { ...o, given: givenFor(context, profile, o.given) });
57
+ bound.beam = (m, o = {}) => frames.beam(m?.kind === 'beam' || m?.kind === 'profile' ? m : typeof m === 'string' ? bound.profileModel(m, {}, o.given) : m, o);
58
+ // (a printed carrier drawn from the workspace's slot, as measured by caliper on the slot coupon)
59
+ bound.carrierModel = (where, o = {}) => frames.carrierModel(where, { ...o, given: givenFor(context, where, o?.given) });
60
+ bound.carrier = (m, o = {}) => frames.carrier(m, m?.kind === 'slot-carrier' ? o : { ...o, given: givenFor(context, m, o?.given) });
61
+ return bound;
62
+ }
63
+
package/lib/list.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  // What a machine takes to build, in numbers: the bought items by rule set with quantities, every screw, nut, washer and
2
2
  // insert (fasten.count: from the fasten relations, a motor's mounting screws, and fits that name a fastener), each by
3
- // thread, length and head with its mass and the packs it is bought in, wires by gauge, and the printed parts with
4
- // their grams and an estimate of the minutes.
3
+ // thread, length and head with its mass and the packs it is bought in, wires by gauge, the printed parts with their
4
+ // grams and an estimate of the minutes, and the beams' cut list (each mark, the bars to buy and the cuts on each:
5
+ // @rulecad/frames' cutList).
5
6
  import { placeItems, jointValues } from '@rulecad/model-link';
6
7
  import { screwModel } from '@rulecad/fixings';
7
8
  import { peekRuleSet as loadRuleSet } from './rules.mjs';
@@ -11,6 +12,8 @@ import { readJson } from './host.mjs';
11
12
  import path from 'node:path';
12
13
  import { volume } from './mesh.mjs';
13
14
  import { wiresFor } from './assembly.mjs';
15
+ import { cutListOf, cutListData } from './beams.mjs';
16
+ import { cutListText } from '@rulecad/frames';
14
17
 
15
18
  const n = (x, d = 1) => Number(x.toFixed(d));
16
19
 
@@ -33,11 +36,13 @@ export function printedParts(s) {
33
36
  return [...by.values()].map((o) => ({ ...o, volume: n(o.volume, 0), grams: n((o.volume / 1000) * mat.density), minutes: n(o.volume / flow / 60, 0) }));
34
37
  }
35
38
 
36
- /** The whole list. @returns {{ bought: object[], fasteners: object[], wires: object[], printed: object[], totals: object }} */
39
+ /** The whole list. @returns {{ bought: object[], fasteners: object[], wires: object[], printed: object[], cut: object | null, totals: object }} */
37
40
  export function shoppingList(s) {
38
41
  const mat = materialOf(s.project), printed = printedParts(s), bought = new Map(), fasteners = new Map();
39
42
  for (const o of s.objects) if (o.bought && !o.unplaced) {
40
- const key = `${o.bought.set}|${o.bought.variant ?? ''}`, line = bought.get(key) ?? { set: o.bought.set, variant: o.bought.variant, part: o.bought.part, qty: 0, grams: o.bought.mass != null ? o.bought.mass * 1000 : null, items: [] };
43
+ // (a beam by its profile and length: one line for each length cut, lib/beams.mjs)
44
+ const len = o.bought.length != null ? Number(o.bought.length.toFixed(2)) : null, key = `${o.bought.set}|${o.bought.variant ?? ''}|${len ?? ''}`;
45
+ const line = bought.get(key) ?? { set: o.bought.set, variant: o.bought.variant, part: o.bought.part, ...(len != null ? { length: len } : {}), qty: 0, grams: o.bought.mass != null ? o.bought.mass * 1000 : null, items: [] };
41
46
  line.qty++; line.items.push(o.id); bought.set(key, line);
42
47
  }
43
48
  // fasten.count: the hardware a fasten placed (a component's too), one part a piece; a motor's mounting screws; and a fit
@@ -55,16 +60,18 @@ export function shoppingList(s) {
55
60
  .sort((a, b) => (a.kind ? 0 : 1) - (b.kind ? 0 : 1) || ['screw', 'nut', 'washer', 'insert'].indexOf(a.kind) - ['screw', 'nut', 'washer', 'insert'].indexOf(b.kind) || String(a.thread).localeCompare(String(b.thread)) || (a.length ?? 0) - (b.length ?? 0) || a.fastener.localeCompare(b.fastener));
56
61
  const rows = s.wires?.length ? wiresFor(s) : [], wires = new Map();
57
62
  for (const w of rows) { const key = w.gauge ?? 'gauge not given', l = wires.get(key) ?? { gauge: w.gauge, conductors: 0, length: 0, runs: [] }; l.length += w.length * w.conductors; l.conductors += w.conductors; l.runs.push(w.id); wires.set(key, l); }
58
- const boughtList = [...bought.values()].map((b) => ({ ...b, grams: b.grams != null ? n(b.grams) : null })).sort((a, b) => a.part.localeCompare(b.part) || a.set.localeCompare(b.set));
63
+ const boughtList = [...bought.values()].map((b) => ({ ...b, grams: b.grams != null ? n(b.grams) : null })).sort((a, b) => a.part.localeCompare(b.part) || a.set.localeCompare(b.set) || (b.length ?? 0) - (a.length ?? 0));
59
64
  const printedGrams = printed.reduce((t, p) => t + p.grams, 0), boughtGrams = boughtList.reduce((t, b) => t + (b.grams ?? 0) * b.qty, 0), unknown = boughtList.filter((b) => b.grams == null).map((b) => b.set);
65
+ const cut = cutListData(cutListOf(s));
60
66
  const fixingsGrams = fixings.reduce((t, f) => t + (f.mass ?? 0), 0);
61
- return { bought: boughtList, fasteners: fixings, wires: [...wires.values()], printed, totals: { printedGrams: n(printedGrams), boughtGrams: n(boughtGrams), fixingsGrams: n(fixingsGrams), machineGrams: n(printedGrams + boughtGrams + fixingsGrams), ...(pack && fixings.some((f) => f.packs) ? { pack } : {}), minutes: n(printed.reduce((t, p) => t + p.minutes, 0), 0), material: mat.name, ...(mat.assumed ? { densityAssumed: true } : {}), ...(unknown.length ? { noMassFor: unknown } : {}) } };
67
+ return { bought: boughtList, fasteners: fixings, wires: [...wires.values()], printed, cut, totals: { printedGrams: n(printedGrams), boughtGrams: n(boughtGrams), fixingsGrams: n(fixingsGrams), machineGrams: n(printedGrams + boughtGrams + fixingsGrams), ...(pack && fixings.some((f) => f.packs) ? { pack } : {}), minutes: n(printed.reduce((t, p) => t + p.minutes, 0), 0), material: mat.name, ...(mat.assumed ? { densityAssumed: true } : {}), ...(unknown.length ? { noMassFor: unknown } : {}) } };
62
68
  }
63
69
 
64
70
  export function listText(ref, l) {
65
71
  const out = [`${ref}: what it takes to build`];
66
72
  const row = (a) => out.push(a.join(' '));
67
- if (l.bought.length) { out.push('', 'Bought'); for (const b of l.bought) row([` ${String(b.qty).padStart(3)} ×`, `${b.set}${b.variant ? ` (${b.variant})` : ''}`, `a ${b.part}`, b.grams != null ? `${b.grams} g each` : 'mass not given', b.items.join(', ')]); }
73
+ if (l.bought.length) { out.push('', 'Bought'); for (const b of l.bought) row([` ${String(b.qty).padStart(3)} ×`, `${b.set}${b.variant ? ` (${b.variant})` : ''}${b.length != null ? ` x ${b.length} mm` : ''}`, `a ${b.part}`, b.grams != null ? `${b.grams} g each` : 'mass not given', b.items.join(', ')]); }
74
+ if (l.cut) { out.push('', `Cut list (kerf ${l.cut.rules.kerf.value} mm, trim ${l.cut.rules.trim.value} mm; a sheet for each mark: cad beams ${ref})`, ...cutListText(l.cut)); }
68
75
  if (l.fasteners.length) {
69
76
  out.push('', 'Fasteners');
70
77
  for (const f of l.fasteners) row([` ${String(f.qty).padStart(3)} ×`, f.fastener, ...(f.mass != null ? [`${f.grams} g each, ${f.mass} g`] : []), ...(f.packs ? [`${f.packs} pack${f.packs > 1 ? 's' : ''} of ${l.totals.pack.size}, ${f.spare} spare`] : []), f.from.join('; ')]);
package/lib/measured.mjs CHANGED
@@ -2,14 +2,16 @@
2
2
  // the estimate was (in the workspace's copy of the rule set), or a measurement of something a check predicts (a figure
3
3
  // no rule holds, like the pen's error at the far corner), runs the assembly's checks either side, says what moved, and
4
4
  // keeps a ledger of predicted against measured beside prints.jsonl. The rules the fixings coupon measures (a pilot or an
5
- // insert hole per thread, the nut fits, the thread gap and flank form) need no --rule: what each is comes from here.
5
+ // insert hole per thread, the nut fits, the thread gap and flank form) and the slot coupon's fits need no --rule: what
6
+ // each is comes from here; a slot's figures go in the workspace's copy of its set, checked as a slot.
6
7
  import fs from 'node:fs';
7
8
  import path from 'node:path';
8
9
  import { setAt } from './jsonedit.mjs';
9
10
  import { CadError } from './errors.mjs';
10
- import { paths, WS, RULE_DIRS } from './workspace.mjs';
11
+ import { paths, WS, RULE_DIRS, printerOf } from './workspace.mjs';
11
12
  import { loadRuleSet } from './rules.mjs';
12
13
  import { buildAssembly, checkAssembly, assemblyPath } from './assembly.mjs';
14
+ import { slotModel } from '@rulecad/frames';
13
15
  import { fixingsContext } from './design.mjs';
14
16
  import { fixingsFor, threads } from '@rulecad/fixings';
15
17
 
@@ -30,6 +32,21 @@ function ruleFile(name) {
30
32
  return { set, rule, data, file: path.join(WS, 'rules', `${set}.json`) };
31
33
  }
32
34
 
35
+ // The slot coupon (examples/bench/projects/benchmarks/MEASURE.md, rows 29 to 33): the two fits it measures, which a
36
+ // printer's set may not hold yet, each with what it is and what the kit drew before (the printer's fit), so the ledger
37
+ // shows predicted against measured; and a slot's own figures, measured by caliper on the person's beam
38
+ const SLOT_COUPON = 'the slot coupon (examples/bench/projects/benchmarks/MEASURE.md)';
39
+ function slotRule(project, set, key, data) {
40
+ if (set === printerOf(project) && ['slot_fit', 'printed_slot_fit'].includes(key)) {
41
+ const fit = data.rules?.fit, was = typeof fit?.value === 'number' ? fit.value : null;
42
+ return { unit: 'mm', predicted: was, was: `${set}.fit, ${fit?.kind ?? 'none'}`, source: SLOT_COUPON,
43
+ rule: key === 'slot_fit' ? `Clearance each side between a printed part and a bought beam's slot it slides in (a tongue in the opening, a carrier in the cavity): the tightest on ${SLOT_COUPON} that slid the beam's length by hand without rattling. Printed carriers are drawn with it (@rulecad/frames carrierModel) before the general fit`
44
+ : `Clearance each side a slot printed in a part is opened by, so a bought slot nut slides in it: the tightest printed slot on ${SLOT_COUPON} a slide-in nut ran the length of by hand without catching. For printed beams and plates with slots`, kind: 'measured' };
45
+ }
46
+ if (data.part === 'slot' && data.rules?.[key]) return { source: `calipers on your own beam (${SLOT_COUPON}, row 32)` };
47
+ return null;
48
+ }
49
+
33
50
  // The printer's rules the fixings read that a printer's set may not hold yet, each measured on the fixings coupon
34
51
  // (examples/bench/projects/benchmarks/MEASURE.md): what it is, its unit, and what the kit drew before it was measured,
35
52
  // so the ledger shows predicted against measured. A pilot or an insert hole is per thread, and may name a plastic
@@ -76,7 +93,7 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
76
93
  if (!project || !name || !fs.existsSync(assemblyPath(ref))) throw new CadError('measured.assembly', `no assembly "${ref}": give <project>/<assembly>, the one whose predictions it moves`);
77
94
  if (!Object.keys(values).length) throw new CadError('measured.usage', 'usage: cad measured <project>/<assembly> <name>=<value> … [--unit mm] [--source "how it was measured"]');
78
95
  const before = await findingsOf(ref), entries = [], predictions = predictionsOf(before);
79
- const writes = []; // (every value is checked before any is written, so a refusal leaves the rule set as it was)
96
+ const writes = [], slots = new Map(); // (every value is checked before any is written, so a refusal leaves the rule sets as they were)
80
97
  for (const [k, value] of Object.entries(values)) {
81
98
  if (!Number.isFinite(value)) throw new CadError('measured.value', `${k}: a measurement is a number (got ${value})`);
82
99
  const named = predictions.filter((x) => x.code === k || x.predict.name === k);
@@ -86,15 +103,18 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
86
103
  continue;
87
104
  }
88
105
  const { set, rule: key, data, file } = ruleFile(k);
89
- const old = data.rules?.[key], known = fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
106
+ const old = data.rules?.[key], known = slotRule(project, set, key, data) ?? fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
90
107
  if (known?.allowed && !known.allowed.includes(value)) throw new CadError('measured.value', `${k} is ${known.allowed.join(' or ')}: the flank forms the coupon prints (got ${value})`);
91
108
  if (!old && !rule && !known) throw new CadError('measured.rule', `${set} has no rule "${key}" (and no check here predicts "${k}"): --rule "what it is" to add it (checks: ${[...new Set(predictions.map((x) => x.code))].join(', ') || 'none'})`);
92
109
  const had = old ?? known, prior = typeof had?.value === 'number' ? had.value : known?.predicted ?? null;
93
110
  if (unit && had?.unit && unit !== had.unit) throw new CadError('measured.unit', `${k} is in ${had.unit}, and this is in ${unit}: give it in ${had.unit}`);
94
111
  const entry = { value, unit: unit ?? had?.unit ?? '', rule: rule ?? had.rule, kind: 'measured', source: source || known?.source || 'measured on the bench', checked: date };
112
+ if (data.part === 'slot') slots.set(set, { data, change: { ...slots.get(set)?.change, [key]: value } });
95
113
  writes.push([file, key, entry]);
96
114
  entries.push({ date, assembly: name, name: k, figure: entry.rule, unit: entry.unit, predicted: prior, was: old ? old.kind : known?.was ?? known?.kind ?? null, measured: value, ratio: prior ? value / prior : null, ...(source ? { source } : {}) });
97
115
  }
116
+ // a slot's figures together still make a slot (an opening narrower than its cavity, lips thinner than it is deep)
117
+ for (const [set, { data, change }] of slots) { try { slotModel(data, change); } catch (e) { throw new CadError('measured.value', `${set}: ${e.message.replace(/^slotModel: /, '')}`); } }
98
118
  for (const [file, key, entry] of writes) fs.writeFileSync(file, setAt(fs.readFileSync(file, 'utf8'), ['rules', key], entry));
99
119
  const after = await findingsOf(ref), was = new Map(before.map((x) => [keyOf(x), x])), moved = [];
100
120
  for (const x of after) {
package/lib/order.mjs CHANGED
@@ -120,7 +120,7 @@ export function assemblyOrder(s) {
120
120
  const worlds = placeItems(s.motion, s.jointValues), marks = s.motion.marks, reaches = (u, v, seen = new Set()) => { if (u === v) return true; if (seen.has(u)) return false; seen.add(u); return [...before.get(u).keys()].some((w) => reaches(w, v, seen)); };
121
121
  const R = 1.5, bad = [];
122
122
  for (const x of s.fits.filter((f) => f.access)) {
123
- const [id, name] = String(x.access).split('.'), m = marks.find((k) => k.id === id && k.name === name);
123
+ const [id, name] = String(x.access).split('.'), m = marks.find((k) => k.id === id && k.name === name) ?? (s.items.find((i) => i.id === id)?.beam ? s.motion.address(String(x.access), 'access') : null); // (a beam's address: x1.top@120)
124
124
  if (!m) throw new Error(`fit ${x.note || `${x.a} / ${x.b}`}: access: no anchor "${x.access}" (give <item>.<anchor>${items.includes(id) ? `; ${id} has ${marks.filter((k) => k.id === id).map((k) => k.name).join(', ') || 'none'}` : ''})`);
125
125
  const W = mul(worlds[m.item], m.frame), O = [W[3], W[7], W[11]], D = [W[2], W[6], W[10]], [u, v] = basis(D), starts = [[0, 0], [R, 0], [-R, 0], [0, R], [0, -R]].map(([a, b]) => O.map((c, k) => c + a * u[k] + b * v[k]));
126
126
  const screwed = [top(x.a), top(x.b)].filter((t) => by.has(t)), later = [...screwed].sort(earlier).at(-1);