@rulecad/cad 0.7.56 → 0.7.58
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +103 -1
- package/CHANGELOG.md +241 -0
- package/EXAMPLES.md +782 -2
- package/README.md +719 -8
- package/TUTORIAL.md +2 -0
- package/bin/cad.mjs +135 -29
- package/lib/assembly.mjs +83 -17
- package/lib/beams.mjs +46 -13
- package/lib/bought.mjs +41 -5
- package/lib/buildpage.mjs +8 -3
- package/lib/edit.mjs +10 -4
- package/lib/fasten.mjs +279 -47
- package/lib/fittings.mjs +313 -0
- package/lib/framebuild.mjs +463 -0
- package/lib/framecheck.mjs +831 -0
- package/lib/framegen.mjs +111 -0
- package/lib/frameheat.mjs +94 -0
- package/lib/frameprint.mjs +277 -0
- package/lib/frames.mjs +5 -3
- package/lib/framesize.mjs +261 -0
- package/lib/guides.mjs +354 -0
- package/lib/jigs.mjs +240 -0
- package/lib/joins.mjs +263 -0
- package/lib/kit.mjs +190 -0
- package/lib/links.mjs +11 -3
- package/lib/list.mjs +28 -8
- package/lib/loads.mjs +12 -4
- package/lib/measured.mjs +86 -17
- package/lib/motors.mjs +7 -3
- package/lib/optimise.mjs +18 -3
- package/lib/order.mjs +28 -14
- package/lib/panels.mjs +220 -0
- package/lib/plates.mjs +37 -16
- package/lib/services.mjs +132 -0
- package/lib/sheet.mjs +15 -1
- package/lib/slotnuts.mjs +159 -0
- package/lib/task.mjs +43 -3
- package/lib/wires.mjs +2 -1
- package/package.json +6 -6
- package/schemas/assembly.schema.json +34 -9
package/TUTORIAL.md
CHANGED
|
@@ -234,3 +234,5 @@ commands to run, tested the same way as this page. Each is also a section of [th
|
|
|
234
234
|
- **Optimised parts**: the stiffest layout for a load, and an analysis of what you drew.
|
|
235
235
|
- **Boards**: circuit boards from the same rules as the case around them.
|
|
236
236
|
- **Mechanisms printed flat**: springs, catches and triggers in one print, checked through their whole cycle.
|
|
237
|
+
- **Frames**: beams of an aluminium profile placed by their ends, joined, with feet and a motor-driven axis, cut,
|
|
238
|
+
drilled and printed on one plate (chapter 16).
|
package/bin/cad.mjs
CHANGED
|
@@ -60,6 +60,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
60
60
|
[--washer] [--length 12] [--torque 0.5] [--note …]
|
|
61
61
|
cad add fasten <project>/<assembly> --from-fits a fasten in place of a holes fit and a fit that fastens the same parts
|
|
62
62
|
(the screw read from them, or --screw "M2 cap")
|
|
63
|
+
cad add join <project>/<assembly> --kind blind --a y1.a --b x1.back@120 two beams joined: the end of a against b's face
|
|
64
|
+
[--screw "M5 button"] [--fitting printed|<bought set>] [--note …]
|
|
63
65
|
cad why <project>/<object>.<name> what a value reads, down to the rules and their sources [--json] [--depth N]
|
|
64
66
|
cad check <project>/<object> raw numbers in the design, then printability (exit 1 on a failure) [--json: findings as data]
|
|
65
67
|
cad preview <project>/<object> six views as a PNG in .preview/ (prints the path); an assembly with a motor also gets
|
|
@@ -93,10 +95,17 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
93
95
|
cad machine <project>/<assembly> the machine as plain data: axes, steps, limits, homing, the task, in exports/
|
|
94
96
|
cad plot <project>/<assembly> <drawing.svg> plans a drawing on the machine: a step file in exports/, an animation in
|
|
95
97
|
.preview/, and any stroke refused [--calibrate: the calibration drawing] [--tol 0.1] [--json]
|
|
96
|
-
cad order <project>/<assembly> the order it goes together in, each step with its fasteners [--preview: an exploded picture of each step in .preview/]
|
|
97
|
-
cad plates <project>/<assembly> every printed part on beds, by filament, spaced by the first-layer rule: written as plate assemblies and checked; a changed part re-packs only its plate [--gap mm] [--json]
|
|
98
|
+
cad order <project>/<assembly> the order it goes together in, each step with its fasteners; a frame from bars to square: cut, drill, sides built flat, nuts to load, joins with their torque, diagonals [--preview: an exploded picture of each step in .preview/]
|
|
99
|
+
cad plates <project>/<assembly> every printed part on beds, by material and filament, spaced by the first-layer rule: written as plate assemblies and checked; a changed part re-packs only its plate; a frame's jigs on plates of their own [--gap mm] [--no-jigs] [--json]
|
|
100
|
+
cad kit <project>/<assembly> the folder to build it from without the model, in exports/: README.md (checks, what to buy and print, cut list, drilling, the build step by step), buy.csv, the plates' 3MFs, the jigs, each beam's sheet [--pictures] [--json]
|
|
98
101
|
cad list <project>/<assembly> what it takes to build: bought parts by set, the beams' cut list and bars to buy, every screw, nut and insert in packs, wire, printed parts in grams
|
|
102
|
+
cad frame <project>/<assembly> a generated frame ("frame": { "kind": "box", "inside": [..] }): its size, its beams by length, its joins and ends
|
|
103
|
+
--expand: written into the assembly as its beams, joins and end fittings, to edit by hand [--json]
|
|
104
|
+
--size: any frame's beams, by group, each given the lightest profile from frame.size.profiles that meets
|
|
105
|
+
its limits, as a table naming the limit that set each; --write writes the profiles in [--json]
|
|
99
106
|
cad beams <project>/<assembly> a cut-and-drill sheet for each mark of beam (beams that are the same share one), to scale, written to exports/ [--json]
|
|
107
|
+
--jigs: the jigs its beams take, as a plate in exports/ (a drill guide per distinct hole across a beam, a tap
|
|
108
|
+
guide per tapped end, a cut-length stop per length, a squaring corner per square join), each marked with its beam [--preview]
|
|
100
109
|
cad wires <project>/<assembly> the wiring sheet: each wire's length, gauge and ends, written to exports/ [--out wiring.md]
|
|
101
110
|
cad measured <project>/<assembly> <name>=<value> … a measurement, where the estimate was: a rule (x1c.press=0.08) or a
|
|
102
111
|
check's prediction (task.accuracy=0.8): says what moved, and keeps a ledger of predicted
|
|
@@ -135,22 +144,23 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
135
144
|
|
|
136
145
|
// Every command and option there is: a misspelt one is refused by name, not passed over
|
|
137
146
|
const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
|
|
138
|
-
'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'beams', 'wires', 'machine', 'plot', 'plates', 'order', 'match', 'variants', 'compare', 'help'];
|
|
147
|
+
'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'beams', 'frame', 'wires', 'machine', 'plot', 'plates', 'order', 'kit', 'match', 'variants', 'compare', 'help'];
|
|
139
148
|
const OPTIONS = ['table', 'calibrate', 'check', 'turns', 'preview', 'gap', 'no-steps', 'all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
|
|
140
149
|
'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'profile', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
|
|
141
150
|
'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
|
|
142
|
-
'unit', 'rule', 'label', 'from', 'out', // cad set, cad rules
|
|
151
|
+
'unit', 'rule', 'label', 'from', 'out', 'jigs', 'no-jigs', 'expand', 'size', 'write', 'pictures', // cad set, cad rules, cad beams, cad frame, cad plates, cad kit
|
|
143
152
|
'a', 'b', 'min', 'max', 'poses', 'id', 'type', 'parent', 'child', 'follow', 'value', 'ratio', 'object', 'assembly', 'variant', 'rotate', 'to', 'roll', // cad add
|
|
144
|
-
'screw', 'through', 'into', 'holes', 'nut', 'washer', 'length', 'torque', 'from-fits'
|
|
153
|
+
'screw', 'through', 'into', 'holes', 'nut', 'washer', 'length', 'torque', 'from-fits', // cad add fasten
|
|
154
|
+
'kind', 'fitting']; // cad add join
|
|
145
155
|
// What a command takes, where that isn't <project>/<object>
|
|
146
|
-
const USAGE = { add: 'fit|joint|item|beam|loop|pose|fasten <project>/<assembly> --key value …', why: '<project>/<object>.<variable>', set: '<project>/<object> name=value …',
|
|
156
|
+
const USAGE = { add: 'fit|joint|item|beam|loop|pose|fasten|join <project>/<assembly> --key value …', why: '<project>/<object>.<variable>', set: '<project>/<object> name=value …',
|
|
147
157
|
optimise: '<project>/<problem>', optimize: '<project>/<problem>', history: '<project>[/<object>]', release: '<project>[/<object>] -m "what changed"',
|
|
148
158
|
diff: '<project>/<object> <from> [<to>]', compare: '<project>/<object> <a> <b>', match: '<project>/<object> <model.stl|model.3mf>', clone: '<board.kicad_pcb | GitHub link> <name>' };
|
|
149
159
|
|
|
150
160
|
const args = process.argv.slice(2);
|
|
151
161
|
// Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
|
|
152
162
|
// (--sweep, --watch and --nut take one or not).
|
|
153
|
-
const FLAGS = ['table', 'calibrate', 'check', 'preview', 'no-steps', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short', 'washer', 'from-fits'];
|
|
163
|
+
const FLAGS = ['table', 'calibrate', 'check', 'preview', 'no-steps', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short', 'washer', 'from-fits', 'jigs', 'no-jigs', 'pictures', 'expand', 'size', 'write'];
|
|
154
164
|
const opt = (k) => {
|
|
155
165
|
const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
|
|
156
166
|
if (i < 0) return undefined;
|
|
@@ -467,8 +477,10 @@ async function main() {
|
|
|
467
477
|
if (cmd === 'compare') return compareVariants(locate(ref), pos[2], pos[3]);
|
|
468
478
|
if (cmd === 'measured') return measuredCommand(ref);
|
|
469
479
|
if (cmd === 'list' || cmd === 'wires' || cmd === 'beams') return listCommand(cmd, ref);
|
|
480
|
+
if (cmd === 'frame') return frameCommand(ref);
|
|
470
481
|
if (cmd === 'machine' || cmd === 'plot') return machineCommand(cmd, ref);
|
|
471
482
|
if (cmd === 'plates' || cmd === 'order') return platesCommand(cmd, ref);
|
|
483
|
+
if (cmd === 'kit') return kitCommand(ref);
|
|
472
484
|
if (cmd === 'history') return history(ref);
|
|
473
485
|
if (cmd === 'diff') return diff(locate(ref), pos[2], pos[3] || null);
|
|
474
486
|
if (cmd === 'printed') return printed(locate(ref));
|
|
@@ -602,7 +614,7 @@ async function editVariables(ref) {
|
|
|
602
614
|
console.log(`set ${r.changed.join(', ')} in ${path.relative(WS, r.file)}`);
|
|
603
615
|
}
|
|
604
616
|
|
|
605
|
-
// cad add fit|joint|item|loop|pose|fasten <project>/<assembly> --key value …: add to an assembly, keeping its layout
|
|
617
|
+
// cad add fit|joint|item|loop|pose|fasten|join <project>/<assembly> --key value …: add to an assembly, keeping its layout
|
|
606
618
|
async function editAssembly(what, ref) {
|
|
607
619
|
const list = (k) => (typeof opt(k) === 'string' ? opt(k).split(',').map((x) => parseValue(x.trim())) : undefined);
|
|
608
620
|
const pick = (keys) => Object.fromEntries(keys.map((k) => [k, typeof opt(k) === 'string' ? parseValue(opt(k)) : undefined]).filter(([, v]) => v !== undefined));
|
|
@@ -629,11 +641,12 @@ async function editAssembly(what, ref) {
|
|
|
629
641
|
const names = (k) => (typeof opt(k) === 'string' ? opt(k).split(',').map((x) => x.trim()).filter(Boolean) : undefined);
|
|
630
642
|
entry = { ...text(['screw']), through: names('through') ?? [], ...text(['into']), ...(names('at') ? { at: names('at') } : {}), ...text(['holes']), ...(opt('nut') ? { nut: opt('nut') === true ? true : String(opt('nut')) } : {}), ...(opt('washer') ? { washer: true } : {}), ...pick(['length', 'torque']), ...text(['note']) };
|
|
631
643
|
}
|
|
644
|
+
else if (what === 'join') entry = text(['kind', 'a', 'b', 'fitting', 'screw', 'note']);
|
|
632
645
|
else if (what === 'pose') {
|
|
633
646
|
const pairs = positional().slice(3);
|
|
634
647
|
if (typeof opt('name') !== 'string' || !pairs.length) throw new Error('usage: cad add pose <project>/<assembly> --name open hinge=90 [joint=value …]');
|
|
635
648
|
entry = { name: opt('name'), values: Object.fromEntries(pairs.map((p) => { const [k, v] = p.split('='); return [k.trim(), v.includes(',') ? v.split(',').map(parseValue) : parseValue(v)]; })) };
|
|
636
|
-
} else throw new Error('usage: cad add fit|joint|item|beam|loop|pose|fasten <project>/<assembly> --key value …');
|
|
649
|
+
} else throw new Error('usage: cad add fit|joint|item|beam|loop|pose|fasten|join <project>/<assembly> --key value …');
|
|
637
650
|
const r = addToAssembly(ref, what === 'beam' ? 'item' : what, entry);
|
|
638
651
|
if (opt('json')) return console.log(JSON.stringify({ ...r, added: entry }));
|
|
639
652
|
console.log(`added ${/^[aeiou]/.test(what) ? "an" : "a"} ${what} to ${path.relative(WS, r.file)}`);
|
|
@@ -709,17 +722,7 @@ async function assembly(cmd, ref) {
|
|
|
709
722
|
if (cmd === 'check') {
|
|
710
723
|
say(`${title} (${a.kind || 'fit'}: ${versions})`);
|
|
711
724
|
// Each pose (or the one asked for): what's the same in every pose is said once, the rest under the pose's name
|
|
712
|
-
const
|
|
713
|
-
const file = path.join(paths.project(s.project), 'assemblies', `${s.name}.json`), layouts = new Set((a.items || []).map((i) => i.repeat?.layout).filter((l) => l && !l.includes('/')));
|
|
714
|
-
const schemaProblems = [...(fs.existsSync(file) ? schemaFindings(JSON.parse(fs.readFileSync(file, 'utf8')), 'assembly', path.relative(WS, file)) : []),
|
|
715
|
-
...[...layouts].map((l) => path.join(paths.project(s.project), 'layouts', `${l}.json`)).filter((f) => fs.existsSync(f)).flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'layout', path.relative(WS, f)))];
|
|
716
|
-
let findings = checkAssembly(s);
|
|
717
|
-
if (poses.length > 1) {
|
|
718
|
-
const each = poses.map((p) => [p, checkAssembly(s.at(p))]), same = (x) => each.every(([, list]) => list.some((y) => y.text === x.text && y.level === x.level));
|
|
719
|
-
findings = [{ level: 'pass', text: `${poses.length} poses checked: ${poses.join(', ')}`, code: 'poses', refs: { poses } }, ...each[0][1].filter(same),
|
|
720
|
-
...each.flatMap(([p, list]) => list.filter((x) => !same(x)).map((x) => ({ ...x, text: `${p}: ${x.text}`, ...(x.card ? { card: `${p}: ${x.card}` } : {}), refs: { ...x.refs, pose: p } })))];
|
|
721
|
-
}
|
|
722
|
-
findings.unshift(...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]));
|
|
725
|
+
const findings = assemblyFindings(s, a, pose);
|
|
723
726
|
if (opt('sweep')) findings.push(...sweep(s, { joint: typeof opt('sweep') === 'string' ? opt('sweep') : undefined, steps: Number(opt('steps')) || 24, progress: showProgress }));
|
|
724
727
|
if (a.kind === 'plate') findings.push(...check(printed.flatMap((p) => p.triangles), rules(printerOf(s.project)), { parts: printed }));
|
|
725
728
|
process.exitCode = report(findings, { assembly: ref, title, kind: a.kind || 'fit', ...(pose ? { pose } : {}) }) ? 1 : 0;
|
|
@@ -1022,27 +1025,112 @@ async function platesCommand(what, ref) {
|
|
|
1022
1025
|
if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
|
|
1023
1026
|
const s = await buildAssembly(ref);
|
|
1024
1027
|
if (what === 'order') {
|
|
1025
|
-
const { orderOf, orderText, stepPictures } = await import('../lib/order.mjs'), r = orderOf(s);
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
if (r.stuck)
|
|
1028
|
+
const { orderOf, orderText, stepPictures } = await import('../lib/order.mjs'), { withPreload } = await import('../lib/slotnuts.mjs'), r = withPreload(s, orderOf(s));
|
|
1029
|
+
// a frame (beams with joins): from bars to a square frame, its sides built flat, nuts loaded before the join that would shut them in
|
|
1030
|
+
const frame = s.joins?.length ? (await import('../lib/framebuild.mjs')) : null, fb = frame ? frame.frameBuild(s) : null;
|
|
1031
|
+
if (opt('json')) { console.log(JSON.stringify(fb ? { ...r, frame: fb } : r, null, 2)); if (r.stuck || fb?.stuck) process.exitCode = 1; return; }
|
|
1032
|
+
console.log(fb ? frame.frameBuildText(ref, fb) : orderText(ref, r));
|
|
1033
|
+
if (r.stuck || fb?.stuck) { process.exitCode = 1; return; }
|
|
1034
|
+
if (opt('preview') && fb) { for (const { n, parts } of frame.frameStepPictures(s, fb)) { const st = fb.steps[n - 1], out = paths.preview(s.project, `${s.name}-step-${String(n).padStart(2, '0')}.png`); await preview(parts, { title: `${s.a.title || s.name}: step ${n} of ${fb.steps.length}`, meta: st.text, out }); console.log(path.relative(WS, out)); } return; } // (numbered as the frame's build is)
|
|
1029
1035
|
if (opt('preview')) { const pics = stepPictures(s, r); for (const [i, parts] of pics.entries()) { const st = r.steps[i], out = paths.preview(s.project, `${s.name}-step-${String(st.n).padStart(2, '0')}.png`); await preview(parts, { title: `${s.a.title || s.name}: step ${st.n} of ${r.steps.length}`, meta: st.text, out }); console.log(path.relative(WS, out)); } }
|
|
1030
1036
|
return;
|
|
1031
1037
|
}
|
|
1032
1038
|
const { platesOf, checkPlate } = await import('../lib/plates.mjs'), gap = opt('gap') != null ? Number(opt('gap')) : undefined;
|
|
1033
1039
|
if (gap != null && !(gap > 0)) throw new Error(`--gap is a distance in mm, above 0 (got ${opt('gap')})`);
|
|
1034
|
-
|
|
1040
|
+
// a frame's jigs (its beams' drill and tap guides, length stops and squaring corners) on beds of their own, in the
|
|
1041
|
+
// project's plastic: exports/<project>/<assembly>.jigs.3mf, as cad beams --jigs writes them (--no-jigs leaves them)
|
|
1042
|
+
const { cutListOf } = await import('../lib/beams.mjs'), jigs = !opt('no-jigs') && cutListOf(s) ? await (await import('../lib/jigs.mjs')).writeJigs(s) : null;
|
|
1043
|
+
let r;
|
|
1044
|
+
try { r = await platesOf(s, { write: true, gap }); } catch (e) { if (e.code !== 'plates.empty' || !jigs?.jigs.length) throw e; r = { bed: null, gap: null, plates: [], touched: [], removed: [], findings: [] }; } // (bought fittings only: the jigs are what it prints)
|
|
1045
|
+
const results = [];
|
|
1035
1046
|
for (const p of r.plates.filter((x) => !x.stood)) results.push({ name: p.name, findings: await checkPlate(`${s.project}/${p.name}`) });
|
|
1036
|
-
const
|
|
1037
|
-
|
|
1047
|
+
const jigRows = jigs ? { plates: jigs.plates.map((p) => ({ ...p, file: path.relative(WS, p.file) })), count: jigs.jigs.length, grams: +jigs.jigs.reduce((t, x) => t + x.grams, 0).toFixed(1), findings: jigs.findings } : null;
|
|
1048
|
+
const fails = [...r.findings, ...results.flatMap((x) => x.findings), ...(jigs?.findings ?? [])].some((x) => x.level === 'fail');
|
|
1049
|
+
if (opt('json')) { console.log(JSON.stringify({ assembly: ref, bed: r.bed, gap: r.gap, plates: r.plates, repacked: r.touched, removed: r.removed, findings: r.findings, checks: results, ...(jigRows ? { jigs: jigRows } : {}) }, null, 2)); process.exitCode = fails ? 1 : 0; return; }
|
|
1038
1050
|
report(r.findings);
|
|
1039
|
-
say(`${ref}: ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}, parts ${r.gap} mm apart (the first layer's rule)`);
|
|
1040
|
-
for (const p of r.plates) say(` ${p.name}${p.stood ? ' (unchanged)' : ''}: ${p.filament}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min: ${p.parts.map((x) => x.id).join(', ')}`);
|
|
1051
|
+
if (r.plates.length) say(`${ref}: ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}, parts ${r.gap} mm apart (the first layer's rule)`);
|
|
1052
|
+
for (const p of r.plates) say(` ${p.name}${p.stood ? ' (unchanged)' : ''}: ${p.material}, ${p.filament}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min: ${p.parts.map((x) => x.id).join(', ')}`);
|
|
1041
1053
|
if (r.removed.length) say(` removed ${r.removed.join(', ')} (nothing is on them now)`);
|
|
1042
1054
|
for (const x of results) { const bad = x.findings.filter((y) => (y.level === 'fail' || y.level === 'warn') && y.code !== 'rules.estimate'); say(` ${x.name}: ${bad.length ? `${bad.length} to look at` : 'prints clean'}`); for (const y of bad) say(` [${y.level}] ${y.text}`); }
|
|
1055
|
+
if (jigRows?.count) {
|
|
1056
|
+
say(`${ref}: ${jigRows.count} jig${jigRows.count === 1 ? '' : 's'} for its beams, ${jigRows.grams} g, on ${jigRows.plates.length} plate${jigRows.plates.length === 1 ? '' : 's'} of their own (cad beams ${ref} --jigs says what each is for)`);
|
|
1057
|
+
for (const p of jigRows.plates) say(` ${p.file}: ${p.material}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}`);
|
|
1058
|
+
for (const f of jigRows.findings) say(` [${f.level}] ${f.text}`);
|
|
1059
|
+
}
|
|
1043
1060
|
process.exitCode = fails ? 1 : 0;
|
|
1044
1061
|
}
|
|
1045
1062
|
|
|
1063
|
+
// An assembly's findings as cad check gives them: each pose (or the one asked for), what is the same in every pose
|
|
1064
|
+
// said once and the rest under the pose's name, after its files' schema check. cad kit counts the same list
|
|
1065
|
+
function assemblyFindings(s, a, pose) {
|
|
1066
|
+
const poses = pose ? [pose] : Object.keys(s.motion.poses);
|
|
1067
|
+
const file = path.join(paths.project(s.project), 'assemblies', `${s.name}.json`), layouts = new Set((a.items || []).map((i) => i.repeat?.layout).filter((l) => l && !l.includes('/')));
|
|
1068
|
+
const schemaProblems = [...(fs.existsSync(file) ? schemaFindings(JSON.parse(fs.readFileSync(file, 'utf8')), 'assembly', path.relative(WS, file)) : []),
|
|
1069
|
+
...[...layouts].map((l) => path.join(paths.project(s.project), 'layouts', `${l}.json`)).filter((f) => fs.existsSync(f)).flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'layout', path.relative(WS, f)))];
|
|
1070
|
+
let findings = checkAssembly(s);
|
|
1071
|
+
if (poses.length > 1) {
|
|
1072
|
+
const each = poses.map((p) => [p, checkAssembly(s.at(p))]), same = (x) => each.every(([, list]) => list.some((y) => y.text === x.text && y.level === x.level));
|
|
1073
|
+
findings = [{ level: 'pass', text: `${poses.length} poses checked: ${poses.join(', ')}`, code: 'poses', refs: { poses } }, ...each[0][1].filter(same),
|
|
1074
|
+
...each.flatMap(([p, list]) => list.filter((x) => !same(x)).map((x) => ({ ...x, text: `${p}: ${x.text}`, ...(x.card ? { card: `${p}: ${x.card}` } : {}), refs: { ...x.refs, pose: p } })))];
|
|
1075
|
+
}
|
|
1076
|
+
findings.unshift(...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]));
|
|
1077
|
+
return findings;
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
// cad kit: the folder to build an assembly from, without the model (lib/kit.mjs)
|
|
1081
|
+
async function kitCommand(ref) {
|
|
1082
|
+
if (!isAssembly(ref)) throw new Error(`cad kit works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
|
|
1083
|
+
// (laying out its plates reads the printer's rule set: a fresh workspace gets its own copy in rules/, as cad plates
|
|
1084
|
+
// gives it, and the kit says which it copied)
|
|
1085
|
+
const rulesDir = path.join(WS, 'rules'), had = new Set(fs.existsSync(rulesDir) ? fs.readdirSync(rulesDir) : []);
|
|
1086
|
+
const s = await buildAssembly(ref), { writeKit } = await import('../lib/kit.mjs');
|
|
1087
|
+
const r = await writeKit(s, assemblyFindings(s, s.a, undefined), { pictures: !!opt('pictures'), preview });
|
|
1088
|
+
const copied = (fs.existsSync(rulesDir) ? fs.readdirSync(rulesDir) : []).filter((f) => f.endsWith('.json') && !had.has(f)).map((f) => `rules/${f}`);
|
|
1089
|
+
const shown = { assembly: ref, dir: path.relative(WS, r.dir), files: r.files, copied, plates: r.plates.map(({ name, material, filament, parts, grams, minutes, file, issues }) => ({ name, material, filament, parts: parts.length, grams, minutes, file, issues })), jigs: r.jigs, sheets: r.sheets, steps: r.steps, warnings: r.findings.map((f) => f.text) };
|
|
1090
|
+
if (opt('json')) return console.log(JSON.stringify(shown, null, 2));
|
|
1091
|
+
say(`${ref}: the kit to build it from, in ${shown.dir}${path.sep}`);
|
|
1092
|
+
say(` README.md: what the checks say, what to buy, what to print${r.sheets.length ? ', the cut list, the drilling and tapping' : ''}${r.steps ? `, and the build in ${r.steps} steps` : ''}`);
|
|
1093
|
+
say(' buy.csv: the shopping list');
|
|
1094
|
+
for (const p of shown.plates) say(` ${p.file}: ${p.material}, ${p.parts} part${p.parts === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min${p.issues.length ? ` (${p.issues.length} to look at)` : ''}`);
|
|
1095
|
+
for (const p of r.jigs?.plates ?? []) say(` ${p.file}: ${r.jigs.count} jigs for the beams, ${p.parts} parts`);
|
|
1096
|
+
for (const x of r.sheets) say(` ${x.file}: mark ${x.mark} (${x.items.join(', ')})`);
|
|
1097
|
+
const pics = r.files.filter((f) => f.startsWith('pictures/'));
|
|
1098
|
+
if (pics.length) say(` pictures/: ${pics.length} pictures (the whole, and the steps of the build)`);
|
|
1099
|
+
for (const w of shown.warnings) say(` warning: ${w}`);
|
|
1100
|
+
for (const f of copied) say(`and copied ${f} into this workspace: the rule set its plates were laid out by, yours to keep and edit (the next kit reads your copy)`);
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
// cad frame: a generated frame as it expands, and --expand writes the expansion into the assembly, to edit by hand
|
|
1104
|
+
async function frameCommand(ref) {
|
|
1105
|
+
if (!isAssembly(ref)) throw new Error(`cad frame works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
|
|
1106
|
+
const { expandFrame, frameText } = await import('../lib/framegen.mjs'), { assemblyPath } = await import('../lib/assembly.mjs');
|
|
1107
|
+
const file = assemblyPath(ref), raw = readJson(file);
|
|
1108
|
+
if (opt('size')) {
|
|
1109
|
+
const { frameSizing, sizingText, writeSizing, sizeOption } = await import('../lib/framesize.mjs'), { placeItems, jointValues, mul } = await import('@rulecad/model-link');
|
|
1110
|
+
const s = await buildAssembly(ref), r = frameSizing(s, { placeItems, jointValues, mul }, sizeOption(s) ?? undefined);
|
|
1111
|
+
if (!r) throw new Error(`${ref} has no frame to size: its beams need joins between them, or "frame": { "supports" }`);
|
|
1112
|
+
const rows = r.rows, out = { assembly: ref, ok: r.ok, total: r.total, drawn: r.drawn, tried: r.tried, search: r.search, groups: rows, limits: r.limits };
|
|
1113
|
+
if (opt('write')) {
|
|
1114
|
+
if (!r.ok) throw new Error(`${ref}: no profile in the list meets every limit, so nothing is written (cad frame ${ref} --size says how near it comes)`);
|
|
1115
|
+
fs.writeFileSync(file, `${JSON.stringify(writeSizing(raw, raw.frame?.kind != null ? expandFrame(raw, s.num).a : raw, r), null, 2)}\n`);
|
|
1116
|
+
if (opt('json')) return console.log(JSON.stringify({ ...out, file: path.relative(WS, file) }, null, 2));
|
|
1117
|
+
console.log(sizingText(r).join('\n'));
|
|
1118
|
+
return console.log(`wrote ${path.relative(WS, file)}: ${rows.reduce((t, x) => t + x.beams.length, 0)} beams given their profiles${raw.frame?.kind != null ? ' (the generated frame written out expanded, as --expand does, as a generator takes one profile)' : ''}; their lines are kept (a deeper beam that would stand past the end of the one it meets moves along it), so check the joins and ends of any beam that changed size`);
|
|
1119
|
+
}
|
|
1120
|
+
if (opt('json')) return console.log(JSON.stringify(out, null, 2));
|
|
1121
|
+
return console.log(`${ref}: ${sizingText(r).join('\n')}\n(cad frame ${ref} --size --write writes these profiles into the assembly)`);
|
|
1122
|
+
}
|
|
1123
|
+
if (raw.frame?.kind == null) throw new Error(`${ref} asks for no generated frame: give it "frame": { "kind": "box", "inside": [300, 300, 350], "profile": "2020-misumi-hfs5", "join": "blind" }`);
|
|
1124
|
+
const s = await buildAssembly(ref), m = s.generated, out = expandFrame(raw, s.num).a;
|
|
1125
|
+
if (opt('expand')) {
|
|
1126
|
+
fs.writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`);
|
|
1127
|
+
if (opt('json')) return console.log(JSON.stringify({ assembly: ref, file: path.relative(WS, file), frame: m }, null, 2));
|
|
1128
|
+
return console.log(`wrote ${path.relative(WS, file)}: the ${m.kind} as ${m.beams.length + (m.moving ? 1 : 0)} beams, ${m.joins.length} joins and ${m.ends.length + m.panels.length} fittings, to edit by hand (its "frame" keeps only how it is solved)`);
|
|
1129
|
+
}
|
|
1130
|
+
if (opt('json')) return console.log(JSON.stringify({ assembly: ref, frame: m, expanded: out }, null, 2));
|
|
1131
|
+
console.log(`${ref}: ${frameText(m).join('\n')}\n(cad frame ${ref} --expand writes these into the assembly, to edit by hand)`);
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1046
1134
|
async function listCommand(what, ref) {
|
|
1047
1135
|
if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
|
|
1048
1136
|
const s = await buildAssembly(ref);
|
|
@@ -1050,11 +1138,29 @@ async function listCommand(what, ref) {
|
|
|
1050
1138
|
const { shoppingList, listText } = await import('../lib/list.mjs'), l = shoppingList(s);
|
|
1051
1139
|
return console.log(opt('json') ? JSON.stringify(l, null, 2) : listText(ref, l));
|
|
1052
1140
|
}
|
|
1141
|
+
if (what === 'beams' && opt('jigs')) {
|
|
1142
|
+
const { writeJigs, jigsText } = await import('../lib/jigs.mjs'), r = await writeJigs(s), rel = (f) => path.relative(WS, f);
|
|
1143
|
+
const shown = { ...r, plates: r.plates.map((p) => ({ ...p, file: rel(p.file) })) };
|
|
1144
|
+
if (opt('preview') && r.parts.length) {
|
|
1145
|
+
const out = paths.preview(s.project, `${s.name}-jigs.png`);
|
|
1146
|
+
await preview(r.parts.flatMap((o) => o.parts.map((p) => ({ name: p.name, label: p.name, role: 'part', triangles: p.triangles }))), { title: `${s.a.title || s.name}: jigs`, meta: `${r.jigs.length} jigs on ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}`, out });
|
|
1147
|
+
shown.preview = rel(out);
|
|
1148
|
+
}
|
|
1149
|
+
delete shown.parts;
|
|
1150
|
+
process.exitCode = r.findings.some((f) => f.level === 'fail') ? 1 : 0;
|
|
1151
|
+
if (opt('json')) return console.log(JSON.stringify(shown, null, 2));
|
|
1152
|
+
console.log(jigsText(ref, shown));
|
|
1153
|
+
if (shown.preview) say(shown.preview);
|
|
1154
|
+
return;
|
|
1155
|
+
}
|
|
1053
1156
|
if (what === 'beams') {
|
|
1054
1157
|
const { writeBeamSheets } = await import('../lib/beams.mjs'), sheets = writeBeamSheets(s);
|
|
1055
1158
|
if (opt('json')) return console.log(JSON.stringify(sheets.map((x) => ({ ...x, file: path.relative(WS, x.file) })), null, 2));
|
|
1056
1159
|
if (!sheets.length) return console.log(`${ref} has no beams`);
|
|
1057
1160
|
for (const x of sheets) say(` mark ${x.mark} (${x.items.join(', ')}), 1:${x.scale}: ${path.relative(WS, x.file)}`);
|
|
1161
|
+
const { writeFrameShape, writeFrameMode } = await import('../lib/framecheck.mjs'), sag = writeFrameShape(s), mode = writeFrameMode(s);
|
|
1162
|
+
if (sag) say(` the frame's sag, drawn ${+sag.scale.toPrecision(3)} times its size (a check view): ${path.relative(WS, sag.file)}`);
|
|
1163
|
+
if (mode) say(` the frame's lowest mode, ${+mode.Hz.toPrecision(3)} Hz, animated (a check view): ${path.relative(WS, mode.file)}`);
|
|
1058
1164
|
return;
|
|
1059
1165
|
}
|
|
1060
1166
|
const { wiresFor } = await import('../lib/assembly.mjs'), { wiringSheet } = await import('../lib/wires.mjs'), rows = wiresFor(s);
|
package/lib/assembly.mjs
CHANGED
|
@@ -18,6 +18,8 @@
|
|
|
18
18
|
// diameter) half way down, so the screw has something to grip. "direction": "up" for screws from below.
|
|
19
19
|
// A screwed joint is a fasten (lib/fasten.mjs): { "screw": "M3 cap", "through": ["bracket"], "into": "base", "at": ["bracket.h1"] }.
|
|
20
20
|
// Its holes are read from the parts as drawn, its screws placed as reference parts, and it holds as a fit that fastens does.
|
|
21
|
+
// Beams are held to each other by joins (lib/joins.mjs): { "kind": "blind", "a": "y1.a", "b": "x1.back@120" }. Each puts
|
|
22
|
+
// its operations on both beams and its screws into fasten before anything is built, and is checked once it is.
|
|
21
23
|
import { host, readJson } from './host.mjs';
|
|
22
24
|
import fs from 'node:fs';
|
|
23
25
|
import crypto from 'node:crypto';
|
|
@@ -41,12 +43,23 @@ import { wiresOf, wireChecks, wireRows, wireTubes, wireRoutes } from './wires.mj
|
|
|
41
43
|
import { printedParts } from './list.mjs';
|
|
42
44
|
import { taskOf, taskChecks } from './task.mjs';
|
|
43
45
|
import { powerChecks } from './power.mjs';
|
|
44
|
-
import { loadChecks } from './loads.mjs';
|
|
46
|
+
import { loadChecks, beyond } from './loads.mjs';
|
|
45
47
|
import { gripChecks } from './grip.mjs';
|
|
46
48
|
import { gaitOf, gaitChecks, gaitSequence } from './gait.mjs';
|
|
47
49
|
import { boughtBuilt, boughtFindings, boughtSets } from './bought.mjs';
|
|
48
50
|
import { orderChecks } from './order.mjs';
|
|
49
|
-
import { beamBuilt, beamPlace, beamAddress, beamFindings, marksOf } from './beams.mjs';
|
|
51
|
+
import { beamBuilt, beamPlace, beamAddress, beamFindings, marksOf, framesContext } from './beams.mjs';
|
|
52
|
+
import { fittingBuilt, fittingFindings, plasticOf } from './fittings.mjs';
|
|
53
|
+
import { expandJoins, joinChecks } from './joins.mjs';
|
|
54
|
+
import { expandFrame, frameText } from './framegen.mjs';
|
|
55
|
+
import { frameChecks } from './framecheck.mjs';
|
|
56
|
+
import { sizeChecks } from './framesize.mjs';
|
|
57
|
+
import { frameHeatChecks } from './frameheat.mjs';
|
|
58
|
+
import { expandPanels, panelBuilt, panelFindings, PANEL_CHECK } from './panels.mjs';
|
|
59
|
+
import { expandServices, serviceFindings } from './services.mjs';
|
|
60
|
+
import { expandGuides, guideBuilt, guideFindings } from './guides.mjs';
|
|
61
|
+
import { slotNutChecks } from './slotnuts.mjs';
|
|
62
|
+
import { frameSquareChecks, frameBuild } from './framebuild.mjs';
|
|
50
63
|
let fastening = null; // lib/fasten.mjs, loaded with the first assembly that has a fasten: the rest start as fast as before
|
|
51
64
|
|
|
52
65
|
export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
|
|
@@ -79,7 +92,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
79
92
|
const outer = overrides;
|
|
80
93
|
const [project, name] = ref.split('/');
|
|
81
94
|
if (stack.includes(ref)) throw new Error(`assembly ${ref} contains itself (${[...stack, ref].join(' → ')})`);
|
|
82
|
-
|
|
95
|
+
let a = readJson(assemblyPath(ref));
|
|
83
96
|
// A pose may set items' variables as well as joints ("cocked": { "run": -30, "action.travel": 25 }): a flexure bent
|
|
84
97
|
// as the pose bends it, while the part itself is printed as drawn. The pose being built sets them on its items.
|
|
85
98
|
const itemSets = (name) => { const out = {}; for (const [k, v] of Object.entries(a.poses?.[name] || {})) if (k.includes('.')) { const [item, ...rest] = k.split('.'); (out[item] ||= {})[rest.join('.')] = v; } return out; };
|
|
@@ -104,6 +117,21 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
104
117
|
return v;
|
|
105
118
|
};
|
|
106
119
|
const num = (x) => evaluate(x, lookup);
|
|
120
|
+
// A generated frame (lib/framegen.mjs): "frame": { "kind": "box", "inside": [..] } into beams, joins and their ends, first
|
|
121
|
+
let generated = null;
|
|
122
|
+
if (a.frame && typeof a.frame === 'object' && !Array.isArray(a.frame)) ({ a, frame: generated } = expandFrame(a, num, framesContext()));
|
|
123
|
+
// Joins between beams (lib/joins.mjs): their operations go on the beams and their screws into fasten before anything is built
|
|
124
|
+
let joins = [];
|
|
125
|
+
if (a.joins != null) ({ a, joins } = expandJoins(a, num, undefined, plasticOf(project)));
|
|
126
|
+
// Panels (lib/panels.mjs): each placed on its bay, its clips or a door's hinges, handle and catch added with their fastens
|
|
127
|
+
let panels = [];
|
|
128
|
+
if ((a.items || []).some((it) => it?.panel)) ({ a, panels } = expandPanels(a, num, undefined, plasticOf(project)));
|
|
129
|
+
// Services (lib/services.mjs): a bought board or supply on its printed mount, a wire's run along a slot held by clips
|
|
130
|
+
let mounts = [], runs = [];
|
|
131
|
+
if ((a.items || []).some((it) => it?.mount != null) || (a.wires || []).some((w) => (w?.via ?? []).some((v) => v && typeof v === 'object'))) ({ a, mounts, runs } = expandServices(a, num, undefined, plasticOf(project)));
|
|
132
|
+
// Guides (lib/guides.mjs): a rail on a beam's face, its screws into the slot, each carriage on its own sliding joint
|
|
133
|
+
let guides = [];
|
|
134
|
+
if (a.guides != null) ({ a, guides } = expandGuides(a, num, undefined, plasticOf(project)));
|
|
107
135
|
const { translate, rotate, transform } = jscad.transforms, deg = Math.PI / 180;
|
|
108
136
|
|
|
109
137
|
const items = [], parts = [], objects = [], fits = [], requires = [];
|
|
@@ -112,6 +140,9 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
112
140
|
const source = async (it, extra) => {
|
|
113
141
|
if (it.motor) { const key = JSON.stringify(['motor', it.id, it.motor]); if (!built.has(key)) built.set(key, motorBuilt(it.motor, num, it.id)); return built.get(key); }
|
|
114
142
|
if (it.beam) { const b = beamBuilt(it, num, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/beams.mjs)
|
|
143
|
+
if (it.fitting) { const b = await fittingBuilt(it, it.id, framesContext(), plasticOf(project)); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/fittings.mjs)
|
|
144
|
+
if (it.panel) { const b = await panelBuilt(it, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/panels.mjs)
|
|
145
|
+
if (it._guide) { const b = guideBuilt(it, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/guides.mjs)
|
|
115
146
|
if (it.bought) {
|
|
116
147
|
const key = JSON.stringify(['bought', it.id, it.bought, it.variant, it.set]);
|
|
117
148
|
if (!built.has(key)) built.set(key, boughtSets().get(it.bought) === 'motor' ? motorBuilt({ model: it.bought }, num, it.id) : boughtBuilt(it.bought, it, num, it.id));
|
|
@@ -153,7 +184,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
153
184
|
let builtCount = 0;
|
|
154
185
|
for (const it of a.items || []) {
|
|
155
186
|
if (!/^[a-z][\w-]*$/.test(it.id || '')) throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
|
|
156
|
-
if ([it.object, it.assembly, it.motor, it.bought, it.beam].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly", "motor", "bought" or "
|
|
187
|
+
if ([it.object, it.assembly, it.motor, it.bought, it.beam, it.fitting, it.panel].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly", "motor", "bought", "beam", "fitting" or "panel"`);
|
|
157
188
|
if (!it.beam && (it.to != null || it.roll != null)) throw new Error(`item ${it.id}: to and roll place a beam by its ends: place ${it.object || it.assembly || it.motor?.model || it.bought} with at and rotate`);
|
|
158
189
|
// Copies: one, a grid from repeat x/y, or a layout's keys. Each: { id, offset (from at), extra (values to set) }
|
|
159
190
|
const rx = it.repeat?.x, ry = it.repeat?.y, rl = it.repeat?.layout, copies = [];
|
|
@@ -219,7 +250,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
219
250
|
for (const n of sub.seen) seen.add(n);
|
|
220
251
|
items.push({ ...it, id, sub, role: 'part' });
|
|
221
252
|
} else {
|
|
222
|
-
objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role, ...(src.set ? { set: src.set } : {}), ...(src.variant ? { variant: src.variant } : {}), ...(src.bought ? { bought: src.bought } : {}), ...(src.motor ? { motor: src.motor } : {}), ...(src.beam ? { beam: src.beam } : {}) });
|
|
253
|
+
objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role, ...(src.set ? { set: src.set } : {}), ...(src.variant ? { variant: src.variant } : {}), ...(src.bought ? { bought: src.bought } : {}), ...(src.motor ? { motor: src.motor } : {}), ...(src.beam ? { beam: src.beam } : {}), ...(src.fitting ? { fitting: src.fitting } : {}), ...(src.panel ? { panel: src.panel } : {}) });
|
|
223
254
|
items.push({ ...it, id, objName: src.objName, built: src.b, version: src.version, role: src.role, ...(src.beam ? { beam: src.beam } : {}) });
|
|
224
255
|
}
|
|
225
256
|
}
|
|
@@ -244,7 +275,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
244
275
|
for (const p of src.b.parts) {
|
|
245
276
|
if (p.role === 'support' && a.kind !== 'plate') continue; // supports are snipped off before parts go together
|
|
246
277
|
out.push({ name: `${id}.${p.name}`, item: id, leaf: id, object: src.objName, role: src.role === 'reference' ? 'reference' : p.role, label: `${id}: ${marks.has(id) ? `mark ${marks.get(id)}, ` : ''}${p.label}`,
|
|
247
|
-
...(p.filament ? { filament: p.filament } : {}), ...(p.mirror === false ? { mirror: false } : {}), part: p.name,
|
|
278
|
+
...(p.filament ? { filament: p.filament } : {}), ...(p.mirror === false ? { mirror: false } : {}), ...(p.fill != null ? { fill: p.fill } : {}), part: p.name,
|
|
248
279
|
geometry: transform(m, p.geometry), ...(p.collide ? { collide: transform(m, p.collide) } : {}), polygons: move(p.polygons), triangles: move(p.triangles),
|
|
249
280
|
shape: `${key}:${p.name}`, hash: `${src.b.hash}:${p.name}`, local: p.polygons, localTriangles: p.triangles, m });
|
|
250
281
|
}
|
|
@@ -303,7 +334,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
303
334
|
const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
|
|
304
335
|
return { ...s, parts: moved, fastened: null, pose: typeof p === 'string' ? p : null, jointValues: v, polygons: moved.flatMap((x) => x.polygons), triangles: moved.flatMap((x) => x.triangles) };
|
|
305
336
|
};
|
|
306
|
-
const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, wires, task, gait, fastened, hardware, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
|
|
337
|
+
const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, wires, task, gait, fastened, hardware, joins, generated, panels, mounts, runs, guides, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
|
|
307
338
|
polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
|
|
308
339
|
return s;
|
|
309
340
|
}
|
|
@@ -742,7 +773,7 @@ function pairOverlap(pa, pb) {
|
|
|
742
773
|
if (!pa.hash || !pb.hash) return overlap(solidOf(pa), solidOf(pb));
|
|
743
774
|
remembered ||= (() => { try { return JSON.parse(host.readText(OVERLAPS)); } catch { return {}; } })();
|
|
744
775
|
const at = (p) => `${p.hash}@${Array.from(p.m || []).map((x) => Math.round(x * 1e6) / 1e6).join(',')}`;
|
|
745
|
-
const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`crossing+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
|
|
776
|
+
const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`crossing+tracks+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
|
|
746
777
|
if (!(k in remembered)) { remembered[k] = overlap(solidOf(pa), solidOf(pb)); fresh++; }
|
|
747
778
|
return remembered[k];
|
|
748
779
|
}
|
|
@@ -767,6 +798,8 @@ function massFinding(s, f) {
|
|
|
767
798
|
}
|
|
768
799
|
|
|
769
800
|
export function checkAssembly(s) {
|
|
801
|
+
// the screws found in this pose (at(pose) leaves them to be found again): the fasten and slot nut checks read the same
|
|
802
|
+
if (!s.fastened && s.a.fasten?.length && fastening) s = { ...s, fastened: fastening.fastenOf(s, placeItems(s.motion, s.jointValues)) };
|
|
770
803
|
const out = [], f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }), mm = (n) => `${Number(n.toFixed(3))}`;
|
|
771
804
|
// Versions: every pin, from this assembly and its components, against every copy of that object
|
|
772
805
|
const pins = new Map();
|
|
@@ -909,12 +942,30 @@ export function checkAssembly(s) {
|
|
|
909
942
|
// nowhere else: a ring gear resting on its case turns with the planets; a pawl resting on its post walks off it.
|
|
910
943
|
if (s.motion.joints.some((j) => j.type !== 'fixed')) {
|
|
911
944
|
const ids = s.motion.items.map((x) => x[0]), top = (n) => String(n).split(/[.@]/)[0];
|
|
912
|
-
|
|
945
|
+
// (a beam placed by its ends is the frame, held where it is drawn: what is screwed to it is held by it)
|
|
946
|
+
const held = new Set([ids[0], ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]), ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id)]), links = s.fits.filter((x) => x.fastens).map((x) => [top(x.a), top(x.b)]);
|
|
947
|
+
// (a fitting at a beam's end, an end cap pressed into it or a foot screwed into its bore, is held by that beam)
|
|
948
|
+
for (const it of s.a.items || []) { const m = typeof it.at === 'string' && (it.fitting || it.bought) ? /^([\w-]+)\.[ab]$/.exec(it.at.trim()) : null; if (m && s.items.some((x) => x.id === m[1] && x.beam)) links.push([it.id, m[1]]); }
|
|
913
949
|
for (let grew = true; grew;) { grew = false; for (const [a, b] of links) { if (held.has(a) && !held.has(b)) { held.add(b); grew = true; } if (held.has(b) && !held.has(a)) { held.add(a); grew = true; } } }
|
|
914
950
|
const placed = new Set(s.objects.filter((o) => !o.unplaced && o.role !== 'reference').map((o) => top(o.id)));
|
|
915
951
|
const loose = ids.filter((id) => !held.has(id) && placed.has(id));
|
|
916
952
|
if (loose.length) f('warn', `${loose.join(', ')} ${loose.length > 1 ? 'are' : 'is'} placed, but nothing holds ${loose.length > 1 ? 'them' : 'it'}: give ${loose.length > 1 ? 'each' : 'it'} a joint, or fasten it to what it sits on (pins, screws, a press) and say so with a fit that "fastens"`, `${loose.length} loose`, { code: 'assembly.loose', refs: { items: loose } });
|
|
917
953
|
else f('pass', `every part turns or slides on a joint, or is fastened to the ${ids[0]}`, null, { code: 'assembly.held' });
|
|
954
|
+
// A fit that fastens holds two items as one, but only a joint or an anchor moves them: one fastened to a part a
|
|
955
|
+
// joint moves, and placed where it stands, stays behind in every pose and is left out of what that joint carries
|
|
956
|
+
// (one also fastened to what stays, as a servo to its stand with its arm fastened to the horn, is held there)
|
|
957
|
+
const moving = s.motion.joints.filter((j) => !j.at && j.type !== 'fixed'), across = (a, b) => moving.find((jj) => beyond(s.motion, jj, ids.indexOf(a)) !== beyond(s.motion, jj, ids.indexOf(b)));
|
|
958
|
+
const still = new Set([ids[0], ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]), ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id)]), same = links.filter(([a, b]) => ids.includes(a) && ids.includes(b) && !across(a, b));
|
|
959
|
+
for (let grew = true; grew;) { grew = false; for (const [a, b] of same) { if (still.has(a) && !still.has(b)) { still.add(b); grew = true; } if (still.has(b) && !still.has(a)) { still.add(a); grew = true; } } }
|
|
960
|
+
for (const x of s.fits.filter((q) => q.fastens)) {
|
|
961
|
+
const [a, b] = [top(x.a), top(x.b)], ia = ids.indexOf(a), ib = ids.indexOf(b);
|
|
962
|
+
if (ia < 0 || ib < 0) continue;
|
|
963
|
+
const j = across(a, b);
|
|
964
|
+
if (!j || (still.has(a) && still.has(b))) continue;
|
|
965
|
+
const [mover, left] = beyond(s.motion, j, ia) ? [a, b] : [b, a];
|
|
966
|
+
f('warn', `${left} is fastened to ${mover} (a fit that fastens), but only ${mover} moves on ${j.id}: ${left} is placed where it stands, so it stays there in every pose and its mass is left out of what ${j.id} carries (joint.moment). Place ${left} on ${mover} by an anchor or an address ("at": "${mover}.<anchor>")`,
|
|
967
|
+
`${left}: left behind by ${j.id}`, { code: 'assembly.fastened', refs: { items: [left, mover], joint: j.id } });
|
|
968
|
+
}
|
|
918
969
|
}
|
|
919
970
|
// Gears: each mesh's centre distance and contact ratio, said between the two axes (the rest by --sweep)
|
|
920
971
|
for (const g of s.motion.meshes || []) {
|
|
@@ -933,16 +984,27 @@ export function checkAssembly(s) {
|
|
|
933
984
|
}
|
|
934
985
|
boughtFindings(s, f);
|
|
935
986
|
beamFindings(s, f);
|
|
987
|
+
fittingFindings(s, f);
|
|
988
|
+
panelFindings(s, f);
|
|
989
|
+
serviceFindings(s, f);
|
|
990
|
+
guideFindings(s, f);
|
|
991
|
+
if (s.generated) { const m = s.generated, [what, ...more] = frameText(m); f('info', `generated: ${what}; ${more.map((x) => x.trim()).join('; ')}`, null, { code: 'frame.generated', values: { inside: m.inside, outside: m.outside, lengths: m.lengths.map(({ length, count }) => ({ length, count })) }, refs: { kind: m.kind, profile: m.profile, join: m.join.kind, arrangement: m.arrangement, by: m.by } }); }
|
|
992
|
+
joinChecks(s, f);
|
|
993
|
+
slotNutChecks(s, f);
|
|
994
|
+
frameSquareChecks(s, f);
|
|
995
|
+
frameHeatChecks(s, f);
|
|
936
996
|
massFinding(s, f);
|
|
937
997
|
runningChecks(s, f, { axisOf, placeItems, jointValues, mul });
|
|
938
998
|
if (s.wires?.length) wireChecks(s, f, { placeItems, jointValues, mul });
|
|
939
999
|
motorChecks(s, f, { placeItems, jointValues, mul }, materialOf(s.project));
|
|
940
1000
|
powerChecks(s, f);
|
|
941
1001
|
loadChecks(s, f, { placeItems, jointValues, mul });
|
|
1002
|
+
frameChecks(s, f, { placeItems, jointValues, mul });
|
|
1003
|
+
sizeChecks(s, f, { placeItems, jointValues, mul });
|
|
942
1004
|
gripChecks(s, f);
|
|
943
1005
|
gaitChecks(s, f, { jointValues, placeItems, sweepOne: (v) => clashesOf(s.at(v), named) });
|
|
944
1006
|
taskChecks(s, f);
|
|
945
|
-
orderChecks(s, f);
|
|
1007
|
+
orderChecks(s, f, { frame: frameBuild });
|
|
946
1008
|
// Plates print everything: no references
|
|
947
1009
|
if (s.a.kind === 'plate') {
|
|
948
1010
|
const refs = s.objects.filter((o) => o.role === 'reference' && !o.unplaced); // an unplaced item only lends its numbers
|
|
@@ -992,20 +1054,24 @@ export function sweep(s, { joint, steps = 24, progress } = {}) {
|
|
|
992
1054
|
for (const j of free) j.dofs.forEach(([lo, hi], d) => {
|
|
993
1055
|
const unit = DOFS[j.type][d] === 'angle' ? '°' : ' mm', name = `${j.id}${j.dofs.length > 1 ? ` ${'xyz'[d] && j.type === 'ball' ? 'xyz'[d] : DOFS[j.type][d]}` : ''}`;
|
|
994
1056
|
const bad = []; // [value, what]
|
|
995
|
-
|
|
996
|
-
|
|
1057
|
+
// a door with its latch shut: also tried just off shut, finer than a step, so a hit within the first degree is seen
|
|
1058
|
+
const held = (s.panels ?? []).find((p) => p.latch && p.joint === j.id && DOFS[j.type][d] === 'angle'), probe = held ? Math.min(PANEL_CHECK.latch_probe.value, (hi - lo) / steps) : 0;
|
|
1059
|
+
const values = [...Array(steps + 1).keys()].map((i) => lo + ((hi - lo) * i) / steps);
|
|
1060
|
+
if (probe > 0 && probe < (hi - lo) / steps) values.splice(1, 0, lo + probe);
|
|
1061
|
+
for (const [i, v] of values.entries()) {
|
|
1062
|
+
const set = { ...base, [j.id]: base[j.id].map((x, k) => (k === d ? v : x)) };
|
|
997
1063
|
const t = s.at(Object.fromEntries(Object.entries(set).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow)));
|
|
998
1064
|
const what = [...clashesOf(t, isNamed).map(([a, b]) => `${a} hits ${b}`), ...loopGaps(t).filter((l) => !l.ok).map((l) => `${l.label} apart by ${mm(l.gap)} mm`)];
|
|
999
1065
|
if (what.length) bad.push([v, what]);
|
|
1000
|
-
progress?.({ stage: 'sweep', joint: j.id, step: i, steps });
|
|
1066
|
+
progress?.({ stage: 'sweep', joint: j.id, step: Math.min(i, steps), steps });
|
|
1001
1067
|
}
|
|
1002
1068
|
const ranges = []; // runs of steps in a row that collide
|
|
1003
1069
|
for (const [v, what] of bad) { const r = ranges[ranges.length - 1]; if (r && Math.abs(v - r.to - (hi - lo) / steps) < 1e-9) { r.to = v; r.what = [...new Set([...r.what, ...what])]; } else ranges.push({ from: v, to: v, what }); }
|
|
1004
|
-
const span = `${mm(lo)} to ${mm(hi)}${unit}
|
|
1005
|
-
if (!ranges.length) f('pass', `sweep ${name}, ${span} in ${steps} steps: nothing collides`, `${name}: clear ${span}`, { code: 'sweep', values: { from: lo, to: hi, steps }, refs: { joint: name, collisions: [] } });
|
|
1006
|
-
else f('fail', `sweep ${name}, ${span} in ${steps} steps: ${ranges.map((r) => `${r.from === r.to ? `at ${mm(r.from)}` : `${mm(r.from)} to ${mm(r.to)}`}${unit.trim()}: ${r.what.slice(0, 3).join('; ')}${r.what.length > 3 ? `; and ${r.what.length - 3} more` : ''}`).join(' | ')}`,
|
|
1070
|
+
const span = `${mm(lo)} to ${mm(hi)}${unit}`, note = held ? ` (${held.latch} shut over ${held.id}: also tried ${mm(probe)}${unit} off shut)` : '';
|
|
1071
|
+
if (!ranges.length) f('pass', `sweep ${name}, ${span} in ${steps} steps${note}: nothing collides`, `${name}: clear ${span}`, { code: 'sweep', values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) }, refs: { joint: name, collisions: [], ...(held ? { latch: held.latch } : {}) } });
|
|
1072
|
+
else f('fail', `sweep ${name}, ${span} in ${steps} steps${note}: ${ranges.map((r) => `${r.from === r.to ? `at ${mm(r.from)}` : `${mm(r.from)} to ${mm(r.to)}`}${unit.trim()}: ${r.what.slice(0, 3).join('; ')}${r.what.length > 3 ? `; and ${r.what.length - 3} more` : ''}`).join(' | ')}`,
|
|
1007
1073
|
`${name}: collides ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`,
|
|
1008
|
-
{ code: 'sweep', values: { from: lo, to: hi, steps }, refs: { joint: name, collisions: ranges.map((r) => ({ from: r.from, to: r.to, what: r.what })) } });
|
|
1074
|
+
{ code: 'sweep', values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) }, refs: { joint: name, ...(held ? { latch: held.latch } : {}), collisions: ranges.map((r) => ({ from: r.from, to: r.to, what: r.what })) } });
|
|
1009
1075
|
});
|
|
1010
1076
|
saveOverlaps();
|
|
1011
1077
|
return out;
|