@rulecad/cad 0.7.48 → 0.7.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +24 -6
- package/EXAMPLES.md +347 -1
- package/README.md +136 -3
- package/bin/cad.mjs +73 -24
- package/lib/assembly.mjs +96 -34
- package/lib/beams.mjs +147 -0
- package/lib/bought.mjs +1 -1
- package/lib/buildpage.mjs +6 -3
- package/lib/design.mjs +48 -13
- package/lib/edit.mjs +12 -4
- package/lib/fasten.mjs +824 -0
- package/lib/fixings.mjs +42 -0
- package/lib/frames.mjs +63 -0
- package/lib/links.mjs +2 -1
- package/lib/list.mjs +38 -12
- package/lib/measured.mjs +69 -8
- package/lib/motors.mjs +48 -7
- package/lib/order.mjs +20 -6
- package/lib/preview/page.html +4 -2
- package/lib/preview.mjs +3 -2
- package/lib/profilemeasure.mjs +278 -0
- package/lib/sandbox-hooks.mjs +2 -2
- package/lib/sandbox-run.mjs +6 -3
- package/lib/sandbox.mjs +9 -6
- package/lib/schema.mjs +1 -1
- package/lib/sheet.mjs +143 -4
- package/package.json +5 -3
- package/schemas/assembly.schema.json +41 -2
- package/schemas/outline.schema.json +24 -0
package/lib/fixings.mjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// v.fixings: @rulecad/fixings as a design gets it, bound to its project. Every function is fixingsFor's, so it reads
|
|
2
|
+
// the workspace's own thread sets before the kit's, the project's printer, and the design's booleans (v.ops); where a
|
|
3
|
+
// call names no material, the project's is taken for what a thread is in or a head sits on (a hole, engagement,
|
|
4
|
+
// stripping, seating: never a screw's own steel). What each call found is kept, so cad check says what every hole
|
|
5
|
+
// and seat was drawn to. No files are read here: the sandbox's runner uses it as the build does.
|
|
6
|
+
import { fixingsFor } from '@rulecad/fixings';
|
|
7
|
+
|
|
8
|
+
// The functions whose material is the part's (the plastic a pilot is formed in, what a thread or a head bears on)
|
|
9
|
+
const IN_PART = ['hole', 'holeModel', 'engagement', 'stripping', 'seating'];
|
|
10
|
+
const isOptions = (o) => o && typeof o === 'object' && !Array.isArray(o);
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @rulecad/fixings bound to a design's project, with what its calls found.
|
|
14
|
+
* @param {{ sets?: object, printer?: object, material?: string | null, ops?: object }} context sets: the workspace's rule
|
|
15
|
+
* sets by name (threads, materials); printer: the printer's rule set ({ name, rules }); material: the project's; ops: v.ops
|
|
16
|
+
* @returns {{ fixings: Record<string, Function>, found: () => object[], used: () => boolean }} fixings: v.fixings;
|
|
17
|
+
* found: the findings of every model made, each said once (values.count where it came up again); used: whether the design called any of it
|
|
18
|
+
*/
|
|
19
|
+
export function designFixings({ sets, printer, material, ops } = {}) {
|
|
20
|
+
const bound = fixingsFor({ ...(sets && Object.keys(sets).length ? { sets } : {}), ...(printer ? { printer } : {}), ...(ops ? { ops } : {}) });
|
|
21
|
+
const found = new Map(); let calls = 0;
|
|
22
|
+
const keep = (r) => {
|
|
23
|
+
const list = Array.isArray(r) ? r : (r?.model ?? r)?.findings;
|
|
24
|
+
if (Array.isArray(list)) for (const x of list) {
|
|
25
|
+
if (!x || typeof x.text !== 'string' || typeof x.level !== 'string') continue;
|
|
26
|
+
const k = `${x.level}|${x.code}|${x.text}`, had = found.get(k);
|
|
27
|
+
if (had) had.values = { ...had.values, count: (had.values?.count ?? 1) + 1 }; else found.set(k, { ...x });
|
|
28
|
+
}
|
|
29
|
+
return r;
|
|
30
|
+
};
|
|
31
|
+
const fixings = {};
|
|
32
|
+
for (const [k, f] of Object.entries(bound)) {
|
|
33
|
+
if (typeof f !== 'function') { fixings[k] = f; continue; }
|
|
34
|
+
const lead = k === 'lengthFor' ? 2 : 1; // (lengthFor takes the stack first: its options come third)
|
|
35
|
+
fixings[k] = (...a) => {
|
|
36
|
+
calls++;
|
|
37
|
+
if (material && IN_PART.includes(k) && (a[lead] === undefined || isOptions(a[lead])) && a[lead]?.material == null) a[lead] = { material, ...a[lead] };
|
|
38
|
+
return keep(f(...a));
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
return { fixings, found: () => [...found.values()], used: () => calls > 0 };
|
|
42
|
+
}
|
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/links.mjs
CHANGED
|
@@ -103,8 +103,9 @@ export async function assemblyModel(s, { title, versions, filaments: fil = {}, n
|
|
|
103
103
|
alts.forEach((x, i) => (model.motion.swap[x.pose] ||= []).push([x.of, list.length - alts.length + i]));
|
|
104
104
|
}
|
|
105
105
|
// A machine's link carries the rest of the project: its task, a drawing to play, its wires' routes, the build page
|
|
106
|
+
// (an assembly with screws has one too: its shopping list and its steps, each with its screws and key)
|
|
106
107
|
if (s.wires?.length) model.wires = wireRoutesOf(s);
|
|
107
|
-
if (s.task || s.wires?.length || s.objects.some((o) => o.bought || o.motor)) {
|
|
108
|
+
if (s.task || s.wires?.length || s.a.fasten?.length || s.objects.some((o) => o.bought || o.motor)) {
|
|
108
109
|
const findings = s.task ? checkAssembly(s) : [];
|
|
109
110
|
if (s.task && model.motion) { model.task = taskData(s, findings); const carried = stepsData(s, steps); if (carried) model.steps = carried; }
|
|
110
111
|
Object.assign(model, await buildData(s));
|
package/lib/list.mjs
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
|
-
// What a machine takes to build, in numbers: the bought items by rule set with quantities,
|
|
2
|
-
//
|
|
1
|
+
// What a machine takes to build, in numbers: the bought items by rule set with quantities, every screw, nut, washer and
|
|
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, 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).
|
|
6
|
+
import { placeItems, jointValues } from '@rulecad/model-link';
|
|
7
|
+
import { screwModel } from '@rulecad/fixings';
|
|
3
8
|
import { peekRuleSet as loadRuleSet } from './rules.mjs';
|
|
9
|
+
import { motorScrews } from './motors.mjs';
|
|
4
10
|
import { paths } from './workspace.mjs';
|
|
5
11
|
import { readJson } from './host.mjs';
|
|
6
12
|
import path from 'node:path';
|
|
7
13
|
import { volume } from './mesh.mjs';
|
|
8
14
|
import { wiresFor } from './assembly.mjs';
|
|
15
|
+
import { cutListOf, cutListData } from './beams.mjs';
|
|
16
|
+
import { cutListText } from '@rulecad/frames';
|
|
9
17
|
|
|
10
18
|
const n = (x, d = 1) => Number(x.toFixed(d));
|
|
11
19
|
|
|
@@ -28,31 +36,49 @@ export function printedParts(s) {
|
|
|
28
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) }));
|
|
29
37
|
}
|
|
30
38
|
|
|
31
|
-
/** 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 }} */
|
|
32
40
|
export function shoppingList(s) {
|
|
33
41
|
const mat = materialOf(s.project), printed = printedParts(s), bought = new Map(), fasteners = new Map();
|
|
34
42
|
for (const o of s.objects) if (o.bought && !o.unplaced) {
|
|
35
|
-
|
|
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: [] };
|
|
36
46
|
line.qty++; line.items.push(o.id); bought.set(key, line);
|
|
37
47
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
48
|
+
// fasten.count: the hardware a fasten placed (a component's too), one part a piece; a motor's mounting screws; and a fit
|
|
49
|
+
// that names its fastener by hand. Summed by name, which is the thread, length and head, or the nut's kind
|
|
50
|
+
const add = (name, n, from, more = {}) => { const line = fasteners.get(name) ?? { fastener: name, qty: 0, from: [], ...more }; line.qty += n; if (!line.from.includes(from)) line.from.push(from); fasteners.set(name, line); };
|
|
51
|
+
for (const p of s.parts) if (p.hardware) { const h = p.hardware; add(h.name, 1, h.from ?? h.name, { kind: h.kind, thread: h.thread ?? null, length: h.length ?? null, head: h.head ?? null, grams: h.grams ?? null }); }
|
|
52
|
+
for (const m of motorScrews(s, { placeItems, jointValues })) {
|
|
53
|
+
let grams = null; try { grams = screwModel(m.thread, { length: m.length, head: 'cap', anyLength: true }).mass; } catch {}
|
|
54
|
+
add(`${m.thread}x${m.length} cap`, m.count, `${m.item} on ${m.other} (its mount, a fit that fastens)`, { kind: 'screw', thread: m.thread, length: m.length, head: 'cap', grams });
|
|
41
55
|
}
|
|
56
|
+
for (const x of s.fits) if (x.fastener && x.fasten == null) add(x.fastener, x.count != null ? x.num(x.count) : 1, x.note || `${x.a} / ${x.b}`);
|
|
57
|
+
// Rounded up to whole packs (packs.pack), the spares said
|
|
58
|
+
let pack = null; try { const r = loadRuleSet('packs').rules.pack; pack = { size: r.value, rule: 'packs.pack', kind: r.kind }; } catch {}
|
|
59
|
+
const fixings = [...fasteners.values()].map((l) => ({ ...l, ...(l.grams != null ? { grams: n(l.grams, 3), mass: n(l.grams * l.qty, 2) } : {}), ...(l.kind && pack ? { packs: Math.ceil(l.qty / pack.size), buy: Math.ceil(l.qty / pack.size) * pack.size, spare: Math.ceil(l.qty / pack.size) * pack.size - l.qty } : {}) }))
|
|
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));
|
|
42
61
|
const rows = s.wires?.length ? wiresFor(s) : [], wires = new Map();
|
|
43
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); }
|
|
44
|
-
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));
|
|
45
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);
|
|
46
|
-
|
|
65
|
+
const cut = cutListData(cutListOf(s));
|
|
66
|
+
const fixingsGrams = fixings.reduce((t, f) => t + (f.mass ?? 0), 0);
|
|
67
|
+
return { bought: boughtList, fasteners: fixings, wires: [...wires.values()], printed, cut, totals: { printedGrams: n(printedGrams), boughtGrams: n(boughtGrams), fixingsGrams: n(fixingsGrams), machineGrams: n(printedGrams + boughtGrams + fixingsGrams), ...(pack && fixings.some((f) => f.packs) ? { pack } : {}), minutes: n(printed.reduce((t, p) => t + p.minutes, 0), 0), material: mat.name, ...(mat.assumed ? { densityAssumed: true } : {}), ...(unknown.length ? { noMassFor: unknown } : {}) } };
|
|
47
68
|
}
|
|
48
69
|
|
|
49
70
|
export function listText(ref, l) {
|
|
50
71
|
const out = [`${ref}: what it takes to build`];
|
|
51
72
|
const row = (a) => out.push(a.join(' '));
|
|
52
|
-
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(', ')]); }
|
|
53
|
-
if (l.
|
|
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)); }
|
|
75
|
+
if (l.fasteners.length) {
|
|
76
|
+
out.push('', 'Fasteners');
|
|
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('; ')]);
|
|
78
|
+
if (l.totals.pack) out.push(` (packs of ${l.totals.pack.size}: ${l.totals.pack.rule}, ${/^[aeiou]/.test(l.totals.pack.kind) ? 'an' : 'a'} ${l.totals.pack.kind}; masses are estimates from each piece's outline)`);
|
|
79
|
+
}
|
|
54
80
|
if (l.wires.length) { out.push('', 'Wire'); for (const w of l.wires) row([` ${w.length} mm of`, w.gauge ?? 'gauge not given', `in ${w.runs.join(', ')}`]); }
|
|
55
81
|
if (l.printed.length) { out.push('', `Printed (${l.totals.material})`); for (const p of l.printed) row([` ${String(p.grams).padStart(7)} g`, `about ${p.minutes} min`, `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}`]); }
|
|
56
|
-
out.push('', `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`);
|
|
82
|
+
out.push('', `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.fixingsGrams ? `${l.totals.fixingsGrams} g of fixings, ` : ''}${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`);
|
|
57
83
|
return out.join('\n');
|
|
58
84
|
}
|
package/lib/measured.mjs
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
// A bench exists so measurements replace estimates and the predictions move. cad measured writes a measured value where
|
|
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
|
-
// keeps a ledger of predicted against measured beside prints.jsonl.
|
|
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) 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.
|
|
5
7
|
import fs from 'node:fs';
|
|
6
8
|
import path from 'node:path';
|
|
7
9
|
import { setAt } from './jsonedit.mjs';
|
|
8
10
|
import { CadError } from './errors.mjs';
|
|
9
|
-
import { paths, WS } from './workspace.mjs';
|
|
11
|
+
import { paths, WS, RULE_DIRS, printerOf } from './workspace.mjs';
|
|
10
12
|
import { loadRuleSet } from './rules.mjs';
|
|
11
13
|
import { buildAssembly, checkAssembly, assemblyPath } from './assembly.mjs';
|
|
14
|
+
import { slotModel } from '@rulecad/frames';
|
|
15
|
+
import { fixingsContext } from './design.mjs';
|
|
16
|
+
import { fixingsFor, threads } from '@rulecad/fixings';
|
|
12
17
|
|
|
13
18
|
const today = () => new Date().toISOString().slice(0, 10), n = (x) => String(Number(Number(x).toFixed(4)));
|
|
14
19
|
export const ledgerFile = (project) => path.join(paths.project(project), 'ledger.jsonl');
|
|
@@ -27,6 +32,55 @@ function ruleFile(name) {
|
|
|
27
32
|
return { set, rule, data, file: path.join(WS, 'rules', `${set}.json`) };
|
|
28
33
|
}
|
|
29
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
|
+
|
|
50
|
+
// The printer's rules the fixings read that a printer's set may not hold yet, each measured on the fixings coupon
|
|
51
|
+
// (examples/bench/projects/benchmarks/MEASURE.md): what it is, its unit, and what the kit drew before it was measured,
|
|
52
|
+
// so the ledger shows predicted against measured. A pilot or an insert hole is per thread, and may name a plastic
|
|
53
|
+
// (x1c.pilot_m4, x1c.pilot_m4_petg); the rest are one per printer.
|
|
54
|
+
const COUPON = 'the fixings coupon (examples/bench/projects/benchmarks/MEASURE.md)';
|
|
55
|
+
function fixingsRule(project, set, key) {
|
|
56
|
+
if (set !== printerName(project)) return null;
|
|
57
|
+
let fx; const f = () => (fx ||= (() => { const { context } = fixingsContext({ project, dir: paths.project(project) }); return { ...fixingsFor({ sets: context.sets, printer: context.printer }), material: context.material }; })());
|
|
58
|
+
const plastic = (p) => (p ?? f().material ?? 'the project\'s plastic').toUpperCase();
|
|
59
|
+
const hole = key.match(/^(pilot|insert)_(.+)$/);
|
|
60
|
+
if (hole) {
|
|
61
|
+
const bySet = new Map(threads().map((t) => [fixingsFor().fixingModel(t).set, t]));
|
|
62
|
+
const [setName, thread] = [...bySet].filter(([k]) => hole[2] === k || hole[2].startsWith(`${k}_`)).sort((a, b) => b[0].length - a[0].length)[0] ?? [];
|
|
63
|
+
if (!thread) return null;
|
|
64
|
+
const own = hole[2].slice(setName.length + 1) || null;
|
|
65
|
+
if (own && !/^[a-z][a-z0-9]*$/.test(own)) return null;
|
|
66
|
+
const h = f().holeModel(thread, { kind: hole[1], ...(own ? { material: own } : {}) });
|
|
67
|
+
return { unit: 'mm', predicted: h.nominal, was: `${h.basis.rule}, ${h.basis.kind}`,
|
|
68
|
+
rule: hole[1] === 'pilot' ? `Hole to draw for ${/^(M|8|11|18)/.test(thread) ? 'an' : 'a'} ${thread} screw to form its own thread in ${plastic(own)}, standing upright: the one on ${COUPON} the screw went into straight and held in, turned by hand. Drawn as it is: no hole compensation`
|
|
69
|
+
: `Hole to draw for ${/^(M|8|11|18)/.test(thread) ? 'an' : 'a'} ${thread} heat-set insert in ${plastic(own)}: the one on ${COUPON} the insert went into straight and flush, and held when a screw was tightened in it. Drawn as it is: no hole compensation`,
|
|
70
|
+
source: COUPON };
|
|
71
|
+
}
|
|
72
|
+
if (key === 'nut_fit') return { unit: 'mm', predicted: f().nutPocketModel('M3').clearance, was: 'snug, no clearance', source: COUPON,
|
|
73
|
+
rule: `Clearance across the flats of a nut pocket let in from a face, on top of hole_comp: the tightest on ${COUPON} a hex nut dropped into by hand and did not turn in as its screw was tightened. A nut pocket's snug fit` };
|
|
74
|
+
if (key === 'nut_slip') { const t = f().nutTrapModel('M3', { depth: 1 }); return { unit: 'mm', predicted: t.clearance, was: t.rests.find((r) => /slip$/.test(r.name))?.name ?? 'slip', source: COUPON,
|
|
75
|
+
rule: `Clearance across the flats of a nut slot a nut slides into from the side, on top of hole_comp: the tightest on ${COUPON} a hex nut slid into by hand, stayed in turned over, and did not turn as its screw was tightened. A nut slot's slip fit` }; }
|
|
76
|
+
if (key === 'thread_flank') { const t = f().threadModel('M8', { length: f().holeModel('M8', { kind: 'thread' }).depth, internal: true }); return { unit: '°', predicted: t.overhang.drawn, was: 'flanks: printed, the default', source: COUPON, allowed: [t.overhang.drawn, t.overhang.standard],
|
|
77
|
+
rule: `The down-facing flank of a printed thread standing upright, as an overhang from upright: ${t.overhang.drawn} is the form laid back to the printer's overhang (flanks: 'printed', the kit's default), ${t.overhang.standard} the standard's own form (flanks: 'standard'). The one on ${COUPON} that held, turned smoothly and printed clean. A record for choosing the default: designs still draw flanks: 'printed' unless they say otherwise` }; }
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
const printerName = (project) => { try { return fixingsContext({ project, dir: paths.project(project) }).context.printer?.name ?? 'x1c'; } catch { return 'x1c'; } };
|
|
81
|
+
// A rule the workspace's copy lacks and the kit's own set of that name holds (a set copied before the rule was added)
|
|
82
|
+
function kitRule(set, key) { try { return JSON.parse(fs.readFileSync(path.join(RULE_DIRS.at(-1), `${set}.json`), 'utf8')).rules?.[key] ?? null; } catch { return null; } }
|
|
83
|
+
|
|
30
84
|
/**
|
|
31
85
|
* Write measurements back.
|
|
32
86
|
* @param {string} ref project/assembly
|
|
@@ -39,6 +93,7 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
|
|
|
39
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`);
|
|
40
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"]');
|
|
41
95
|
const before = await findingsOf(ref), entries = [], predictions = predictionsOf(before);
|
|
96
|
+
const writes = [], slots = new Map(); // (every value is checked before any is written, so a refusal leaves the rule sets as they were)
|
|
42
97
|
for (const [k, value] of Object.entries(values)) {
|
|
43
98
|
if (!Number.isFinite(value)) throw new CadError('measured.value', `${k}: a measurement is a number (got ${value})`);
|
|
44
99
|
const named = predictions.filter((x) => x.code === k || x.predict.name === k);
|
|
@@ -48,13 +103,19 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
|
|
|
48
103
|
continue;
|
|
49
104
|
}
|
|
50
105
|
const { set, rule: key, data, file } = ruleFile(k);
|
|
51
|
-
const old = data.rules?.[key];
|
|
52
|
-
if (
|
|
53
|
-
if (
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
106
|
+
const old = data.rules?.[key], known = slotRule(project, set, key, data) ?? fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
|
|
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})`);
|
|
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'})`);
|
|
109
|
+
const had = old ?? known, prior = typeof had?.value === 'number' ? had.value : known?.predicted ?? null;
|
|
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}`);
|
|
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 } });
|
|
113
|
+
writes.push([file, key, entry]);
|
|
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 } : {}) });
|
|
57
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: /, '')}`); } }
|
|
118
|
+
for (const [file, key, entry] of writes) fs.writeFileSync(file, setAt(fs.readFileSync(file, 'utf8'), ['rules', key], entry));
|
|
58
119
|
const after = await findingsOf(ref), was = new Map(before.map((x) => [keyOf(x), x])), moved = [];
|
|
59
120
|
for (const x of after) {
|
|
60
121
|
const y = was.get(keyOf(x));
|
package/lib/motors.mjs
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { createRequire } from 'node:module';
|
|
6
6
|
import { motorModel, motorParts, mountModel, performance } from '@rulecad/motors';
|
|
7
7
|
import { stageEfficiency } from '@rulecad/gears';
|
|
8
|
+
import { screwGroup } from '@rulecad/fixings';
|
|
8
9
|
import { named } from './parts.mjs';
|
|
9
10
|
import { referenceBuilt } from './bought.mjs';
|
|
10
11
|
import crypto from 'node:crypto';
|
|
@@ -145,6 +146,13 @@ function worstLoad(motion, loads, j, drive, { placeItems, jointValues, mul }) {
|
|
|
145
146
|
// What a stepper gives at the current it's set to: torque goes with the current, up to its rating
|
|
146
147
|
export const atCurrent = (m, spec, torque) => (m.type === 'stepper' && spec.current != null && m.figures.rated_current?.value ? torque * Math.min(1, spec.current / m.figures.rated_current.value) : torque);
|
|
147
148
|
|
|
149
|
+
/**
|
|
150
|
+
* The torque a motor puts on its own screws, as a reaction about its shaft: what it gives at its working speed (the
|
|
151
|
+
* assembly's, else workingSpeed), at the current it's set to. motor.torque, motor.mount and fasten.load all read this one.
|
|
152
|
+
* @param {{ model: object, spec: object }} d a drive (an assembly's motor item) @returns {number} N m
|
|
153
|
+
*/
|
|
154
|
+
export const mountTorque = (d) => atCurrent(d.model, d.spec, performance(d.model, { speed: workingSpeed(d.model, d.spec) }).motor.torque);
|
|
155
|
+
|
|
148
156
|
// A motor's speed if the assembly doesn't say: its corner speed, its rated speed, or half its free speed
|
|
149
157
|
export function workingSpeed(model, spec) {
|
|
150
158
|
if (spec.speed != null) return spec.speed;
|
|
@@ -157,7 +165,7 @@ const material = (name) => { const n = String(name || 'pla').toLowerCase().split
|
|
|
157
165
|
// The findings: f(level, text, card, extra), as the assembly's check makes them
|
|
158
166
|
export function motorChecks(s, f, helpers, materialName) {
|
|
159
167
|
const motion = s.motion, drives = motion?.drives || [], loads = motion?.loads || [], { placeItems, jointValues, mul } = helpers;
|
|
160
|
-
if (!drives.length) { if (loads.length) f('warn', `there are loads, but no motor: nothing has been checked against them (add a "motor" item that "drives" a joint)`, null, { code: 'motor.loads' }); return; }
|
|
168
|
+
if (!drives.length) { if (loads.length && !s.a.fasten?.length) f('warn', `there are loads, but no motor: nothing has been checked against them (add a "motor" item that "drives" a joint)`, null, { code: 'motor.loads' }); return; }
|
|
161
169
|
const worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined));
|
|
162
170
|
for (const d of drives) {
|
|
163
171
|
const m = d.model, grams = n3(m.mass * 1000, 1), K = d.spec.margin != null ? d.spec.margin : 2, W = worlds[d.item];
|
|
@@ -191,7 +199,7 @@ export function motorChecks(s, f, helpers, materialName) {
|
|
|
191
199
|
back += (atLead / reduction) * ηback; backOn += atLead / reduction;
|
|
192
200
|
lines.push({ x, t, load, unit, reduction, atLead, η });
|
|
193
201
|
}
|
|
194
|
-
const speedOut = motorSpeed / loaded[0].t.ratio, rated = performance(m, { speed: motorSpeed }), avail =
|
|
202
|
+
const speedOut = motorSpeed / loaded[0].t.ratio, rated = performance(m, { speed: motorSpeed }), avail = mountTorque(d), margin = need ? avail / need : Infinity;
|
|
195
203
|
const main = lines[0], what = main.unit === 'N m' ? `${n3(main.load.torque)} N m` : `${n3(main.load.torque, 2)} N`, gives = main.unit === 'N m' ? `${n3(avail * main.reduction * main.η)} N m` : `${n3((avail * main.reduction * main.η * Math.PI * 1000) / (main.t.slide * 180), 1)} N`;
|
|
196
204
|
const trust = rated.rests.filter((k) => k !== 'spec' && k !== 'measured'), caveat = trust.length ? ` (rests on ${trust.join(' and ')} figures: measure it)` : '';
|
|
197
205
|
const level = margin < 1 ? 'fail' : margin < K ? 'warn' : 'pass', fix = margin < 1 && main.t.slide == null ? ` A ratio of ${n3((main.reduction * K) / margin, 1)}:1 would give it ${K} times` : '';
|
|
@@ -224,17 +232,50 @@ export function motorChecks(s, f, helpers, materialName) {
|
|
|
224
232
|
|
|
225
233
|
// The part a motor is fastened to, under the motor's full torque as a reaction at its screws: how thick it is at the
|
|
226
234
|
// holes (read from the part as drawn), the screws' bearing on the plastic, and how far the whole part bends (mountBends).
|
|
227
|
-
|
|
235
|
+
// The part a motor is fastened to, read at its screw holes in the motor's frame: the thinnest wall at a hole (t) and the
|
|
236
|
+
// plate round them (plate), or null where no fit that fastens names the motor
|
|
237
|
+
function mountPlate(s, d, W) {
|
|
228
238
|
const m = d.model, top = (n) => String(n).split(/[.@]/)[0], fit = s.fits.find((x) => x.fastens && [top(x.a), top(x.b)].includes(d.id));
|
|
229
|
-
if (!fit || !m.mount.holes.length) return;
|
|
230
|
-
const other = top(fit.a) === d.id ? top(fit.b) : top(fit.a), parts = s.parts.filter((p) => p.item === other || p.leaf === other);
|
|
231
|
-
if (!parts.length) return;
|
|
239
|
+
if (!fit || !m.mount.holes.length) return null;
|
|
240
|
+
const other = top(fit.a) === d.id ? top(fit.b) : top(fit.a), parts = s.parts.filter((p) => !p.hardware && (p.item === other || p.leaf === other));
|
|
241
|
+
if (!parts.length) return null;
|
|
232
242
|
const inv = (p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
|
|
233
243
|
const pts = parts.flatMap((p) => p.triangles.flat().map(inv)), side = m.mount.side, nominal = mountModel(m, { plate: 10 }), hd = nominal.holes[0].diameter;
|
|
234
244
|
let t = Infinity, plate = 0; // the shortest wall a hole has, and the plate round it (more, if the screw's head is sunk)
|
|
235
245
|
for (const [hx, hy] of m.mount.holes) for (const p of pts) { const r = Math.hypot(p[0] - hx, p[1] - hy), z = p[2] * side; if (r < hd / 2 + 2 && z > 0.5) { t = Math.min(t, z); plate = Math.max(plate, z); } }
|
|
246
|
+
return { fit, other, parts, inv, t, plate, hd };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* The screws that hold each motor to the part it is fastened to by a fit with "fastens" (a motor named in a "fasten"
|
|
251
|
+
* has its screws counted there): as many as its mounting holes, the length mountModel works out for the plate as drawn,
|
|
252
|
+
* taken to a length sold (the longest that does not pass it into the motor's own thread; through plain holes, the shortest that reaches).
|
|
253
|
+
* @param {object} s a built assembly @param {{ placeItems: Function, jointValues: Function }} helpers
|
|
254
|
+
* @returns {{ item: string, other: string, thread: string, length: number, wanted: number, count: number }[]}
|
|
255
|
+
*/
|
|
256
|
+
export function motorScrews(s, { placeItems, jointValues }) {
|
|
257
|
+
const drives = s.motion?.drives || [], top = (n) => String(n).split(/[.@]/)[0];
|
|
258
|
+
if (!drives.length) return [];
|
|
259
|
+
const named = new Set((s.a.fasten || []).flatMap((x) => [...(x.through || []), x.into].map(top)));
|
|
260
|
+
const worlds = placeItems(s.motion, s.jointValues ?? jointValues(s.motion, s.motion.pose ?? undefined)), out = [];
|
|
261
|
+
for (const d of drives) {
|
|
262
|
+
if (named.has(d.id)) continue;
|
|
263
|
+
const p = mountPlate(s, d, worlds[d.item]); if (!p || p.t === Infinity) continue;
|
|
264
|
+
const here = mountModel(d.model, { plate: +p.plate.toFixed(2), ...(d.spec.screw ? { screw: d.spec.screw } : {}) }), thread = here.screw?.thread, L = here.screwLength;
|
|
265
|
+
if (!thread || !(L > 0)) continue;
|
|
266
|
+
let sold = null; try { sold = peekRuleSet(thread.toLowerCase().replace('.', '_')).rules.lengths?.value ?? null; } catch {}
|
|
267
|
+
const length = !sold ? L : d.model.mount.thread ? [...sold].reverse().find((l) => l <= L) ?? sold[0] : sold.find((l) => l >= L) ?? sold.at(-1);
|
|
268
|
+
out.push({ item: d.id, other: p.other, thread, length, wanted: L, count: d.model.mount.holes.length });
|
|
269
|
+
}
|
|
270
|
+
return out;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function mountCheck(s, d, f, W, avail, materialName, frame) {
|
|
274
|
+
const m = d.model, at = mountPlate(s, d, W);
|
|
275
|
+
if (!at) return;
|
|
276
|
+
const { other, parts, inv, t, plate, hd } = at;
|
|
236
277
|
if (t === Infinity) return f('warn', `${d.id}: couldn't find the plate at its screw holes in ${other}`, `${d.id}: mount not found`, { code: 'motor.mount' });
|
|
237
|
-
const here = mountModel(m, { plate: +plate.toFixed(2), ...(d.spec.screw ? { screw: d.spec.screw } : {}) }), mat = material(materialName) || material('pla'),
|
|
278
|
+
const here = mountModel(m, { plate: +plate.toFixed(2), ...(d.spec.screw ? { screw: d.spec.screw } : {}) }), mat = material(materialName) || material('pla'), each = Math.max(...screwGroup(m.mount.holes, { moment: [0, 0, avail] }).screws.map((x) => x.shear)), bearing = each / (hd * t), margin = mat.strength / bearing;
|
|
238
279
|
for (const x of here.findings) f(x.level, `${d.id} on ${other}: ${x.text}`, x.level === 'pass' ? null : `${d.id}: ${x.code.split('.')[1]}`, { code: 'motor.mount' });
|
|
239
280
|
f(margin < 2 ? 'fail' : 'pass', `${d.id} on ${other}: ${n3(plate, 2)} mm of plate at the screws, each taking ${n3(each, 1)} N against the torque (bearing ${n3(bearing, 1)} MPa, ${n3(margin, 0)} times under ${mat.name.toUpperCase()}'s ${mat.strength} MPa)`, margin < 2 ? `${d.id}: screws pull through` : null, { code: 'motor.mount', values: { plate, bearing, margin } });
|
|
240
281
|
mountBends(s, d, f, W, avail, mat, { other, parts, inv, plate, hd, ...frame });
|
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);
|
|
@@ -130,10 +130,21 @@ export function assemblyOrder(s) {
|
|
|
130
130
|
else if (later) add(later, q.id, `${q.id} covers the screw of ${x.note || later}`);
|
|
131
131
|
}
|
|
132
132
|
}
|
|
133
|
+
// A fasten's screws (lib/fasten.mjs): what stands over a head goes on after the parts the screw joins. A part that
|
|
134
|
+
// must be there first (it comes before them, it is one of them, or it is no step at all) closes the way, unless a
|
|
135
|
+
// ball-end key reaches the head tilted
|
|
136
|
+
for (const rel of s.fastened?.relations ?? []) for (const sc of rel.screws) {
|
|
137
|
+
const acc = sc.access; if (!acc?.blockers?.length) continue;
|
|
138
|
+
const screwed = [...rel.through, rel.into].map(top).filter((t) => by.has(t)), later = [...screwed].sort(earlier).at(-1), walls = [...new Set(acc.blockers.map((b) => b.item))];
|
|
139
|
+
const first = walls.filter((q) => !by.has(q) || screwed.includes(q) || (later && reaches(q, later)));
|
|
140
|
+
if (first.length) { if (acc.tilt == null) bad.push({ fit: { note: rel.label }, wall: first[0], at: acc.top, later, fasten: rel.index, screw: sc.index, member: screwed.includes(first[0]), fixed: !by.has(first[0]) }); continue; }
|
|
141
|
+
for (const q of walls) add(later, q, `${q} covers the screws of ${rel.label}`);
|
|
142
|
+
}
|
|
133
143
|
const box = (g) => { const p = g.tris.flat(); return [0, 1, 2].map((k) => { const v = p.map((x) => x[k]); return (Math.min(...v) + Math.max(...v)) / 2; }); };
|
|
134
144
|
if (bad.length) {
|
|
135
|
-
const b = bad[0], label = b.fit.note || `${b.fit.a} to ${b.fit.b}`;
|
|
136
|
-
return { steps: [], stuck: { item: b.later, screw: label, wall: b.wall, at: b.at,
|
|
145
|
+
const b = bad[0], label = b.fit.note || `${b.fit.a} to ${b.fit.b}`, why = b.member ? 'it is one of the parts the screw joins' : b.fixed ? 'it is in place before anything is fitted' : `goes on first (${[...before.get(b.wall)].slice(0, 1).map(([, w]) => w)})`;
|
|
146
|
+
return { steps: [], stuck: { item: b.later, screw: label, wall: b.wall, at: b.at, ...(b.fasten != null ? { fasten: b.fasten, screws: bad.filter((x) => x.fasten === b.fasten).map((x) => x.screw) } : {}),
|
|
147
|
+
text: `the screw of "${label}" can't be reached in any order: ${b.wall} stands over it${b.member || b.fixed ? `, and ${why}` : ` and ${why}`}` } };
|
|
137
148
|
}
|
|
138
149
|
let span = 1;
|
|
139
150
|
for (const g of all) for (const t of g.tris) for (const p of t) for (const c of p) span = Math.max(span, Math.abs(c) * 2);
|
|
@@ -190,7 +201,7 @@ export function assemblyOrder(s) {
|
|
|
190
201
|
for (const [i, x] of seq.entries()) {
|
|
191
202
|
if (x.group) { steps.push({ items: x.group.map((g) => g.id), object: null, dir: round(x.d), fasteners: [], together: true }); continue; }
|
|
192
203
|
const { p, d } = x, list = [...new Set(s.fits.filter((f) => [...names(f.a), ...names(f.b)].includes(p.id) && (f.fastens || f.seat != null || f.fastener) && [...names(f.a), ...names(f.b)].every((n) => (at.get(n) ?? 0) <= i)))];
|
|
193
|
-
steps.push({ items: [p.id], object: p.object, dir: round(d), fasteners: list.map((f) => ({ fit: f.note || f.label || `${f.a} to ${f.b}`, ...(f.fastener ? { fastener: f.fastener } : {}), ...(f.count != null ? { count: f.num(f.count) } : {}) })) });
|
|
204
|
+
steps.push({ items: [p.id], object: p.object, dir: round(d), fasteners: list.map((f) => ({ fit: f.note || f.label || `${f.a} to ${f.b}`, ...(f.fastener ? { fastener: f.fastener } : {}), ...(f.count != null ? { count: f.num(f.count) } : {}), ...(f.key ? { key: f.key } : {}), ...(f.tighten ? { tighten: f.tighten } : {}) })) });
|
|
194
205
|
}
|
|
195
206
|
// Copies of one thing fitted the same way, one after another, are one step
|
|
196
207
|
const merged = [];
|
|
@@ -199,13 +210,16 @@ export function assemblyOrder(s) {
|
|
|
199
210
|
if (last && st.object && !st.together && last.object === st.object && last.dir.join() === st.dir.join() && JSON.stringify(last.fasteners.map((f) => f.fit)) === JSON.stringify(st.fasteners.map((f) => f.fit))) last.items.push(...st.items);
|
|
200
211
|
else merged.push({ items: [...st.items], object: st.object, dir: st.dir, fasteners: st.fasteners, ...(st.together ? { together: true } : {}) });
|
|
201
212
|
}
|
|
202
|
-
merged.forEach((st, i) => { st.n = i + 1; st.text = `${st.items.join(', ')}${st.object && !st.items.includes(st.object) ? ` (${st.object})` : ''}${st.together ? ' go on as one' : i ? ` goes on${st.items.length > 1 ? ', one by one' : ''}` : ' first'}${st.fasteners.length ? `: ${st.fasteners.map(
|
|
213
|
+
merged.forEach((st, i) => { st.n = i + 1; st.text = `${st.items.join(', ')}${st.object && !st.items.includes(st.object) ? ` (${st.object})` : ''}${st.together ? ' go on as one' : i ? ` goes on${st.items.length > 1 ? ', one by one' : ''}` : ' first'}${st.fasteners.length ? `: ${st.fasteners.map(fastenerText).join('; ')}` : ''}`; });
|
|
203
214
|
return { steps: merged, stuck: null };
|
|
204
215
|
}
|
|
205
216
|
|
|
217
|
+
/** One fastening of a step as the order and the build page say it: the fit, its screws by count and name, the key and how tight. */
|
|
218
|
+
export const fastenerText = (f) => `${f.fit}${f.fastener ? ` (${f.count != null ? `${f.count} × ` : ''}${f.fastener})` : ''}${f.key ? ` with ${/^[aeiou8]/i.test(f.key) ? 'an' : 'a'} ${f.key}` : ''}${f.tighten ? `, ${f.tighten.given ? `to ${f.tighten.torque} N m` : f.tighten.load ? `to ${f.tighten.torque} N m (what the joint's load leaves the thread)` : `to ${f.tighten.torque} N m at most (what the seat takes)`}` : ''}`;
|
|
219
|
+
|
|
206
220
|
// Cached by what the parts are and where they are, with everything else that changes the answer
|
|
207
221
|
function orderFile(s) {
|
|
208
|
-
const key = crypto.createHash('sha256').update(JSON.stringify([
|
|
222
|
+
const key = crypto.createHash('sha256').update(JSON.stringify([5, s.parts.map((p) => [p.item, p.hash ?? p.shape, Array.from(p.m ?? []).map((x) => +x.toFixed(4))]), s.fits.map(({ num, ...x }) => x), s.motion.joints.map((j) => [j.id, j.child, j.parent])])).digest('hex');
|
|
209
223
|
return paths.cache('order', `${key}.json`);
|
|
210
224
|
}
|
|
211
225
|
export function orderOf(s) {
|
package/lib/preview/page.html
CHANGED
|
@@ -27,8 +27,10 @@ if (data.explode) {
|
|
|
27
27
|
const gap = (all.max.y - all.min.y) * 0.8;
|
|
28
28
|
let drop = 0;
|
|
29
29
|
data.parts.forEach((p, i) => { if (p.role === 'support') { drop += gap; geos[i].translate(0, -drop, 0); geos[i].computeBoundingBox(); } });
|
|
30
|
-
const items = [...new Set(data.parts.map((p) => p.item).filter(Boolean))]; // assemblies: each item above the last
|
|
31
|
-
data.parts.forEach((p, i) => { const k = items.indexOf(p.item); if (k > 0) { geos[i].translate(0, k * gap, 0); geos[i].computeBoundingBox(); } });
|
|
30
|
+
const items = [...new Set(data.parts.filter((p) => !p.lift).map((p) => p.item).filter(Boolean))]; // assemblies: each item above the last
|
|
31
|
+
data.parts.forEach((p, i) => { const k = items.indexOf(p.lift ? p.with : p.item); if (k > 0) { geos[i].translate(0, k * gap, 0); geos[i].computeBoundingBox(); } });
|
|
32
|
+
// hardware (a screw, a nut, a washer, an insert) goes with the part it sits in, then out along its own axis (z up here is y)
|
|
33
|
+
data.parts.forEach((p, i) => { if (p.lift) { const d = gap * 0.45; geos[i].translate(p.lift[0] * d, p.lift[2] * d, -p.lift[1] * d); geos[i].computeBoundingBox(); } });
|
|
32
34
|
}
|
|
33
35
|
const box = new THREE.Box3(); geos.forEach((g) => box.union(g.boundingBox));
|
|
34
36
|
const center = box.getCenter(new THREE.Vector3()), radius = box.getSize(new THREE.Vector3()).length() / 2;
|
package/lib/preview.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// preview(parts, { title, meta, out, explode }) -> out: a 1800 × 1200 PNG of six views (front, side, 3/4, top, bottom, 3/4 below),
|
|
2
2
|
// parts: [{ name, role, label, item, triangles }]; supports and references are drawn faint (lines only); explode drops
|
|
3
|
-
// supports below and, in an assembly, lifts each kind of object above the one before (plate, switches, keycaps)
|
|
3
|
+
// supports below and, in an assembly, lifts each kind of object above the one before (plate, switches, keycaps); a part
|
|
4
|
+
// with `lift` (a screw, a nut: lib/fasten.mjs) goes with the part it sits in (`with`) and then out along its own axis.
|
|
4
5
|
// rendered by headless Chrome from lib/preview/page.html, served on this Mac only for the few seconds it takes.
|
|
5
6
|
import fs from 'node:fs';
|
|
6
7
|
import os from 'node:os';
|
|
@@ -20,7 +21,7 @@ const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); //
|
|
|
20
21
|
|
|
21
22
|
export async function preview(parts, { title = '', meta = '', out, explode = false, marks = null }) {
|
|
22
23
|
const flat = (tris) => { const positions = []; for (const t of tris) for (let i = 1; i < t.length - 1; i++) positions.push(...t[0], ...t[i], ...t[i + 1]); return positions; };
|
|
23
|
-
const data = JSON.stringify({ title, meta, explode, marks, parts: parts.map((p) => ({ name: p.name, role: p.role, label: p.label, item: p.object || p.item, positions: flat(p.triangles) })) });
|
|
24
|
+
const data = JSON.stringify({ title, meta, explode, marks, parts: parts.map((p) => ({ name: p.name, role: p.role, label: p.label, item: p.object || p.item, ...(p.lift ? { lift: p.lift, with: p.with } : {}), positions: flat(p.triangles) })) });
|
|
24
25
|
const server = http.createServer((req, res) => {
|
|
25
26
|
const u = new URL(req.url, 'http://x').pathname;
|
|
26
27
|
const send = (type, body) => { res.writeHead(200, { 'Content-Type': type }); res.end(body); };
|