@rulecad/cad 0.7.12 → 0.7.25
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 +6 -1
- package/README.md +72 -15
- package/TUTORIAL.md +225 -0
- package/bin/cad.mjs +97 -31
- package/lib/animate.mjs +71 -0
- package/lib/assembly.mjs +31 -5
- package/lib/clone.mjs +150 -0
- package/lib/design.mjs +75 -33
- package/lib/errors.mjs +20 -2
- package/lib/host.mjs +7 -0
- package/lib/jsonedit.mjs +17 -11
- package/lib/layout.mjs +2 -2
- package/lib/links.mjs +23 -7
- package/lib/live-shape.mjs +131 -0
- package/lib/live.mjs +2 -2
- package/lib/optimise.mjs +85 -23
- package/lib/parts.mjs +26 -0
- package/lib/player.mjs +225 -0
- package/lib/preview.mjs +3 -1
- package/lib/rules.mjs +2 -2
- package/lib/sandbox-hooks.mjs +9 -6
- package/lib/sandbox-run.mjs +24 -10
- package/lib/sandbox.mjs +27 -15
- package/lib/schema.mjs +1 -7
- package/lib/workspace.mjs +8 -3
- package/package.json +16 -7
- package/schemas/assembly.schema.json +1 -1
- package/schemas/object.schema.json +1 -1
- package/schemas/problem.schema.json +98 -4
- package/schemas/rules.schema.json +3 -1
package/bin/cad.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import fs from 'node:fs';
|
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { execFileSync } from 'node:child_process';
|
|
6
6
|
import { fmt, loadRuleSet } from '../lib/rules.mjs';
|
|
7
|
-
import { WS, TOOL, paths, config, printerOf } from '../lib/workspace.mjs';
|
|
7
|
+
import { WS, TOOL, paths, config, configError, printerOf } from '../lib/workspace.mjs';
|
|
8
8
|
import { fromKLE } from '@rulecad/keyboard-layout';
|
|
9
9
|
import { target, hasTarget } from '../lib/targets.mjs';
|
|
10
10
|
import { locate, build, pick, lint, readObject, printer, pcbEngine, objectSets } from '../lib/design.mjs';
|
|
@@ -12,13 +12,15 @@ import { git, tags, bump, bigger, newer, compare, snapshot, materialise, files,
|
|
|
12
12
|
import { check } from '@rulecad/printcheck';
|
|
13
13
|
import { preview } from '../lib/preview.mjs';
|
|
14
14
|
import { measure, match } from '../lib/meshcmd.mjs';
|
|
15
|
+
import { cloneBoard } from '../lib/clone.mjs';
|
|
15
16
|
import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, motionData } from '../lib/assembly.mjs';
|
|
16
17
|
import { valuesOf, why } from '../lib/explain.mjs';
|
|
17
|
-
import { errorData } from '../lib/errors.mjs';
|
|
18
|
+
import { errorData, near } from '../lib/errors.mjs';
|
|
18
19
|
import { schemaFindings } from '../lib/schema.mjs';
|
|
19
20
|
import { optimised, readProblem, analysePart, picture, problemFile } from '../lib/optimise.mjs';
|
|
20
21
|
import { evaluate } from '../lib/rules.mjs';
|
|
21
22
|
import { setVariables, addToAssembly, parseValue } from '../lib/edit.mjs';
|
|
23
|
+
import { setAt } from '../lib/jsonedit.mjs';
|
|
22
24
|
import { threemf, slotOf } from '../lib/threemf.mjs';
|
|
23
25
|
import { liveView } from '../lib/live.mjs';
|
|
24
26
|
import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW } from '../lib/links.mjs';
|
|
@@ -39,6 +41,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
39
41
|
|
|
40
42
|
cad new <project>/<object> start a design from the template (makes the project if needed)
|
|
41
43
|
cad import-kle <file> <project>/<name> a keyboard layout from keyboard-layout-editor.com, into layouts/
|
|
44
|
+
cad clone <board.kicad_pcb | GitHub link> <name> a published circuit board into rules/<name>.json, to redraw by rules [--source, --licence]
|
|
42
45
|
cad agents AGENTS.md: how an AI agent should design in this workspace
|
|
43
46
|
cad rules <project>/<object> every variable: value, the rule behind it, its source
|
|
44
47
|
cad values <project>/<object> [names…] the object's variables, resolved [--json]
|
|
@@ -46,7 +49,9 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
46
49
|
cad add fit|joint|item|loop|pose <project>/<assembly> --a … --b … --min … add to an assembly, keeping its layout
|
|
47
50
|
cad why <project>/<object>.<name> what a value reads, down to the rules and their sources [--json] [--depth N]
|
|
48
51
|
cad check <project>/<object> raw numbers in the design, then printability (exit 1 on a failure) [--json: findings as data]
|
|
49
|
-
cad preview <project>/<object>
|
|
52
|
+
cad preview <project>/<object> six views as a PNG in .preview/ (prints the path)
|
|
53
|
+
cad animate <project>/<object> a lamina mechanism's sequence, start to finish, in .preview/: an animated SVG, the
|
|
54
|
+
data (shapes, forces, energies, strains each frame, JSON) and a page that plays it
|
|
50
55
|
cad optimise <project>/<problem> the stiffest layout for a problem in the project's problems/ (name:variant for a
|
|
51
56
|
variant): a picture in .preview/, the result kept for designs [--fresh] [--json]
|
|
52
57
|
[--watch [port]: a live view of it at http://127.0.0.1:8090/, with a stop button]
|
|
@@ -88,15 +93,40 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
88
93
|
--set name=value,name=value change variables that have a tweak range (any command)
|
|
89
94
|
--part <name> only that part (check, preview, export, link): e.g. --part cap
|
|
90
95
|
--explode preview: parts moved apart, so each can be seen
|
|
91
|
-
--trailer "Co-Authored-By: …" added to release commits (for agents)
|
|
96
|
+
--trailer "Co-Authored-By: …" added to release commits (for agents)
|
|
97
|
+
cad --version this tool's version`;
|
|
98
|
+
|
|
99
|
+
// Every command and option there is: a misspelt one is refused by name, not passed over
|
|
100
|
+
const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
|
|
101
|
+
'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'match', 'variants', 'compare', 'help'];
|
|
102
|
+
const OPTIONS = ['all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
|
|
103
|
+
'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
|
|
104
|
+
'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
|
|
105
|
+
'unit', 'rule', 'label', // cad set
|
|
106
|
+
'a', 'b', 'min', 'max', 'poses', 'id', 'type', 'parent', 'child', 'follow', 'value', 'ratio', 'object', 'assembly', 'variant', 'rotate']; // cad add
|
|
107
|
+
// What a command takes, where that isn't <project>/<object>
|
|
108
|
+
const USAGE = { add: 'fit|joint|item|loop|pose <project>/<assembly> --key value …', why: '<project>/<object>.<variable>', set: '<project>/<object> name=value …',
|
|
109
|
+
optimise: '<project>/<problem>', optimize: '<project>/<problem>', history: '<project>[/<object>]', release: '<project>[/<object>] -m "what changed"',
|
|
110
|
+
diff: '<project>/<object> <from> [<to>]', compare: '<project>/<object> <a> <b>', match: '<project>/<object> <model.stl|model.3mf>', clone: '<board.kicad_pcb | GitHub link> <name>' };
|
|
92
111
|
|
|
93
112
|
const args = process.argv.slice(2);
|
|
94
|
-
// --name value, or -m for one-letter names
|
|
95
|
-
|
|
113
|
+
// Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
|
|
114
|
+
// (--sweep and --watch take one or not).
|
|
115
|
+
const FLAGS = ['all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short'];
|
|
116
|
+
const opt = (k) => {
|
|
117
|
+
const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
|
|
118
|
+
if (i < 0) return undefined;
|
|
119
|
+
if (FLAGS.includes(k)) return true;
|
|
120
|
+
if (args[i + 1] && !args[i + 1].startsWith('--')) return args[i + 1];
|
|
121
|
+
if (['sweep', 'watch'].includes(k)) return true;
|
|
122
|
+
throw new Error(`${args[i]} needs a value after it`);
|
|
123
|
+
};
|
|
96
124
|
// The arguments that aren't options or an option's value: cad values keyboard/case depth width --json
|
|
97
|
-
const
|
|
98
|
-
const
|
|
99
|
-
|
|
125
|
+
const takesValue = (a) => a === '-m' || (a.startsWith('--') && !FLAGS.includes(a.slice(2)));
|
|
126
|
+
const positional = () => args.filter((a, i) => !a.startsWith('--') && a !== '-m' && !(i > 0 && takesValue(args[i - 1])));
|
|
127
|
+
// --set name=value,name=value (a value may hold an = of its own)
|
|
128
|
+
const sets = () => Object.fromEntries(String(opt('set') || '').split(',').filter(Boolean).map((p) => { const i = p.indexOf('='); return i < 0 ? [p.trim(), undefined] : [p.slice(0, i).trim(), p.slice(i + 1).trim()]; }));
|
|
129
|
+
const suffix = (set) => Object.entries(set).map(([k, v]) => `-${k}=${v}`).join('').replace(/[^\w.=+-]/g, '_'); // in file names: nothing that could name another folder
|
|
100
130
|
|
|
101
131
|
// --progress: what a long build or sweep is doing, on one line of stderr
|
|
102
132
|
const showProgress = (e) => {
|
|
@@ -116,7 +146,7 @@ const sig = (n) => (Number.isFinite(n) ? String(Number(n.toPrecision(3))) : Stri
|
|
|
116
146
|
const stiffOf = (c) => (c.moment ? c.torsion : c.stiffness);
|
|
117
147
|
const howFar = (c) => (c.moment ? `turns ${sig(c.angle * 180 / Math.PI)}° under ${sig(c.moment / 1000)} N·m, ${sig(c.torsion / 1000 * Math.PI / 180)} N·m a degree` : `moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
|
|
118
148
|
// cad optimise: run a problem (with a progress line), then report it and draw it: a 2D layout as an SVG of its
|
|
119
|
-
// densities, a 3D one as the preview's
|
|
149
|
+
// densities, a 3D one as the preview's views of its surface
|
|
120
150
|
async function optimiseProblem(ref) {
|
|
121
151
|
const [project, name] = String(ref).split('/');
|
|
122
152
|
if (!project || !name) throw new Error('usage: cad optimise <project>/<problem>[:variant]');
|
|
@@ -127,7 +157,9 @@ async function optimiseProblem(ref) {
|
|
|
127
157
|
}
|
|
128
158
|
const live = !opt('json') && process.stderr.isTTY;
|
|
129
159
|
// --watch [port]: the live view, served while it runs (a watched run is always run afresh, so there is something to watch)
|
|
130
|
-
const watch = opt('watch')
|
|
160
|
+
const watch = opt('watch');
|
|
161
|
+
if (watch && watch !== true && !(Number(watch) > 0 && Number(watch) < 65536)) throw new Error(`--watch takes a port number (got "${watch}")`);
|
|
162
|
+
const view = watch ? await liveView({ port: watch === true ? 8090 : Number(watch), title: `cad optimise ${ref}` }) : null;
|
|
131
163
|
if (view) say(`watching at ${view.url}`);
|
|
132
164
|
let r;
|
|
133
165
|
try {
|
|
@@ -140,7 +172,7 @@ async function optimiseProblem(ref) {
|
|
|
140
172
|
if (view) { view.close(`finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, { hold: 10 * 60e3 }); say(`the live view shows the result for ten more minutes (Ctrl-C to stop it)`); }
|
|
141
173
|
const p = await readProblem(project, name), cells = r.dim === 3 ? `${r.grid.nx} × ${r.grid.ny} × ${r.grid.nz}` : `${r.grid.nx} × ${r.grid.ny}`;
|
|
142
174
|
const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => c.moment ? `${c.name} ${sig(c.angle * 180 / Math.PI)}° (${sig(c.torsion / 1000 * Math.PI / 180)} N·m/°)` : `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
|
|
143
|
-
`${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}${r.dropped ? `; ${r.dropped.length} loose ${r.dropped.length === 1 ? 'piece' : 'pieces'} dropped (${sig(r.dropped.reduce((t, v) => t + v, 0))} mm³)` : ''}${r.emptied ? `; ${r.emptied} ${r.emptied === 1 ? 'cell' : 'cells'} that wouldn't print emptied` : ''}`,
|
|
175
|
+
`${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}${r.dropped ? `; ${r.dropped.length} loose ${r.dropped.length === 1 ? 'piece' : 'pieces'} dropped (${sig(r.dropped.reduce((t, v) => t + v, 0))} mm³)` : ''}${r.emptied ? `; ${r.emptied} ${r.emptied === 1 ? 'cell' : 'cells'} that wouldn't print emptied` : ''}${r.cleared ? `; sliced as the printer will, ${r.cleared} ${r.cleared === 1 ? 'cell' : 'cells'} under islands emptied` : ''}`,
|
|
144
176
|
...(r.unsupported > 0.01 ? [`${fmt(r.unsupported * 100)}% of the kept regions has nothing holding it up (at ${r.overhang ? 'the printer\'s overhang limit' : '45°'} or less): give the part more material to stand them on, or keep less`] : [])];
|
|
145
177
|
let out;
|
|
146
178
|
if (r.dim === 3) {
|
|
@@ -155,6 +187,7 @@ async function optimiseProblem(ref) {
|
|
|
155
187
|
if (opt('json')) return console.log(JSON.stringify((({ density, history, mesh, ...x }) => x)(r), null, 2));
|
|
156
188
|
console.log(`${r.title}${r.cached ? ' (cached)' : ` (${fmt(r.seconds)} s)`}`);
|
|
157
189
|
for (const c of r.cases) console.log(` ${c.name}: ${howFar(c)}`);
|
|
190
|
+
if (r.mechanism) console.log(` the output moves ${sig(r.mechanism.travel)} mm its way for ${sig(r.mechanism.input)} mm of push: an advantage of ${sig(r.mechanism.advantage)}`);
|
|
158
191
|
if (r.stress) console.log(` peak stress ${sig(r.stress.peak)} MPa, the limit ${sig(r.stress.limit)} MPa${r.stress.peak > r.stress.limit * 1.02 ? ': over it (raise the volume, ease the limit, or use a smaller cell)' : ''}`);
|
|
159
192
|
if (r.dim === 3) console.log(` ${fmt(r.volume * 100)}% of the space filled: ${fmt(r.solid / 1000)} cm³ (${fmt(r.solid / 1000 * (p.material.density || 0))} g of ${p.material.name})${r.overhang ? `, printable built ${r.overhang}` : ''}`);
|
|
160
193
|
else console.log(` ${fmt(r.volume * 100)}% of the space filled, outline ${fmt(r.area)} mm² (${fmt(r.area * r.thickness / 1000)} cm³ before bosses and holes are made exact)`);
|
|
@@ -243,6 +276,9 @@ async function analyses(b, d, tag) {
|
|
|
243
276
|
values: { stress: c.stress, at: c.stressAt, ...(safety != null ? { safety } : {}), ...(fatigue != null ? { fatigue } : {}), ...(minSafety != null ? { min: minSafety } : {}) }, refs },
|
|
244
277
|
];
|
|
245
278
|
});
|
|
279
|
+
// Members the grid is too coarse for: under four cells thick, a cell's stiffness is a rough figure
|
|
280
|
+
if (r.thin && r.thin.share > 0.05) found.push({ level: 'warn', code: 'fea.coarse', values: { share: r.thin.share, cells: r.thin.cells, cell: r.grid.h }, refs: { problem: a.problem, part: part.name },
|
|
281
|
+
text: `${a.problem}: ${fmt(r.thin.share * 100)}% of the part is in members under ${r.thin.cells} cells (${fmt(r.thin.cells * r.grid.h)} mm) thick, where the stiffness is rough: use a smaller cell (${fmt(r.grid.h / 2)} mm) and see that it settles` });
|
|
246
282
|
const grams = m.density ? ` (${fmt((r.volume / 1000) * m.density)} g of ${m.name})` : '';
|
|
247
283
|
if (a.volume != null) {
|
|
248
284
|
const want = evaluate(a.volume, lookup), tol = a.tolerance ?? 0.01, off = (r.volume - want) / want;
|
|
@@ -265,8 +301,13 @@ async function analyses(b, d, tag) {
|
|
|
265
301
|
}
|
|
266
302
|
|
|
267
303
|
async function main() {
|
|
268
|
-
const [cmd, ref] =
|
|
269
|
-
if (!
|
|
304
|
+
const first = args[0], pos = positional(), [cmd = first, ref] = pos; // names first or options first: cad check --json keyboard/case
|
|
305
|
+
if (!first || ['help', '--help', '-h'].includes(first)) return console.log(HELP);
|
|
306
|
+
if (['--version', '-v', 'version'].includes(first)) return console.log(JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
|
|
307
|
+
if (!COMMANDS.includes(cmd)) { const guess = near(cmd, COMMANDS); throw new Error(`no command "${cmd}"${guess ? ` (did you mean "${guess}"?)` : ''}: cad help lists them`); }
|
|
308
|
+
const odd = args.find((a) => a.startsWith('--') && !OPTIONS.includes(a.slice(2)));
|
|
309
|
+
if (odd) { const guess = near(odd.slice(2), OPTIONS); throw new Error(`no option ${odd}${guess ? ` (did you mean --${guess}?)` : ''}: cad help lists them`); }
|
|
310
|
+
if (configError) throw configError;
|
|
270
311
|
|
|
271
312
|
if (cmd === 'new') {
|
|
272
313
|
const [project, name] = String(ref || '').split('/');
|
|
@@ -294,7 +335,7 @@ async function main() {
|
|
|
294
335
|
return console.log(`wrote ${path.relative(process.cwd(), to) || 'AGENTS.md'}: how an AI agent should design here (CLAUDE.md includes it)`);
|
|
295
336
|
}
|
|
296
337
|
if (cmd === 'import-kle') { // a layout from keyboard-layout-editor.com into a project's layouts/
|
|
297
|
-
const [project, name] = String(
|
|
338
|
+
const [project, name] = String(pos[2] || '').split('/');
|
|
298
339
|
if (!ref || !fs.existsSync(ref) || !project || !/^[a-z][a-z0-9-]*$/.test(name || '')) throw new Error('usage: cad import-kle <layout.json> <project>/<name> (the JSON download, or a file with its Raw data)');
|
|
299
340
|
const { layout, notes } = fromKLE(fs.readFileSync(ref, 'utf8'));
|
|
300
341
|
const to = path.join(paths.project(project), 'layouts', `${name}.json`);
|
|
@@ -305,22 +346,23 @@ async function main() {
|
|
|
305
346
|
for (const n of notes) console.log(` note: ${n}`);
|
|
306
347
|
return;
|
|
307
348
|
}
|
|
349
|
+
if (cmd === 'clone') return cloneBoard(ref, pos[2], { source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), noModels: !!opt('no-models') });
|
|
308
350
|
if (cmd === 'status') return status(ref);
|
|
309
351
|
if (cmd === 'measure') {
|
|
310
352
|
if (!ref) throw new Error('usage: cad measure <model.stl|model.3mf> [--along x] [--at 10,50] [--line 0.6,2.5] [--rules <name>]');
|
|
311
353
|
const list = (k) => (opt(k) && opt(k) !== true ? String(opt(k)).split(k === 'line' ? ';' : ',').filter(Boolean) : []);
|
|
312
354
|
return measure(ref, { along: opt('along'), at: list('at'), line: list('line'), rules: opt('rules'), source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), pictures: !opt('no-pictures') });
|
|
313
355
|
}
|
|
314
|
-
if (!ref) throw new Error(`usage: cad ${cmd} <project>/<object
|
|
356
|
+
if (!ref || (cmd === 'add' && !pos[2])) throw new Error(`usage: cad ${cmd} ${USAGE[cmd] || '<project>/<object>'}`);
|
|
315
357
|
if (cmd === 'release') return ref.includes('/') ? releaseObject(locate(ref)) : opt('all') ? releaseAll(ref) : releaseProject(ref);
|
|
316
358
|
if (cmd === 'variants') return variants(locate(ref));
|
|
317
|
-
if (cmd === 'compare') return compareVariants(locate(ref),
|
|
359
|
+
if (cmd === 'compare') return compareVariants(locate(ref), pos[2], pos[3]);
|
|
318
360
|
if (cmd === 'history') return history(ref);
|
|
319
|
-
if (cmd === 'diff') return diff(locate(ref),
|
|
361
|
+
if (cmd === 'diff') return diff(locate(ref), pos[2], pos[3] || null);
|
|
320
362
|
if (cmd === 'printed') return printed(locate(ref));
|
|
321
363
|
if (cmd === 'why') return explainValue(ref);
|
|
322
364
|
if (cmd === 'set') return editVariables(ref);
|
|
323
|
-
if (cmd === 'add') return editAssembly(
|
|
365
|
+
if (cmd === 'add') return editAssembly(pos[1], pos[2]);
|
|
324
366
|
if (cmd === 'optimise' || cmd === 'optimize') return await optimiseProblem(ref);
|
|
325
367
|
if (isAssembly(ref)) return assembly(cmd, ref);
|
|
326
368
|
const [base, at] = ref.split('@');
|
|
@@ -332,7 +374,7 @@ async function main() {
|
|
|
332
374
|
if (b.circuit && ['check', 'preview', 'export'].includes(cmd)) return board(cmd, d, b, { title, version, tag });
|
|
333
375
|
|
|
334
376
|
if (cmd === 'match') {
|
|
335
|
-
const file =
|
|
377
|
+
const file = pos[2];
|
|
336
378
|
if (!file || file.startsWith('--')) throw new Error(`usage: cad match ${ref} <model.stl|model.3mf> [--tol 0.2] [--place "rz90 t1,2,3"]`);
|
|
337
379
|
const tol = opt('tol') ? Number(opt('tol')) : printer(b, d).fit ?? 0.2;
|
|
338
380
|
const ok = await match(b, d, file, { place: opt('place'), tol, samples: Number(opt('samples')) || 20000, at: opt('at') ? String(opt('at')).split(',') : [], title: `${title} ${version}`, tag, pictures: !opt('no-pictures') });
|
|
@@ -368,6 +410,7 @@ async function main() {
|
|
|
368
410
|
...(b.object.role === 'reference'
|
|
369
411
|
? [{ level: 'pass', text: `a reference (${(await import('@rulecad/printcheck')).bounds(b.triangles).size.map(fmt).join(' × ')} mm), not printed: no print checks`, code: 'print.reference' }]
|
|
370
412
|
: check(b.triangles, printer(b, d), { parts: b.parts })),
|
|
413
|
+
...(b.mechanism?.findings || []), // a lamina mechanism's own: it prints free, stops, holds, clears in every state
|
|
371
414
|
...(await analyses(b, d, tag)),
|
|
372
415
|
], { object: `${d.project}/${d.name}`, title, version, ...(Object.keys(set).length ? { set } : {}), orientation: b.object.orientation, parts: b.parts.map((p) => ({ name: p.name, role: p.role || 'part' })) });
|
|
373
416
|
if (b.object.orientation) say(` orientation: ${b.object.orientation}`);
|
|
@@ -376,6 +419,18 @@ async function main() {
|
|
|
376
419
|
return;
|
|
377
420
|
}
|
|
378
421
|
|
|
422
|
+
if (cmd === 'animate') {
|
|
423
|
+
if (!b.mechanism) throw new Error(`${d.project}/${d.name} isn't a lamina mechanism: cad animate plays the sequence of one made with flexures.lamina()`);
|
|
424
|
+
const out = paths.preview(d.project, `${d.name}${tag}-sequence.svg`);
|
|
425
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
426
|
+
fs.writeFileSync(out, (await import('../lib/animate.mjs')).sequenceSvg(b.mechanism, { title: `${title} ${version}: ${(b.mechanism.sequence || []).join(', ')}` }));
|
|
427
|
+
// and the sequence as data (shapes, forces, energies, strains each frame), with a page that plays it
|
|
428
|
+
const { playerData, playerHtml } = await import('../lib/player.mjs'), data = playerData(b.mechanism, { title, version, object: `${d.project}/${d.name}` });
|
|
429
|
+
const json = paths.preview(d.project, `${d.name}${tag}-sequence.json`), html = paths.preview(d.project, `${d.name}${tag}-player.html`);
|
|
430
|
+
fs.writeFileSync(json, JSON.stringify(data)); fs.writeFileSync(html, playerHtml(data));
|
|
431
|
+
console.log(out); console.log(json); return console.log(html);
|
|
432
|
+
}
|
|
433
|
+
|
|
379
434
|
if (cmd === 'preview') {
|
|
380
435
|
const out = paths.preview(d.project, `${d.name}${tag}${opt('explode') ? '-exploded' : ''}.png`);
|
|
381
436
|
const size = (await import('@rulecad/printcheck')).bounds(b.triangles).size.map((n) => fmt(n)).join(' × ');
|
|
@@ -418,6 +473,7 @@ async function editVariables(ref) {
|
|
|
418
473
|
const pairs = positional().slice(2);
|
|
419
474
|
if (!ref || !pairs.length || pairs.some((p) => !p.includes('='))) throw new Error('usage: cad set <project>/<object> name=value [name=value …] [--unit mm] [--rule "why"] [--label "Label"] [--new]');
|
|
420
475
|
const extra = Object.fromEntries(['unit', 'rule', 'label'].filter((k) => typeof opt(k) === 'string').map((k) => [k, opt(k)]));
|
|
476
|
+
if (pairs.length > 1 && (extra.rule || extra.label)) throw new Error(`--${extra.rule ? 'rule' : 'label'} describes one variable: set ${pairs.map((p) => p.split('=')[0]).join(' and ')} one at a time`);
|
|
421
477
|
const changes = Object.fromEntries(pairs.map((p) => { const i = p.indexOf('='); return [p.slice(0, i).trim(), { value: parseValue(p.slice(i + 1).trim()), ...extra }]; }));
|
|
422
478
|
const r = await setVariables(ref, changes, { create: !!opt('new') });
|
|
423
479
|
if (opt('json')) return console.log(JSON.stringify(r));
|
|
@@ -475,7 +531,7 @@ async function board(cmd, d, b, { title, version, tag }) {
|
|
|
475
531
|
...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
|
|
476
532
|
...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
|
|
477
533
|
raw.length ? { level: 'fail', text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}` } : { level: 'pass', text: 'every measurement is a variable' },
|
|
478
|
-
...(await pcb.checks(b.circuit, b.values, b.matrix)),
|
|
534
|
+
...(await pcb.checks(b.circuit, b.values, b.matrix, b.source)),
|
|
479
535
|
]);
|
|
480
536
|
if (b.object.orientation) console.log(` ${b.object.orientation}`);
|
|
481
537
|
process.exitCode = failed ? 1 : 0;
|
|
@@ -658,8 +714,8 @@ async function releaseObject(d, { batch = false } = {}) {
|
|
|
658
714
|
const message = opt('m');
|
|
659
715
|
if (!message || message === true) throw new Error('say what changed: -m "Wider slot for a looser fit"');
|
|
660
716
|
const object = readObject(d), b = await build(d);
|
|
661
|
-
const raw = lint(fs.readFileSync(d.js, 'utf8')), fails = (b.circuit ? await (await pcbEngine()).checks(b.circuit, b.values, b.matrix) // boards: the board's checks
|
|
662
|
-
: b.object.role === 'reference' ? [] : check(b.triangles, printer(b, d), { parts: b.parts })).filter((r) => r.level === 'fail'); // references aren't printed
|
|
717
|
+
const raw = lint(fs.readFileSync(d.js, 'utf8')), fails = (b.circuit ? await (await pcbEngine()).checks(b.circuit, b.values, b.matrix, b.source) // boards: the board's checks
|
|
718
|
+
: b.object.role === 'reference' ? [] : [...check(b.triangles, printer(b, d), { parts: b.parts }), ...(b.mechanism?.findings || [])]).filter((r) => r.level === 'fail'); // references aren't printed; a mechanism's own checks count
|
|
663
719
|
if (raw.length || fails.length) throw new Error(`fix the check first: ${[...raw.map((r) => `raw number ${r.text} on line ${r.line}`), ...fails.map((f) => f.text)].join('; ')}`);
|
|
664
720
|
let { last, kind, reasons } = await since(d);
|
|
665
721
|
if (!kind) throw new Error(`nothing has changed since ${last.version}`);
|
|
@@ -676,17 +732,25 @@ async function releaseObject(d, { batch = false } = {}) {
|
|
|
676
732
|
if (opt('dry-run')) return;
|
|
677
733
|
const allowed = [...files(d, object), `projects/${d.project}/CHANGELOG.md`, path.relative(WS, printsFile(d))];
|
|
678
734
|
if (!batch) onlyChanged(allowed); // releaseAll checked the whole tree first
|
|
679
|
-
fs.writeFileSync(d.json, fs.readFileSync(d.json, 'utf8')
|
|
735
|
+
fs.writeFileSync(d.json, setAt(fs.readFileSync(d.json, 'utf8'), ['version'], version)); // the object's own version (added, if it had none), nothing else
|
|
680
736
|
const log = changelog(d.dir, `${d.name} ${version} (${kind}), ${today()}`, message, reasons);
|
|
681
737
|
commitAndTag([...files(d, object), log].filter((f) => fs.existsSync(path.join(WS, f))), `${tag}: ${message}`, tag, `${kind}: ${message}${b.circuit ? `\n\nengine: ${engineId()}` : ''}`);
|
|
682
738
|
console.log(`tagged ${tag}${opt('push') ? ' and pushed' : ' (not pushed: --push, or git push --follow-tags)'}`);
|
|
683
739
|
}
|
|
684
740
|
|
|
741
|
+
// A project's project.json, or a plain word that there's no such project (and which there are)
|
|
742
|
+
function projectFile(project) {
|
|
743
|
+
const pj = path.join(paths.project(project), 'project.json');
|
|
744
|
+
if (!fs.existsSync(pj)) { const have = projects(); throw new Error(`no project "${project}"${have.length ? ` (projects: ${have.join(', ')})` : ': cad new <project>/<object> starts one'}`); }
|
|
745
|
+
return pj;
|
|
746
|
+
}
|
|
747
|
+
// The workspace's projects: the folders under projects/ that hold a project.json (not a stray file, such as .DS_Store)
|
|
748
|
+
const projects = () => (fs.existsSync(paths.projects) ? fs.readdirSync(paths.projects).filter((p) => fs.existsSync(path.join(paths.project(p), 'project.json'))).sort() : []);
|
|
749
|
+
|
|
685
750
|
async function releaseProject(project) {
|
|
686
751
|
const message = opt('m');
|
|
687
752
|
if (!message || message === true) throw new Error('say what this release is: -m "First full set"');
|
|
688
|
-
const dir = paths.project(project), pj =
|
|
689
|
-
if (!fs.existsSync(pj)) throw new Error(`no project "${project}"`);
|
|
753
|
+
const dir = paths.project(project), pj = projectFile(project);
|
|
690
754
|
const p = JSON.parse(fs.readFileSync(pj, 'utf8')), manifest = {};
|
|
691
755
|
for (const name of p.objects) {
|
|
692
756
|
const d = locate(`${project}/${name}`), s = await since(d);
|
|
@@ -722,7 +786,7 @@ async function releaseProject(project) {
|
|
|
722
786
|
|
|
723
787
|
// Release every object in a project that changed, then the project: the tree may hold changes only to their files.
|
|
724
788
|
async function releaseAll(project) {
|
|
725
|
-
const pj = JSON.parse(fs.readFileSync(
|
|
789
|
+
const pj = JSON.parse(fs.readFileSync(projectFile(project), 'utf8'));
|
|
726
790
|
const changed = [];
|
|
727
791
|
for (const n of pj.objects) { const d = locate(`${project}/${n}`); if ((await since(d)).kind) changed.push(d); }
|
|
728
792
|
const allowed = new Set([`projects/${project}/project.json`, `projects/${project}/CHANGELOG.md`, `projects/${project}/prints.jsonl`,
|
|
@@ -754,8 +818,9 @@ async function compareVariants(d, a, b) {
|
|
|
754
818
|
}
|
|
755
819
|
|
|
756
820
|
async function status(project) {
|
|
757
|
-
|
|
758
|
-
|
|
821
|
+
if (!project && !projects().length) return console.log(`no projects in ${WS} yet: cad new <project>/<object> starts one`);
|
|
822
|
+
for (const p of project ? [project] : projects()) {
|
|
823
|
+
const pj = JSON.parse(fs.readFileSync(projectFile(p), 'utf8'));
|
|
759
824
|
console.log(`${p}${pj.version ? `@${pj.version}` : ''}`);
|
|
760
825
|
for (const name of pj.objects) {
|
|
761
826
|
const s = await since(locate(`${p}/${name}`));
|
|
@@ -790,7 +855,8 @@ async function diff(d, from, to) {
|
|
|
790
855
|
function printed(d) {
|
|
791
856
|
const result = opt('result');
|
|
792
857
|
if (!['ok', 'failed'].includes(result)) throw new Error('--result ok or --result failed (and --note "what happened")');
|
|
793
|
-
const object = readObject(d),
|
|
858
|
+
const object = readObject(d), released = tags(d.project, d.name).map((t) => t.version), version = opt('version') || released.at(-1) || object.version;
|
|
859
|
+
if (opt('version') && version !== object.version && !released.includes(version)) throw new Error(`${d.name} has no version ${version} (${released.length ? `releases: ${released.join(', ')}` : `unreleased, at ${object.version}`})`);
|
|
794
860
|
const entry = { date: today(), object: d.name, version, ...(opt('set') ? { set: opt('set') } : {}), material: opt('material') || object.material, result, ...(opt('note') ? { note: opt('note') } : {}) };
|
|
795
861
|
fs.appendFileSync(printsFile(d), JSON.stringify(entry) + '\n');
|
|
796
862
|
console.log(`logged in ${path.relative(WS, printsFile(d))}: ${d.name}@${version} ${result}`);
|
|
@@ -798,6 +864,6 @@ function printed(d) {
|
|
|
798
864
|
|
|
799
865
|
main().catch((e) => {
|
|
800
866
|
if (opt('json')) console.log(JSON.stringify({ error: errorData({ ...e, message: e.message, code: e.code, file: e.file && path.relative(WS, e.file) }) }, null, 2));
|
|
801
|
-
else console.error(`${e.message}${e.file ? ` (${path.relative(WS, e.file)}${e.path ? `: ${e.path}` : ''})` : ''}`);
|
|
867
|
+
else console.error(`${e.message}${e.file ? ` (${path.relative(WS, e.file)}${e.line ? `:${e.line}` : ''}${e.path ? `: ${e.path}` : ''})` : ''}`);
|
|
802
868
|
process.exit(1);
|
|
803
869
|
});
|
package/lib/animate.mjs
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// A lamina mechanism's sequence as one animated SVG: the frame drawn once, and each moving part (bodies, and the
|
|
2
|
+
// flexures drawn bent) frame by frame, holding a moment at each state. Self-contained: it plays in any browser, with
|
|
3
|
+
// nothing to install. Frames come from @rulecad/flexures lamina() (followers pushed aside where their drivers meet them).
|
|
4
|
+
const COLOURS = { ground: '#c9ccd1', body: '#2f6fb3', flexure: '#e07a1f' };
|
|
5
|
+
const HOLD = 8; // a state is shown this many frames' time
|
|
6
|
+
const STEP = 0.06; // seconds a frame
|
|
7
|
+
|
|
8
|
+
const fmt = (n) => +n.toFixed(2);
|
|
9
|
+
const pathOf = (outlines) => outlines.map((o) => `M${o.map(([x, y]) => `${fmt(x)} ${fmt(-y)}`).join('L')}Z`).join('');
|
|
10
|
+
const escape = (s) => String(s).replace(/[<>&"]/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' })[c]);
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @param {{ frames: { from: string, to: string, t: number, parts: Record<string, number[][][]> }[], joints: Record<string, object> }} mechanism
|
|
14
|
+
* @param {{ title?: string }} [o]
|
|
15
|
+
* @returns {string} the SVG
|
|
16
|
+
*/
|
|
17
|
+
export function sequenceSvg(mechanism, { title = '' } = {}) {
|
|
18
|
+
const frames = mechanism.frames || [];
|
|
19
|
+
if (!frames.length) throw new Error('the mechanism has no sequence to animate: give its lamina a sequence of states');
|
|
20
|
+
const flexures = new Set(Object.keys(mechanism.joints || {})), kind = (n) => (n === 'ground' ? 'ground' : flexures.has(n) ? 'flexure' : 'body');
|
|
21
|
+
// The view: everything every frame reaches, with a margin and a line for the caption
|
|
22
|
+
let lo = [Infinity, Infinity], hi = [-Infinity, -Infinity];
|
|
23
|
+
for (const fr of frames) for (const outs of Object.values(fr.parts)) for (const o of outs) for (const [x, y] of o) { lo = [Math.min(lo[0], x), Math.min(lo[1], -y)]; hi = [Math.max(hi[0], x), Math.max(hi[1], -y)]; }
|
|
24
|
+
const pad = Math.max(hi[0] - lo[0], hi[1] - lo[1]) * 0.05, caption = pad * 2;
|
|
25
|
+
// The force curves of the steps a hand drives, a chart each, in a row under the drawing
|
|
26
|
+
const charts = (mechanism.curves || []).flatMap((tr) => tr.curve.filter((c) => c.points.length > 1).map((c) => ({ from: tr.from, to: tr.to, ...c })));
|
|
27
|
+
const chartH = charts.length ? (hi[1] - lo[1]) * 0.35 : 0;
|
|
28
|
+
const vb = [lo[0] - pad, lo[1] - pad - caption, hi[0] - lo[0] + 2 * pad, hi[1] - lo[1] + 2 * pad + caption * 2 + (chartH ? chartH + caption * 1.5 : 0)]; // a band above for the key, below for the step and the charts
|
|
29
|
+
// Timing: each frame its share; a state (the first frame of each step, and the last) held longer
|
|
30
|
+
const weights = frames.map((fr, i) => (fr.t === 0 || i === frames.length - 1 ? HOLD : 1)), total = weights.reduce((a, b) => a + b, 0);
|
|
31
|
+
const starts = []; weights.reduce((at, w) => { starts.push(at / total); return at + w; }, 0);
|
|
32
|
+
const dur = `${fmt(total * STEP)}s`;
|
|
33
|
+
const show = (i) => { // visible only during frame i
|
|
34
|
+
const a = fmt(starts[i]), b = fmt(i + 1 < frames.length ? starts[i + 1] : 1);
|
|
35
|
+
const keys = [...new Set([0, a, b, 1])].sort((x, y) => x - y), values = keys.map((k) => (k >= a && k < b ? 'inline' : 'none'));
|
|
36
|
+
if (i === frames.length - 1) values[values.length - 1] = 'inline';
|
|
37
|
+
return `<animate attributeName="display" values="${values.join(';')}" keyTimes="${keys.join(';')}" dur="${dur}" calcMode="discrete" repeatCount="indefinite"/>`;
|
|
38
|
+
};
|
|
39
|
+
const ground = frames[0].parts.ground ? `<path d="${pathOf(frames[0].parts.ground)}" fill="${COLOURS.ground}" fill-rule="evenodd"/>` : '';
|
|
40
|
+
const size = fmt(caption * 0.45), textY = fmt(hi[1] + pad + caption * 0.65), keyY = fmt(vb[1] + caption * 0.65);
|
|
41
|
+
// Each chart: its box, the curve, and where frame i sits on it (if frame i is in its step)
|
|
42
|
+
const chartTop = hi[1] + pad + caption * 1.5, cw = vb[2] / Math.max(1, charts.length), inner = (k) => ({ x0: vb[0] + k * cw + pad * 1.5, x1: vb[0] + (k + 1) * cw - pad * 0.5, y0: chartTop + caption * 0.6, y1: chartTop + chartH });
|
|
43
|
+
const scaled = charts.map((c, k) => {
|
|
44
|
+
const b = inner(k), xs = c.points.map(([x]) => Math.abs(x)), fs = c.points.map(([, F]) => F), xm = Math.max(1e-9, ...xs), fmin = Math.min(0, ...fs), fmax = Math.max(1e-9, ...fs);
|
|
45
|
+
const at = ([x, F]) => [b.x0 + (Math.abs(x) / xm) * (b.x1 - b.x0), b.y1 - ((F - fmin) / (fmax - fmin)) * (b.y1 - b.y0)];
|
|
46
|
+
return { ...c, b, at, fmax, xm };
|
|
47
|
+
});
|
|
48
|
+
const chartArt = scaled.map((c) => {
|
|
49
|
+
const pts = c.points.map(c.at), zero = c.at([0, 0])[1];
|
|
50
|
+
const small = fmt(Math.min(size * 0.6, (c.b.x1 - c.b.x0) / 22)); // two short lines, sized to fit the chart's width
|
|
51
|
+
return `<g font-family="system-ui, sans-serif" fill="#555"><text x="${fmt(c.b.x0)}" y="${fmt(c.b.y0 - caption * 0.45)}" font-size="${small}">${escape(`${c.from} to ${c.to}, ${c.joint}`)}</text><text x="${fmt(c.b.x0)}" y="${fmt(c.b.y0 - caption * 0.1)}" font-size="${small}">${escape(`up to ${c.fmax.toFixed(1)} N over ${c.xm.toFixed(1)} mm`)}</text>
|
|
52
|
+
<line x1="${fmt(c.b.x0)}" y1="${fmt(zero)}" x2="${fmt(c.b.x1)}" y2="${fmt(zero)}" stroke="#ccc" stroke-width="${fmt(size * 0.04)}"/><line x1="${fmt(c.b.x0)}" y1="${fmt(c.b.y0)}" x2="${fmt(c.b.x0)}" y2="${fmt(c.b.y1)}" stroke="#ccc" stroke-width="${fmt(size * 0.04)}"/>
|
|
53
|
+
<polyline points="${pts.map(([x, y]) => `${fmt(x)},${fmt(y)}`).join(' ')}" fill="none" stroke="#2f6fb3" stroke-width="${fmt(size * 0.08)}"/></g>`;
|
|
54
|
+
}).join('\n');
|
|
55
|
+
const markerOf = (fr) => scaled.filter((c) => c.from === fr.from && c.to === fr.to).map((c) => { const p = c.at(c.points[Math.min(c.points.length - 1, Math.round(fr.t * (c.points.length - 1)))]); return `<circle cx="${fmt(p[0])}" cy="${fmt(p[1])}" r="${fmt(size * 0.25)}" fill="#e07a1f"/>`; }).join('');
|
|
56
|
+
const body = frames.map((fr, i) => {
|
|
57
|
+
const label = fr.label || (fr.t === 0 && fr.from === fr.to ? fr.from : fr.t === 0 ? fr.from : `${fr.from} to ${fr.to}`);
|
|
58
|
+
const shapes = Object.entries(fr.parts).filter(([n]) => n !== 'ground').map(([n, o]) => `<path d="${pathOf(o)}" fill="${COLOURS[kind(n)]}" fill-rule="evenodd"/>`).join('');
|
|
59
|
+
return `<g display="${i ? 'none' : 'inline'}">${show(i)}${shapes}${markerOf(fr)}<text x="${fmt(vb[0] + pad)}" y="${textY}" font-size="${size}" font-family="system-ui, sans-serif" fill="#333">${escape(label)}</text></g>`;
|
|
60
|
+
}).join('\n');
|
|
61
|
+
const key = Object.entries(COLOURS).map(([k, c], i) => `<rect x="${fmt(vb[0] + pad + i * size * 5)}" y="${fmt(keyY - size * 0.8)}" width="${size}" height="${size}" fill="${c}"/><text x="${fmt(vb[0] + pad + i * size * 5 + size * 1.3)}" y="${keyY}" font-size="${fmt(size * 0.8)}" font-family="system-ui, sans-serif" fill="#555">${{ ground: 'frame', body: 'moves', flexure: 'bends' }[k]}</text>`).join('');
|
|
62
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${vb.map(fmt).join(' ')}" width="900">
|
|
63
|
+
<title>${escape(title)}</title>
|
|
64
|
+
<rect x="${fmt(vb[0])}" y="${fmt(vb[1])}" width="${fmt(vb[2])}" height="${fmt(vb[3])}" fill="#fff"/>
|
|
65
|
+
${ground}
|
|
66
|
+
${body}
|
|
67
|
+
${chartArt}
|
|
68
|
+
${key}
|
|
69
|
+
</svg>
|
|
70
|
+
`;
|
|
71
|
+
}
|
package/lib/assembly.mjs
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
// { "holes": "pcb.board", "into": "case.body", "depth": "m2.insert_length", "label": "Screws find their inserts" }
|
|
17
17
|
// The path must be clear for depth mm (it lands in a hole) and solid within "ring" mm of it (default: the hole's
|
|
18
18
|
// diameter) half way down, so the screw has something to grip. "direction": "up" for screws from below.
|
|
19
|
-
import { host } from './host.mjs';
|
|
19
|
+
import { host, readJson } from './host.mjs';
|
|
20
20
|
import fs from 'node:fs';
|
|
21
21
|
import crypto from 'node:crypto';
|
|
22
22
|
import path from 'node:path';
|
|
@@ -56,9 +56,16 @@ export { satisfies }; // from @rulecad/versions
|
|
|
56
56
|
// overrides: { itemId: { variable: value } }, set on this assembly's items by the assembly that uses it.
|
|
57
57
|
// opts: { mirror: true } builds each object with its mirror settings (cad show).
|
|
58
58
|
export async function buildAssembly(ref, stack = [], overrides = {}, opts = {}) {
|
|
59
|
+
const outer = overrides;
|
|
59
60
|
const [project, name] = ref.split('/');
|
|
60
61
|
if (stack.includes(ref)) throw new Error(`assembly ${ref} contains itself (${[...stack, ref].join(' → ')})`);
|
|
61
|
-
const a =
|
|
62
|
+
const a = readJson(assemblyPath(ref));
|
|
63
|
+
// A pose may set items' variables as well as joints ("cocked": { "run": -30, "action.travel": 25 }): a flexure bent
|
|
64
|
+
// as the pose bends it, while the part itself is printed as drawn. The pose being built sets them on its items.
|
|
65
|
+
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; };
|
|
66
|
+
const builtPose = opts.pose ?? a.pose ?? Object.keys(a.poses || {})[0];
|
|
67
|
+
const ownSets = typeof builtPose === 'string' ? itemSets(builtPose) : {};
|
|
68
|
+
overrides = { ...overrides };
|
|
62
69
|
const printer = printerOf(project);
|
|
63
70
|
if (a.kind === 'plate' && !(a.uses || []).includes(printer)) a.uses = [...(a.uses || []), printer]; // a plate is checked as a print
|
|
64
71
|
const values = Object.fromEntries((a.uses || []).map((u) => { const s = loadRuleSet(u); return [u, Object.fromEntries(Object.entries(s.rules).map(([k, r]) => [k, r.value]))]; }));
|
|
@@ -86,7 +93,20 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
86
93
|
// from: inputs worked out from items built before this one ({ "usb_y": "board.pcb.pico_y" }): numbers, in this
|
|
87
94
|
// assembly's names, so a part can take a value only another part knows once it's built
|
|
88
95
|
const from = Object.fromEntries(Object.entries(it.from || {}).map(([k, x]) => [k, num(x)]));
|
|
89
|
-
|
|
96
|
+
// The pose's settings for this item: expressions in the assembly's names (launcher.travel), which may name the item's
|
|
97
|
+
// own variables (magazine.preload: the item is built once as drawn to read them), or a choice as it is
|
|
98
|
+
const base = { ...(it.set || {}), ...from, ...(overrides[it.id] || {}), ...(it.assembly ? {} : extra) };
|
|
99
|
+
let own = null;
|
|
100
|
+
const ownValue = async (x) => {
|
|
101
|
+
if (typeof x !== 'string') return x;
|
|
102
|
+
try { return num(x); } catch {}
|
|
103
|
+
if (!it.object || !new RegExp(`\\b${it.id}\\.`).test(x)) return x;
|
|
104
|
+
if (!own) { const [r, named] = String(it.object).split(':'), [objName, pin] = r.split('@'), d = locate(`${project}/${objName}`); own = (await build({ ...(pin ? materialise(d, pin) : d), ...((named || it.variant) ? { variant: named || it.variant } : {}) }, base, opts)).values; }
|
|
105
|
+
return evaluate(x, (n) => { if (n.startsWith(`${it.id}.`)) { const v = own[n.slice(it.id.length + 1)]; if (typeof v === 'number') return v; } return lookup(n); });
|
|
106
|
+
};
|
|
107
|
+
const posed = {};
|
|
108
|
+
for (const [k, x] of Object.entries(ownSets[it.id] || {})) posed[k] = await ownValue(x);
|
|
109
|
+
const set = { ...(it.set || {}), ...from, ...posed, ...(overrides[it.id] || {}), ...(it.assembly ? {} : extra) };
|
|
90
110
|
// Built for the mirror, an object's mirror settings win (no legends), so copies that differ only there are one shape
|
|
91
111
|
if (opts.mirror && it.object) for (const k of Object.keys(readObject(locate(`${project}/${String(it.object).split(/[:@]/)[0]}`)).mirror || {})) delete set[k];
|
|
92
112
|
const sub = it.assembly ? extra : {}; // a component's values go to its items: { cap: { units: 1.5 } }
|
|
@@ -221,7 +241,11 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
221
241
|
for (const id of copies) { const swap = (n) => (n === star ? at(id, n) : n); fits.push({ ...x, a: swap(x.a), b: swap(x.b), num }); }
|
|
222
242
|
}
|
|
223
243
|
// at(pose): the same assembly in another pose (a name, or { joint: values }), nothing built again
|
|
244
|
+
const same = (x, y) => JSON.stringify(x) === JSON.stringify(y);
|
|
245
|
+
const others = {};
|
|
246
|
+
if (!opts.onePose) for (const n of Object.keys(a.poses || {})) if (n !== builtPose && !same(itemSets(n), ownSets)) others[n] = await buildAssembly(ref, stack, outer, { ...opts, pose: n, onePose: true });
|
|
224
247
|
const at = (p) => {
|
|
248
|
+
if (typeof p === 'string' && others[p]) return others[p];
|
|
225
249
|
const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
|
|
226
250
|
return { ...s, parts: moved, pose: typeof p === 'string' ? p : null, jointValues: v, polygons: moved.flatMap((x) => x.polygons), triangles: moved.flatMap((x) => x.triangles) };
|
|
227
251
|
};
|
|
@@ -247,7 +271,9 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
247
271
|
// another's values (times "ratio", plus "offset"): the second hinge of a pair, gears. Items joined in a ring (two links
|
|
248
272
|
// between the same two parts) can't all be joints: join the ring's last pair with "loops" instead, which the check
|
|
249
273
|
// measures in every pose: [{ "a": "link_l.top", "b": "mount_l.axis", "label": "Left pivot lines up" }].
|
|
250
|
-
// "poses": { "open": { "hinge": 90 } } names sets of values, "pose" the one shown (default: the first);
|
|
274
|
+
// "poses": { "open": { "hinge": 90 } } names sets of values, "pose" the one shown (default: the first); a pose can set an
|
|
275
|
+
// item's variables too ("cocked": { "run": -30, "action.travel": 25 }), so a flexure is drawn bent in that pose and
|
|
276
|
+
// straight as printed (each such pose is built on its own; at(pose) returns it); check checks
|
|
251
277
|
// every pose, and --sweep moves each joint through its range, looking for parts that collide.
|
|
252
278
|
const rows = (m) => [m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14]]; // JSCAD's mat4 is column-major
|
|
253
279
|
const toMat4 = (r) => [r[0], r[4], r[8], 0, r[1], r[5], r[9], 0, r[2], r[6], r[10], 0, r[3], r[7], r[11], 1];
|
|
@@ -321,7 +347,7 @@ function motionOf(a, placed, num, ref) {
|
|
|
321
347
|
// A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
|
|
322
348
|
return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
|
|
323
349
|
});
|
|
324
|
-
const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).map(([id, v]) => {
|
|
350
|
+
const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).filter(([id]) => !id.includes('.')).map(([id, v]) => {
|
|
325
351
|
if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
|
|
326
352
|
return [id, Array.isArray(v) ? v.map(num) : num(v)];
|
|
327
353
|
}))]));
|