@rulecad/cad 0.5.1 → 0.7.0

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 CHANGED
@@ -80,6 +80,18 @@ variable says which rule it comes from. Follow these steps; they're what makes a
80
80
  - Join pins with `nets` (`GND: ['U1.GND', 'J1.GND']`) and let the autorouter draw them; `cad check` runs the fab's
81
81
  design rules. Look at the copper preview: connectors should face the edge their plug comes from.
82
82
 
83
+ ## Optimised parts
84
+ - For a flat part that carries load (a lever, a bracket, a pedal arm), describe it as a problem in `problems/`: the
85
+ space it may fill, the bosses to keep, the holes to avoid, the supports and loads (in newtons, each in a case), the
86
+ material's rule set. `npx cad optimise <project>/<problem>` and **look at the picture** in `.preview/`.
87
+ - A design reads the result through a `problem` variable and builds it with `v.shapes.optimisedOutline(...)`. Add an
88
+ `analysis` to the object so `cad check` reports its stiffness; report those numbers with their load and material.
89
+ - Solid parts (brackets, joints) are 3D problems: regions with a z, a named part as the space if it helps. Set
90
+ `"overhang"` to the way up it will print, so the result needs no supports, and give horizontal bosses and holes a
91
+ `teardrop`. Build with `v.shapes.optimisedSolid(...)` and `"engine": "manifold"`; look at the four views.
92
+ - Say plainly that the analysis is coarse and the material values are data-sheet figures: anything that could hurt
93
+ someone if it broke needs testing, not just a check.
94
+
83
95
  ## Talking to the person
84
96
  - Give links as one labelled line (`npx cad link <project>/<object> --md`), never a raw URL. If it says
85
97
  "(not a release)", say so. If it says the link is too long for chat, don't paste it: tell the person, and offer
package/README.md CHANGED
@@ -329,6 +329,90 @@ then y, then z, as `rotate` does.
329
329
  and a quick look for parts pushed into each other when you let a slider go. The quick look can miss parts that cross
330
330
  without a corner going in, so `--sweep` is the real check.
331
331
 
332
+ ## Optimised parts
333
+
334
+ `cad optimise` finds the stiffest layout of a flat part: where to put a fixed amount of material so the part bends
335
+ least under its loads (topology optimisation, by @rulecad/topopt). A problem is a file in the project's `problems/`,
336
+ with numbers as expressions like an object's (schema: `schemas/problem.schema.json`):
337
+
338
+ ```json
339
+ {
340
+ "title": "A lever",
341
+ "uses": ["m5", "x1c"],
342
+ "material": "pla",
343
+ "thickness": 6, "cell": 1, "volume": 0.5, "filter": 2.5,
344
+ "space": { "at": [60, 0], "size": [140, 40] },
345
+ "keep": [{ "at": [0, 0], "r": 6 }, { "at": [120, 0], "r": 5 }],
346
+ "avoid": [{ "at": [0, 0], "r": "m5.clearance / 2" }, { "at": [120, 0], "r": 2.3 }],
347
+ "supports": [{ "at": [0, 0], "r": "m5.clearance / 2" }],
348
+ "loads": [{ "at": [120, 0], "r": 2.3, "force": [0, -20], "case": "down" }]
349
+ }
350
+ ```
351
+
352
+ - **The space** is where material may go (a circle `r`, a rectangle `size`, or a polygon `points`, in mm). **Keep**
353
+ regions stay solid (bosses round bolts), **avoid** regions stay empty (the holes, clearances).
354
+ - **Supports** hold the material within `r` of a point (a bolt's hole); **loads** push on it, in newtons, each in a load
355
+ case. Cases are optimised together, each by its weight in `cases` (0: analysed, not optimised for).
356
+ - **The material** is a rule set with `modulus` (MPa) and `poisson`: `pla`, `petg`, `al6061`, `al7075`, `s275`,
357
+ `ss304`, `ti64` come with rulecad. Printed values vary: measure yours.
358
+ - **Settings:** `volume`, the share of the space to fill; `cell`, the grid (smaller is finer and slower: a 140 × 40
359
+ grid takes about half a minute); `filter`, about the thinnest member, in mm.
360
+ - **Variants**, picked as `name:variant`, set variables that have a tweak range, as an object's do.
361
+
362
+ `cad optimise <project>/<problem>` runs it, reports how far each load case moves its load and the stiffness that
363
+ gives, and draws the layout in `.preview/`. The result is kept, keyed by everything it's made from, so it's only
364
+ worked out again when something it depends on changes.
365
+
366
+ A design uses it through a variable of type `problem`, which picks a problem by name:
367
+
368
+ ```json
369
+ "problem": { "type": "problem", "value": "lever", "choice": ["lever", "lever:both"] }
370
+ ```
371
+
372
+ ```js
373
+ export function main (v) {
374
+ return extrudeLinear({ height: v.thickness }, v.shapes.optimisedOutline(v.problems[v.problem]))
375
+ }
376
+ ```
377
+
378
+ `optimisedOutline` gives the outline as a 2D shape, its keep regions added and avoid regions cut exactly, so bolt
379
+ holes come out true.
380
+
381
+ ### Solid parts (3D)
382
+
383
+ A problem whose regions have a z is solid. It has no thickness, and takes more kinds of region:
384
+ - **A box:** `size`.
385
+ - **A cylinder:** `r`, `length` and `axis`. Along x or y it can be a teardrop: `"teardrop": "-z"` for a boss,
386
+ `"+z"` for a hole. It gets a 45° point, so it prints.
387
+ - **A ball:** `r`.
388
+ - **A named part of another design in the project:** `{ "part": "envelope.body" }`.
389
+
390
+ Supports and loads can be any region; a force has x, y and z. `"overhang": "+z"` keeps only material that prints
391
+ without supports standing that way up (a variable holding `"+z"` or `"none"` works too, so a variant can switch it).
392
+
393
+ `cad optimise` draws the result's four views in `.preview/`. A design builds the result with
394
+ `v.shapes.optimisedSolid(v.problems[v.problem], { ops: v.ops })`, which adds the keep regions and cuts the avoid
395
+ regions exactly. The surface is a big mesh, so set the object's `"engine": "manifold"`. An `analysis` of a solid part
396
+ voxelises it on the problem's grid.
397
+
398
+ Grids in 3D are solved by multigrid. A 16 × 16 × 40 grid (about 10,000 cubes) takes a second or two a step, so a whole
399
+ optimisation takes a few minutes. The result is kept, so it's worked out once.
400
+
401
+ ### Analysis
402
+
403
+ Any flat part, optimised or not, can be checked under a problem's supports and loads. An object's `analysis` names
404
+ the problem, and optionally a limit:
405
+
406
+ ```json
407
+ "analysis": [{ "problem": "lever", "max_deflection": 0.5, "volume": "target", "tolerance": 0.01 }]
408
+ ```
409
+
410
+ `cad check` then reports, for each load case, how far the part moves its load, its stiffness (N/mm) and its peak
411
+ stress against the material's strength, and the part's volume and weight. With `max_deflection` a case that moves
412
+ further fails; with `volume` a part whose volume is further than `tolerance` (a share) from it fails. A picture goes in
413
+ `.preview/`. The analysis is coarse: it's a design aid, not engineering sign-off. A part that could hurt someone if
414
+ it failed needs testing.
415
+
332
416
  ## Boards
333
417
 
334
418
  A circuit board is an object whose .json says `"engine": "pcb"`. Its `main(v)` returns a
package/bin/cad.mjs CHANGED
@@ -16,6 +16,8 @@ import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, motionData } f
16
16
  import { valuesOf, why } from '../lib/explain.mjs';
17
17
  import { errorData } from '../lib/errors.mjs';
18
18
  import { schemaFindings } from '../lib/schema.mjs';
19
+ import { optimised, readProblem, analysePart, picture, problemFile } from '../lib/optimise.mjs';
20
+ import { evaluate } from '../lib/rules.mjs';
19
21
  import { setVariables, addToAssembly, parseValue } from '../lib/edit.mjs';
20
22
  import { threemf, slotOf } from '../lib/threemf.mjs';
21
23
  import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW } from '../lib/links.mjs';
@@ -44,6 +46,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
44
46
  cad why <project>/<object>.<name> what a value reads, down to the rules and their sources [--json] [--depth N]
45
47
  cad check <project>/<object> raw numbers in the design, then printability (exit 1 on a failure) [--json: findings as data]
46
48
  cad preview <project>/<object> four views as a PNG in .preview/ (prints the path)
49
+ cad optimise <project>/<problem> the stiffest layout for a problem in the project's problems/ (name:variant for a
50
+ variant): a picture in .preview/, the result kept for designs [--fresh] [--json]
47
51
  cad export <project>/<object> a 3MF for Bambu Studio in exports/ [--open: open it in Bambu Studio]
48
52
  cad show <project>/<object> the model on display through your show target, with its rules [--ttl 10m]
49
53
  cad link <project>/<object> links to open the model in a browser, and to download its STL or 3MF
@@ -105,6 +109,72 @@ function report(findings, about = {}) {
105
109
  }
106
110
  const say = (...a) => { if (!opt('json')) console.log(...a); }; // text output that --json leaves out
107
111
 
112
+ const sig = (n) => (Number.isFinite(n) ? String(Number(n.toPrecision(3))) : String(n)); // three significant figures
113
+ // cad optimise: run a problem (with a progress line), then report it and draw it: a 2D layout as an SVG of its
114
+ // densities, a 3D one as the preview's four views of its surface
115
+ async function optimiseProblem(ref) {
116
+ const [project, name] = String(ref).split('/');
117
+ if (!project || !name) throw new Error('usage: cad optimise <project>/<problem>[:variant]');
118
+ const file = problemFile(project, name.split(':')[0]);
119
+ if (fs.existsSync(file)) {
120
+ const bad = schemaFindings(JSON.parse(fs.readFileSync(file, 'utf8')), 'problem', path.relative(WS, file));
121
+ if (bad.length) { report(bad); process.exitCode = 1; return; }
122
+ }
123
+ const live = !opt('json') && process.stderr.isTTY;
124
+ const r = await optimised(project, name, { fresh: !!opt('fresh'), onStep: (s) => live && process.stderr.write(`\r\x1b[Kstep ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm change ${s.change.toFixed(3)} sharpness ${s.beta}`) });
125
+ if (live) process.stderr.write('\r\x1b[K');
126
+ 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}`;
127
+ const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
128
+ `${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}` : ''}`];
129
+ let out;
130
+ if (r.dim === 3) {
131
+ out = paths.preview(project, `${name.replace(':', '-')}-optimised.png`);
132
+ const triangles = r.mesh.faces.map((f) => f.map((i) => r.mesh.vertices[i]));
133
+ await preview([{ name: 'body', label: r.title, triangles }], { title: r.title, meta: lines.join(' · '), out });
134
+ } else {
135
+ out = paths.preview(project, `${name.replace(':', '-')}-optimised.svg`);
136
+ fs.mkdirSync(path.dirname(out), { recursive: true });
137
+ fs.writeFileSync(out, picture(r, { title: r.title, lines }));
138
+ }
139
+ if (opt('json')) return console.log(JSON.stringify((({ density, history, mesh, ...x }) => x)(r), null, 2));
140
+ console.log(`${r.title}${r.cached ? ' (cached)' : ` (${fmt(r.seconds)} s)`}`);
141
+ for (const c of r.cases) console.log(` ${c.name}: moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
142
+ 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}` : ''}`);
143
+ 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)`);
144
+ console.log(` ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? ', settled' : ': stopped before it settled (raise steps)'}`);
145
+ console.log(out);
146
+ }
147
+
148
+ // An object's analyses for cad check: each problem's load cases on the part, and its volume against a target
149
+ async function analyses(b, d, tag) {
150
+ const lookup = (n) => { const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), b.values); if (typeof v !== 'number') throw new Error(`analysis: "${n}" isn't a number`); return v; };
151
+ const all = [];
152
+ for (const a of b.object.analysis || []) all.push(...await (async () => {
153
+ const part = a.part ? b.parts.find((p) => p.name === a.part) : b.parts.find((p) => p.role !== 'support');
154
+ if (!part) return [{ level: 'fail', text: `analysis: no part "${a.part}"`, code: 'fea.part' }];
155
+ const r = await analysePart(part.triangles, d.project, a.problem), m = r.material, limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
156
+ let out = null;
157
+ if (r.dim !== 3) { // a flat part's picture: its cells as analysed, with the supports and loads
158
+ out = paths.preview(d.project, `${d.name}${tag}-analysis-${a.problem.replace(':', '-')}.svg`);
159
+ fs.mkdirSync(path.dirname(out), { recursive: true });
160
+ fs.writeFileSync(out, picture({ ...r, ...(await readProblem(d.project, a.problem)).problem }, { title: `${b.object.title || d.name}: ${a.problem}`, lines: r.cases.map((c) => `${c.name}: ${sig(c.deflection)} mm, ${sig(c.stiffness)} N/mm, peak stress ${sig(c.stress)} MPa`) }));
161
+ }
162
+ const found = r.cases.map((c) => {
163
+ const safety = m.strength ? `, peak stress ${sig(c.stress)} MPa (${sig(m.strength / c.stress)}× under ${m.name}'s strength; coarse)` : '';
164
+ const text = `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm${safety}`;
165
+ const values = { deflection: c.deflection, force: c.force, stiffness: c.stiffness, stress: c.stress, ...(limit != null ? { limit } : {}) };
166
+ return { level: limit == null ? 'info' : c.deflection <= limit ? 'pass' : 'fail', text: limit == null ? text : `${text} (at most ${fmt(limit)})`, code: 'fea.deflection', values, refs: { problem: a.problem, part: part.name, ...(out ? { picture: path.relative(WS, out) } : {}) } };
167
+ });
168
+ const grams = m.density ? ` (${fmt((r.volume / 1000) * m.density)} g of ${m.name})` : '';
169
+ if (a.volume != null) {
170
+ const want = evaluate(a.volume, lookup), tol = a.tolerance ?? 0.01, off = (r.volume - want) / want;
171
+ found.push({ level: Math.abs(off) <= tol ? 'pass' : 'fail', text: `volume ${fmt(r.volume)} mm³${grams}: ${off >= 0 ? '+' : ''}${fmt(off * 100)}% from ${fmt(want)} (within ${fmt(tol * 100)}%)`, code: 'fea.volume', values: { volume: r.volume, target: want, off } });
172
+ } else found.push({ level: 'info', text: `volume ${fmt(r.volume)} mm³${grams}`, code: 'fea.volume', values: { volume: r.volume } });
173
+ return found;
174
+ })());
175
+ return all;
176
+ }
177
+
108
178
  async function main() {
109
179
  const [cmd, ref] = args;
110
180
  if (!cmd || cmd === 'help') return console.log(HELP);
@@ -162,6 +232,7 @@ async function main() {
162
232
  if (cmd === 'why') return explainValue(ref);
163
233
  if (cmd === 'set') return editVariables(ref);
164
234
  if (cmd === 'add') return editAssembly(args[1], args[2]);
235
+ if (cmd === 'optimise' || cmd === 'optimize') return await optimiseProblem(ref);
165
236
  if (isAssembly(ref)) return assembly(cmd, ref);
166
237
  const [base, at] = ref.split('@');
167
238
  const d = at ? materialise(locate(base), at) : locate(ref), set = sets();
@@ -197,7 +268,9 @@ async function main() {
197
268
  const raw = lint(fs.readFileSync(d.js, 'utf8')), file = path.relative(WS, d.js);
198
269
  // The files first: the object's JSON, and the workspace's own rule sets it uses, against their schemas
199
270
  const own = (f) => path.relative(WS, f), ruleFiles = (b.object.uses || []).filter((u) => !u.includes('/')).map((u) => path.join(WS, 'rules', `${u}.json`)).filter((f) => fs.existsSync(f));
200
- const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f)))];
271
+ const problemFiles = [...new Set([...Object.values(b.object.variables || {}).filter((v) => v.type === 'problem').flatMap((v) => v.choice || [v.value]), ...(b.object.analysis || []).map((a) => a.problem)].map((n) => problemFile(d.project, String(n).split(':')[0])))].filter((f) => fs.existsSync(f));
272
+ const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f))),
273
+ ...problemFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'problem', own(f)))];
201
274
  const failed = report([
202
275
  ...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
203
276
  ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
@@ -206,6 +279,7 @@ async function main() {
206
279
  ...(b.object.role === 'reference'
207
280
  ? [{ 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' }]
208
281
  : check(b.triangles, printer(b, d), { parts: b.parts })),
282
+ ...(await analyses(b, d, tag)),
209
283
  ], { 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' })) });
210
284
  if (b.object.orientation) say(` orientation: ${b.object.orientation}`);
211
285
  if (b.parts.length > 1) say(` parts: ${b.parts.map((p) => `${p.name}${p.role === 'support' ? ' (support)' : ''}`).join(', ')}`);
@@ -305,7 +379,9 @@ async function board(cmd, d, b, { title, version, tag }) {
305
379
  const raw = lint(fs.readFileSync(d.js, 'utf8'));
306
380
  // The files first: the object's JSON, and the workspace's own rule sets it uses, against their schemas
307
381
  const own = (f) => path.relative(WS, f), ruleFiles = (b.object.uses || []).filter((u) => !u.includes('/')).map((u) => path.join(WS, 'rules', `${u}.json`)).filter((f) => fs.existsSync(f));
308
- const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f)))];
382
+ const problemFiles = [...new Set([...Object.values(b.object.variables || {}).filter((v) => v.type === 'problem').flatMap((v) => v.choice || [v.value]), ...(b.object.analysis || []).map((a) => a.problem)].map((n) => problemFile(d.project, String(n).split(':')[0])))].filter((f) => fs.existsSync(f));
383
+ const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f))),
384
+ ...problemFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'problem', own(f)))];
309
385
  const failed = report([
310
386
  ...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
311
387
  ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
package/lib/design.mjs CHANGED
@@ -21,12 +21,13 @@ import { runSandboxed, sandboxed } from './sandbox.mjs';
21
21
  export { polygons };
22
22
  import fs from 'node:fs';
23
23
  import path from 'node:path';
24
- import { pathToFileURL } from 'node:url';
24
+ import { pathToFileURL, fileURLToPath } from 'node:url';
25
25
  import { createRequire } from 'node:module';
26
26
  import crypto from 'node:crypto';
27
27
  import { resolve, loadRuleSet } from './rules.mjs';
28
28
  import { WS, paths, printerOf } from './workspace.mjs';
29
29
  import { readLayout, hasLayout, keys, width, depth } from './layout.mjs';
30
+ import { optimised, forDesign } from './optimise.mjs';
30
31
  import * as shapes from '@rulecad/shapes';
31
32
  import { engineId, packageVersion, materialise } from './versions.mjs';
32
33
  import { satisfies } from '@rulecad/versions';
@@ -89,6 +90,19 @@ export function layoutsOf(d, object) {
89
90
  return out;
90
91
  }
91
92
 
93
+ // The optimised layouts an object's problem variables pick, by name, for v.problems
94
+ export async function problemsOf(d, object, values) {
95
+ const out = {};
96
+ for (const [name, v] of Object.entries(object.variables || {})) if (v.type === 'problem') {
97
+ const ref = values[name];
98
+ if (!out[ref]) {
99
+ const r = await optimised(d.project, ref, { onStep: (s) => s.step === 1 && console.error(`optimising ${ref} (once: the result is cached until the problem changes)…`) });
100
+ out[ref] = forDesign(r);
101
+ }
102
+ }
103
+ return out;
104
+ }
105
+
92
106
  // A variant's inputs, under what's set explicitly
93
107
  export function variantSet(d, object, set = {}) {
94
108
  if (!d.variant) return set;
@@ -101,7 +115,8 @@ const CACHE = paths.cache('builds'), CACHE_VERSION = 2;
101
115
  const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
102
116
  // What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
103
117
  // boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
104
- const own = source(import.meta.url) + source(import.meta.resolve('@rulecad/shapes')) + packageVersion('@jscad/modeling');
118
+ const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes')));
119
+ const own = source(import.meta.url) + fs.readdirSync(shapesDir).filter((f) => f.endsWith('.mjs')).sort().map((f) => source(pathToFileURL(path.join(shapesDir, f)).href)).join('') + packageVersion('@jscad/modeling'); // every shapes module, not just its entry
105
120
  export const pcbEngine = () => import('@rulecad/pcb').catch((e) => {
106
121
  if (e.code === 'ERR_MODULE_NOT_FOUND' && /@rulecad\/pcb/.test(e.message)) throw new Error('boards need the board engine: npm install @rulecad/pcb');
107
122
  throw e;
@@ -134,10 +149,14 @@ export async function build(d, set = {}, { mirror = false } = {}) {
134
149
  const files = layoutsOf(d, object);
135
150
  if (object.layouts) values.layouts = object.layouts; // older designs kept layouts in their .json
136
151
  if (Object.keys(files).length) values.layouts = Object.fromEntries(Object.entries(files).map(([n, l]) => [n, { ...l, keys: keys(l), width: width(l), depth: depth(l) }]));
152
+ // Optimised layouts: a "type": "problem" variable picks a problem in the project's problems/; the design gets the
153
+ // one it picked as v.problems[name] (lib/optimise.mjs), optimised the first time and cached after
154
+ const problems = await problemsOf(d, object, values);
155
+ if (Object.keys(problems).length) values.problems = problems;
137
156
 
138
157
  // The cache: everything the build is made from. A hit skips running the design (and its booleans) altogether
139
158
  const ruleText = [...(object.uses || []).map((u) => JSON.stringify(sets[u] || loadRuleSet(u))), JSON.stringify(refs.extra)];
140
- const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), JSON.stringify(object), ruleText, files, set, display])).digest('hex');
159
+ const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), JSON.stringify(object), ruleText, files, Object.values(problems).map((p) => p.hash), set, display])).digest('hex');
141
160
  const hit = path.join(CACHE, `${key}.json`);
142
161
  if (!process.env.CAD_NO_CACHE && host.exists(hit)) {
143
162
  const c = JSON.parse(host.readText(hit));
@@ -0,0 +1,251 @@
1
+ // Optimisation problems and analysis: problems/<name>.json in a project describes a part to optimise, flat (2D) or
2
+ // solid (3D): where material may go, what stays solid or empty, supports, loads, material. @rulecad/topopt finds the
3
+ // stiffest layout, and @rulecad/fea analyses any part under the same problem's loads (an object's "analysis", run by
4
+ // cad check). The problem file is the source: a result is derived from it, cached by everything it's made from, and
5
+ // remade only when one of those changes. A name may pick a variant: lever:both. A 3D region can be a named part of
6
+ // another design in the project ({ "part": "envelope.body" }), as it's built.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import crypto from 'node:crypto';
10
+ import { host } from './host.mjs';
11
+ import { paths } from './workspace.mjs';
12
+ import { resolve, evaluate } from './rules.mjs';
13
+ import { located } from './errors.mjs';
14
+ import { discretise, optimise, outlines, surface, area } from '@rulecad/topopt';
15
+ import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
16
+
17
+ const VERSION = 2, source = (m) => fs.readFileSync(new URL(import.meta.resolve(m)), 'utf8'); // the solver's code: a change remakes results
18
+ export const problemFile = (project, name) => path.join(paths.project(project), 'problems', `${name}.json`);
19
+ export const hasProblem = (project, ref) => host.exists(problemFile(project, String(ref).split(':')[0]));
20
+
21
+ /**
22
+ * A problem with every expression worked out: what @rulecad/topopt takes, with its material and settings.
23
+ * @param {string} project @param {string} ref name, or name:variant
24
+ */
25
+ export async function readProblem(project, ref) {
26
+ const [name, variant] = String(ref).split(':'), file = problemFile(project, name);
27
+ if (!host.exists(file)) throw new Error(`no problem "${name}" (projects/${project}/problems/${name}.json)`);
28
+ const p = JSON.parse(host.readText(file));
29
+ if (variant && !p.variants?.[variant]) throw new Error(`problem ${name} has no variant "${variant}" (variants: ${Object.keys(p.variants || {}).join(', ') || 'none'})`);
30
+ const uses = [...new Set([...(p.uses || []), p.material])];
31
+ let values;
32
+ try { ({ values } = resolve({ uses, variables: p.variables || {} }, { set: variant ? p.variants[variant] : {} })); } catch (e) { throw located(e, file, 'var'); }
33
+ const lookup = (n) => {
34
+ const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), values);
35
+ if (typeof v !== 'number') throw new Error(`${path.basename(file)}: "${n}" isn't a number here (variables: ${Object.keys(p.variables || {}).join(', ')})`);
36
+ return v;
37
+ };
38
+ const ev = (x) => evaluate(x, lookup), pt = (a) => a.map(ev);
39
+ // A named part of another design in the project, as triangles (built with its defaults)
40
+ const parts = new Map();
41
+ const part = async (ref) => {
42
+ if (!parts.has(ref)) {
43
+ const [object, partName] = ref.split('.'), { build, locate } = await import('./design.mjs');
44
+ const b = await build(locate(`${project}/${object}`)), found = partName ? b.parts.find((q) => q.name === partName) : b.parts.find((q) => q.role !== 'support');
45
+ if (!found) throw new Error(`${path.basename(file)}: ${object} has no part "${partName}" (parts: ${b.parts.map((q) => q.name).join(', ')})`);
46
+ parts.set(ref, found.triangles);
47
+ }
48
+ return parts.get(ref);
49
+ };
50
+ const region = async (r) => {
51
+ if (r.part) return { triangles: await part(r.part), part: r.part };
52
+ if (r.points) return { points: r.points.map(pt) };
53
+ if (r.size) return { at: pt(r.at), size: r.size.map(ev) };
54
+ if (r.length != null) return { at: pt(r.at), r: ev(r.r), length: ev(r.length), axis: r.axis || 'z', ...(r.teardrop ? { teardrop: r.teardrop } : {}) };
55
+ return { at: pt(r.at), ...(r.r != null ? { r: ev(r.r) } : {}) };
56
+ };
57
+ const regions = (list) => Promise.all([list || []].flat().map(region));
58
+ const m = values[p.material];
59
+ if (typeof m?.modulus !== 'number' || typeof m?.poisson !== 'number') throw new Error(`material ${p.material}: its rule set needs modulus (MPa) and poisson`);
60
+ const space = await regions(p.space), dim = space[0].triangles || space[0].length != null || (space[0].size || space[0].at)?.length === 3 ? 3 : 2;
61
+ // The build direction: a direction ('+z'), or a variable holding one
62
+ const overhang = p.overhang ? (typeof values[p.overhang] === 'string' ? values[p.overhang] : p.overhang) : null;
63
+ const problem = {
64
+ space, keep: await regions(p.keep), avoid: await regions(p.avoid),
65
+ supports: await Promise.all(p.supports.map(async (s) => ({ ...(await region(s)), fix: s.fix || 'xyz'.slice(0, dim) }))),
66
+ loads: await Promise.all(p.loads.map(async (l) => ({ ...(await region(l)), force: pt(l.force), case: l.case || 'load' }))),
67
+ cases: Object.fromEntries(Object.entries(p.cases || {}).map(([k, w]) => [k, ev(w)])),
68
+ material: { E: m.modulus, nu: m.poisson }, ...(dim === 2 ? { thickness: ev(p.thickness) } : {}), cell: ev(p.cell), volume: ev(p.volume),
69
+ ...(p.filter != null ? { filter: ev(p.filter) } : {}), ...(p.penal != null ? { penal: ev(p.penal) } : {}),
70
+ ...(p.projection != null ? { projection: p.projection } : {}), ...(p.steps != null ? { steps: p.steps } : {}),
71
+ ...(overhang && overhang !== 'none' ? { overhang } : {}),
72
+ };
73
+ if (dim === 2 && !(problem.thickness > 0)) throw new Error(`${path.basename(file)}: a flat (2D) problem needs a thickness`);
74
+ const outline = { smooth: p.outline?.smooth ?? 4, minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2 };
75
+ return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline };
76
+ }
77
+
78
+ /**
79
+ * The optimised layout for a problem, from the cache when nothing it depends on has changed. A 2D result has outlines
80
+ * (closed loops in mm); a 3D one has a mesh ({ vertices, faces }, a closed surface in mm).
81
+ * @param {string} project @param {string} ref
82
+ * @param {{ onStep?: Function, fresh?: boolean }} [options] fresh: run it even if it's cached
83
+ */
84
+ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
85
+ const r = await readProblem(project, ref), topopt = source('@rulecad/topopt'), [solver] = topopt.split('// ---------- shapes from results ----------');
86
+ const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
87
+ // Two keeps: the densities, by the problem and the code that decides them (the slow part), and the shape drawn from
88
+ // them, by everything: a change to how shapes are drawn redraws them without optimising again
89
+ const hash = digest([VERSION, r.problem, r.outline, topopt, source('@rulecad/fea')]), file = paths.cache('optimise', `${hash}.json`);
90
+ if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file)) return { ...JSON.parse(host.readText(file)), cached: true };
91
+ const spec = discretise(r.problem), densities = paths.cache('densities', `${digest([VERSION, r.problem, solver, source('@rulecad/fea')])}.json`);
92
+ const o = !fresh && !process.env.CAD_NO_CACHE && host.exists(densities) ? (({ density, ...x }) => ({ ...x, density: Float64Array.from(density) }))(JSON.parse(host.readText(densities))) : optimise(spec, { onStep });
93
+ if (!host.exists(densities)) host.writeText(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
94
+ // Regions as data: a part's triangles are named, not copied
95
+ const named = (list) => list.map(({ triangles, ...x }) => x);
96
+ const shape = r.dim === 2 ? (() => {
97
+ const loops = outlines(spec.grid, o.density, spec.origin, r.outline);
98
+ return { outlines: loops.map((l) => l.map(([x, y]) => [round(x), round(y)])), area: loops.reduce((s, l) => s + area(l), 0) };
99
+ })() : (() => {
100
+ // The surface's level, found so the solid holds as much material as the optimised densities do (drawn at 0.5,
101
+ // thin members come out thinner than they are)
102
+ const want = o.density.reduce((t, d) => t + d, 0) * spec.grid.h ** 3, at = (iso) => surface(spec.grid, o.density, spec.origin, { smooth: r.outline.smooth, iso });
103
+ let lo = 0.2, hi = 0.8, best = at(0.5), iso = 0.5;
104
+ for (let k = 0; k < 10 && Math.abs(meshVolume(best.vertices, best.faces) / want - 1) > 0.003; k++) {
105
+ if (meshVolume(best.vertices, best.faces) < want) hi = iso; else lo = iso; // a lower level encloses more
106
+ iso = (lo + hi) / 2; best = at(iso);
107
+ }
108
+ const { vertices, faces } = best;
109
+ return { mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces }, solid: meshVolume(vertices, faces), iso };
110
+ })();
111
+ const result = {
112
+ problem: ref, title: r.title, hash, dim: r.dim, material: r.material.name, ...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
113
+ grid: spec.grid, origin: spec.origin, regions: { keep: named(spec.regions.keep), avoid: named(spec.regions.avoid) }, ...shape,
114
+ volume: o.volume, compliance: o.compliance, cases: o.cases, overhang: r.problem.overhang || null,
115
+ steps: o.steps, converged: o.converged, seconds: o.seconds, history: o.history, density: Array.from(o.density, (d) => round(d, 3)),
116
+ supports: named(r.problem.supports), loads: named(r.problem.loads),
117
+ };
118
+ host.writeText(file, JSON.stringify(result));
119
+ return result;
120
+ }
121
+
122
+ // A closed mesh's volume (mm³), by the divergence theorem
123
+ function meshVolume(vertices, faces) {
124
+ let v = 0;
125
+ for (const [i, j, k] of faces) { const a = vertices[i], b = vertices[j], c = vertices[k]; v += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6; }
126
+ return v;
127
+ }
128
+
129
+ // What a design gets as v.problems[name]: the outlines and regions to build from, and the numbers to report
130
+ export const forDesign = ({ density, history, ...r }) => r;
131
+
132
+ /**
133
+ * Analyse a part under a problem's supports and loads, on its grid. A flat part (2D problem: triangles, z up, the
134
+ * plate lying on the bed): each cell is as solid as the share of the problem's thickness the part fills above it. A
135
+ * solid part (3D): each cube is solid if its centre is inside the part.
136
+ * @param {number[][][]} triangles @param {string} project @param {string} ref
137
+ */
138
+ export async function analysePart(triangles, project, ref) {
139
+ const r = await readProblem(project, ref), { problem } = r, h = problem.cell;
140
+ if (r.dim === 3) return analyseSolid(triangles, r);
141
+ // The grid covers the part and the problem's space
142
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
143
+ for (const t of triangles) for (const [x, y] of t) { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }
144
+ const nx = Math.max(1, Math.ceil((x1 - x0) / h)), ny = Math.max(1, Math.ceil((y1 - y0) / h));
145
+ const density = fill(triangles, { nx, ny, h, origin: [x0, y0] }, problem.thickness);
146
+ const g = makeGrid({ nx, ny, h }), at = positions(g).map(([x, y]) => [x + x0, y + y0]);
147
+ // Supports and loads on the nodes near them that touch the part
148
+ const onPart = new Uint8Array(g.nodes);
149
+ for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) for (let k = 0; k < 4; k++) onPart[g.edof[e * 8 + 2 * k] / 2] = 1;
150
+ const near = (p, rr = 0, what) => {
151
+ const found = [];
152
+ for (let n = 0; n < g.nodes; n++) if (onPart[n] && Math.hypot(at[n][0] - p[0], at[n][1] - p[1]) <= rr + h * 0.75) found.push(n);
153
+ if (!found.length) throw new Error(`${what} at ${p.join(', ')} isn't on the part: is it placed as the problem expects?`);
154
+ return found;
155
+ };
156
+ const fixed = new Uint8Array(g.dofs);
157
+ for (const s of problem.supports) for (const n of near(s.at, s.r, 'a support')) { if (s.fix.includes('x')) fixed[2 * n] = 1; if (s.fix.includes('y')) fixed[2 * n + 1] = 1; }
158
+ const names = [...new Set(problem.loads.map((l) => l.case))];
159
+ const loads = names.map((name) => {
160
+ const f = new Float64Array(g.dofs);
161
+ for (const l of problem.loads.filter((x) => x.case === name)) { const ns = near(l.at, l.r, `the load "${name}"`); for (const n of ns) { f[2 * n] += l.force[0] / ns.length; f[2 * n + 1] += l.force[1] / ns.length; } }
162
+ return f;
163
+ });
164
+ const a = analyse({ grid: g, density, material: problem.material, thickness: problem.thickness, fixed, loads });
165
+ const cases = names.map((name, c) => {
166
+ const size = Math.hypot(...problem.loads.filter((l) => l.case === name).reduce((s, l) => [s[0] + l.force[0], s[1] + l.force[1]], [0, 0]));
167
+ const deflection = size ? a.compliance[c] / size : 0;
168
+ let most = 0;
169
+ for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) most = Math.max(most, a.stress[c][e]);
170
+ return { name, force: size, deflection, stiffness: deflection ? size / deflection : Infinity, stress: most };
171
+ });
172
+ return { problem: ref, material: r.material, cases, volume: volume(triangles), grid: { nx, ny, h }, origin: [x0, y0], density };
173
+ }
174
+
175
+ // A solid part on the problem's grid: the part itself is the space (keep and avoid regions don't apply), so the
176
+ // supports and loads land on it as they would on an optimised layout
177
+ function analyseSolid(triangles, r) {
178
+ const { problem } = r, spec = discretise({ ...problem, space: { triangles }, keep: [], avoid: [], volume: 1 });
179
+ const g = makeGrid(spec.grid), density = Float64Array.from(spec.passive, (p) => (p === 0 ? 1 : 0));
180
+ if (!density.some((d) => d)) throw new Error('the part is smaller than one cell of the problem: use a smaller cell');
181
+ const a = analyse({ grid: g, density, material: problem.material, fixed: spec.fixed, loads: spec.loads.map((l) => l.force) });
182
+ const cases = spec.loads.map((l, c) => {
183
+ const deflection = l.size ? a.compliance[c] / l.size : 0;
184
+ let most = 0;
185
+ for (let e = 0; e < density.length; e++) if (density[e]) most = Math.max(most, a.stress[c][e]);
186
+ return { name: l.name, force: l.size, deflection, stiffness: deflection ? l.size / deflection : Infinity, stress: most };
187
+ });
188
+ return { problem: r.ref, dim: 3, material: r.material, cases, volume: volume(triangles), grid: spec.grid, origin: spec.origin, density };
189
+ }
190
+
191
+ // How much of the thickness the part fills over each cell's centre: a ray straight up through the part enters it
192
+ // through faces that face down and leaves through faces that face up, so the filled length is the sum of the up
193
+ // faces' heights there less the down faces'
194
+ function fill(triangles, { nx, ny, h, origin }, thickness) {
195
+ const length = new Float64Array(nx * ny), jx = h * 1e-4 * Math.SQRT2, jy = h * 1e-4 * Math.PI; // off-centre, so no ray meets an edge exactly
196
+ for (const [a, b, c] of triangles) {
197
+ const nz = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
198
+ if (Math.abs(nz) < 1e-12) continue; // a wall: the ray runs alongside it
199
+ const lo = [Math.min(a[0], b[0], c[0]), Math.min(a[1], b[1], c[1])], hi = [Math.max(a[0], b[0], c[0]), Math.max(a[1], b[1], c[1])];
200
+ const i0 = Math.max(0, Math.floor((lo[0] - origin[0]) / h)), i1 = Math.min(nx - 1, Math.ceil((hi[0] - origin[0]) / h));
201
+ const j0 = Math.max(0, Math.floor((lo[1] - origin[1]) / h)), j1 = Math.min(ny - 1, Math.ceil((hi[1] - origin[1]) / h));
202
+ for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
203
+ const x = origin[0] + (i + 0.5) * h + jx, y = origin[1] + (j + 0.5) * h + jy;
204
+ const w0 = ((b[0] - x) * (c[1] - y) - (b[1] - y) * (c[0] - x)) / nz, w1 = ((c[0] - x) * (a[1] - y) - (c[1] - y) * (a[0] - x)) / nz, w2 = 1 - w0 - w1;
205
+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;
206
+ length[j * nx + i] += Math.sign(nz) * (w0 * a[2] + w1 * b[2] + w2 * c[2]);
207
+ }
208
+ }
209
+ return length.map((l) => Math.min(1, Math.max(0, l / thickness)));
210
+ }
211
+
212
+ // A closed mesh's volume (mm³), by the divergence theorem
213
+ function volume(triangles) {
214
+ let v = 0;
215
+ for (const [a, b, c] of triangles) v += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6;
216
+ return Math.abs(v);
217
+ }
218
+
219
+ const round = (n, d = 4) => Number(n.toFixed(d));
220
+
221
+ /**
222
+ * A picture of a density field (an optimised result, or an analysed part) as SVG: cells shaded by density, outlines,
223
+ * supports (triangles) and loads (arrows).
224
+ * @param {{ grid: { nx: number, ny: number, h: number }, origin: number[], density: ArrayLike<number>, outlines?: number[][][], supports?: any[], loads?: any[] }} r
225
+ * @param {{ title?: string, lines?: string[] }} [label]
226
+ */
227
+ export function picture(r, { title = '', lines = [] } = {}) {
228
+ const { nx, ny, h } = r.grid, s = Math.max(2, Math.min(8, Math.floor(1100 / (nx * h)))) , pad = 24, top = 30 + lines.length * 16;
229
+ const W = nx * h * s + 2 * pad, H = ny * h * s + pad + top + 12;
230
+ const X = (x) => pad + (x - r.origin[0]) * s, Y = (y) => top + (ny * h - (y - r.origin[1])) * s;
231
+ const cells = [];
232
+ for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
233
+ const d = r.density[j * nx + i];
234
+ if (d > 0.02) cells.push(`<rect x="${X(r.origin[0] + i * h).toFixed(1)}" y="${Y(r.origin[1] + (j + 1) * h).toFixed(1)}" width="${(h * s + 0.3).toFixed(1)}" height="${(h * s + 0.3).toFixed(1)}" fill-opacity="${d.toFixed(2)}"/>`);
235
+ }
236
+ const loops = (r.outlines || []).map((l) => `<path d="M${l.map(([x, y]) => `${X(x).toFixed(1)},${Y(y).toFixed(1)}`).join('L')}Z"/>`);
237
+ const supports = (r.supports || []).map((p) => `<path d="M${X(p.at[0])},${Y(p.at[1])}l-6,10h12z"/>`);
238
+ const loads = (r.loads || []).map((l) => {
239
+ const len = Math.hypot(...l.force) || 1, dx = (l.force[0] / len) * 30, dy = (-l.force[1] / len) * 30, x = X(l.at[0]), y = Y(l.at[1]);
240
+ return `<path d="M${x - dx},${y - dy}L${x},${y}"/><circle cx="${x}" cy="${y}" r="3"/>`;
241
+ });
242
+ const text = [title, ...lines].map((t, i) => `<text x="${pad}" y="${20 + i * 16}" font-size="${i ? 12 : 14}"${i ? '' : ' font-weight="600"'}>${t.replace(/&/g, '&amp;').replace(/</g, '&lt;')}</text>`);
243
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" font-family="system-ui, sans-serif">
244
+ <rect width="100%" height="100%" fill="#fff"/>${text.join('')}
245
+ <g fill="#2b4c7e">${cells.join('')}</g>
246
+ <g fill="none" stroke="#e8a33d" stroke-width="1.5">${loops.join('')}</g>
247
+ <g fill="#3a9d5d">${supports.join('')}</g>
248
+ <g stroke="#c0392b" fill="#c0392b" stroke-width="2.5">${loads.join('')}</g>
249
+ </svg>
250
+ `;
251
+ }
package/lib/schema.mjs CHANGED
@@ -7,7 +7,7 @@ import { fileURLToPath } from 'node:url';
7
7
 
8
8
  const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'schemas');
9
9
  const cache = new Map();
10
- /** A schema by name: object, assembly, rules or layout. @param {'object' | 'assembly' | 'rules' | 'layout'} name */
10
+ /** A schema by name: object, assembly, rules, layout or problem. @param {'object' | 'assembly' | 'rules' | 'layout' | 'problem'} name */
11
11
  export function schema(name) {
12
12
  if (!cache.has(name)) cache.set(name, JSON.parse(fs.readFileSync(path.join(DIR, `${name}.schema.json`), 'utf8')));
13
13
  return cache.get(name);
@@ -63,7 +63,7 @@ export function validate(value, s, root = s, at = '') {
63
63
  return out;
64
64
  }
65
65
 
66
- /** Problems with a file's JSON as findings (code schema), for cad check. @param {any} json @param {'object' | 'assembly' | 'rules' | 'layout'} kind @param {string} file */
66
+ /** Problems with a file's JSON as findings (code schema), for cad check. @param {any} json @param {'object' | 'assembly' | 'rules' | 'layout' | 'problem'} kind @param {string} file */
67
67
  export function schemaFindings(json, kind, file) {
68
68
  return validate(json, schema(kind)).map((x) => ({ level: 'fail', text: `${file}: ${x.path}: ${x.message}`, code: 'schema', refs: { file, path: x.path } }));
69
69
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.5.1",
3
+ "version": "0.7.0",
4
4
  "description": "The cad command: JSCAD designs from traceable rules, checked for printing and fit, versioned by what fits, shared as links and exported as Bambu 3MF.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -44,16 +44,18 @@
44
44
  "directory": "packages/cad"
45
45
  },
46
46
  "dependencies": {
47
- "@rulecad/variables": "^0.1.7",
47
+ "@rulecad/variables": "^0.2.0",
48
48
  "@rulecad/keyboard-layout": "^0.1.2",
49
49
  "@rulecad/printcheck": "^0.1.3",
50
50
  "@rulecad/fit": "^0.2.1",
51
51
  "@rulecad/model-link": "^0.2.0",
52
52
  "@rulecad/versions": "^0.1.0",
53
- "@rulecad/shapes": "^0.2.1",
54
- "@rulecad/rules": "^0.2.0",
53
+ "@rulecad/shapes": "^0.4.0",
54
+ "@rulecad/rules": "^0.3.0",
55
55
  "@jscad/modeling": "^2.12.0",
56
- "three": "^0.186.1"
56
+ "three": "^0.186.1",
57
+ "@rulecad/fea": "^0.2.0",
58
+ "@rulecad/topopt": "^0.2.0"
57
59
  },
58
60
  "peerDependencies": {
59
61
  "@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0"
@@ -24,7 +24,8 @@
24
24
  "parts": { "type": "object", "additionalProperties": { "$ref": "#/$defs/part" } },
25
25
  "variants": { "type": "object", "additionalProperties": { "type": "object" } },
26
26
  "anchors": { "type": "object", "additionalProperties": { "$ref": "#/$defs/anchor" } },
27
- "layouts": { "type": "object", "description": "Older designs kept layouts here; now in the project's layouts/" }
27
+ "layouts": { "type": "object", "description": "Older designs kept layouts here; now in the project's layouts/" },
28
+ "analysis": { "type": "array", "items": { "$ref": "#/$defs/analysis" }, "description": "Checks of how the part bends under a problem's loads (cad check)" }
28
29
  },
29
30
  "$defs": {
30
31
  "expr": { "type": ["number", "string"] },
@@ -40,7 +41,7 @@
40
41
  "show": { "type": "boolean" },
41
42
  "interface": { "type": "boolean", "description": "Other objects depend on it: a change bumps the version accordingly" },
42
43
  "tweak": { "type": "object", "required": ["min", "max"], "additionalProperties": false, "properties": { "min": { "$ref": "#/$defs/expr" }, "max": { "$ref": "#/$defs/expr" }, "step": { "type": "number" } } },
43
- "type": { "enum": ["text", "anchor", "choice", "layout"] },
44
+ "type": { "enum": ["text", "anchor", "choice", "layout", "problem"] },
44
45
  "choice": { "type": "array" },
45
46
  "max": { "type": "number" },
46
47
  "fields": { "type": "array", "items": { "type": "string" } },
@@ -49,6 +50,18 @@
49
50
  "checked": { "type": "string" }
50
51
  }
51
52
  },
53
+ "analysis": {
54
+ "type": "object",
55
+ "required": ["problem"],
56
+ "additionalProperties": false,
57
+ "properties": {
58
+ "problem": { "type": "string", "description": "A problem in the project's problems/ (name, or name:variant): its supports, loads, material and thickness" },
59
+ "part": { "type": "string", "description": "The part analysed (default: the first that isn't a support)" },
60
+ "max_deflection": { "$ref": "#/$defs/expr", "description": "Fail if any load case moves its load further than this, in mm" },
61
+ "volume": { "$ref": "#/$defs/expr", "description": "Fail if the part's volume differs from this (mm³) by more than tolerance" },
62
+ "tolerance": { "type": "number", "description": "For volume: the share it may differ by (default 0.01)" }
63
+ }
64
+ },
52
65
  "part": {
53
66
  "type": "object",
54
67
  "additionalProperties": false,
@@ -0,0 +1,348 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://jonibach.github.io/rulecad/schemas/problem.schema.json",
4
+ "title": "rulecad optimisation problem",
5
+ "description": "A part to optimise, flat (2D) or solid (3D), in projects/<project>/problems/<name>.json: where material may go, what must stay solid or empty, where it's held and loaded, and what it's made of. Numbers are expressions, as in objects: of its variables and the rule sets it uses. cad optimise runs it; a design reads the result through a variable of type problem.",
6
+ "type": "object",
7
+ "required": [
8
+ "material",
9
+ "cell",
10
+ "volume",
11
+ "space",
12
+ "supports",
13
+ "loads"
14
+ ],
15
+ "additionalProperties": false,
16
+ "properties": {
17
+ "$schema": {
18
+ "type": "string"
19
+ },
20
+ "title": {
21
+ "type": "string"
22
+ },
23
+ "description": {
24
+ "type": "string"
25
+ },
26
+ "uses": {
27
+ "type": "array",
28
+ "items": {
29
+ "type": "string"
30
+ },
31
+ "description": "Rule sets: the material's, the printer's, the part's own"
32
+ },
33
+ "variables": {
34
+ "type": "object",
35
+ "description": "As in objects"
36
+ },
37
+ "variants": {
38
+ "type": "object",
39
+ "additionalProperties": {
40
+ "type": "object"
41
+ },
42
+ "description": "Named settings of variables with tweak ranges, picked as name:variant"
43
+ },
44
+ "material": {
45
+ "type": "string",
46
+ "description": "A rule set with modulus (MPa), poisson and, for safety factors, strength (MPa)"
47
+ },
48
+ "thickness": {
49
+ "$ref": "#/$defs/expr",
50
+ "description": "A flat (2D) problem's thickness, mm"
51
+ },
52
+ "cell": {
53
+ "$ref": "#/$defs/expr",
54
+ "description": "The grid's cell size, mm: smaller is finer and slower"
55
+ },
56
+ "volume": {
57
+ "$ref": "#/$defs/expr",
58
+ "description": "The share of the space to fill, 0 to 1 (keep regions count towards it)"
59
+ },
60
+ "filter": {
61
+ "$ref": "#/$defs/expr",
62
+ "description": "Filter radius, mm: about the thinnest member (default 1.5 cells)"
63
+ },
64
+ "penal": {
65
+ "$ref": "#/$defs/expr",
66
+ "description": "The penalty on part-solid cells (default 3)"
67
+ },
68
+ "projection": {
69
+ "type": "boolean",
70
+ "description": "Sharpen the result to solid and empty (default true)"
71
+ },
72
+ "steps": {
73
+ "type": "integer",
74
+ "description": "At most this many steps (default 300)"
75
+ },
76
+ "space": {
77
+ "oneOf": [
78
+ {
79
+ "$ref": "#/$defs/region"
80
+ },
81
+ {
82
+ "type": "array",
83
+ "items": {
84
+ "$ref": "#/$defs/region"
85
+ }
86
+ }
87
+ ],
88
+ "description": "Where material may go"
89
+ },
90
+ "keep": {
91
+ "type": "array",
92
+ "items": {
93
+ "$ref": "#/$defs/region"
94
+ },
95
+ "description": "Must stay solid: bosses round bolt holes"
96
+ },
97
+ "avoid": {
98
+ "type": "array",
99
+ "items": {
100
+ "$ref": "#/$defs/region"
101
+ },
102
+ "description": "Must stay empty: holes, clearances (avoid wins over keep)"
103
+ },
104
+ "supports": {
105
+ "type": "array",
106
+ "minItems": 1,
107
+ "items": {
108
+ "$ref": "#/$defs/support"
109
+ }
110
+ },
111
+ "loads": {
112
+ "type": "array",
113
+ "minItems": 1,
114
+ "items": {
115
+ "$ref": "#/$defs/load"
116
+ }
117
+ },
118
+ "cases": {
119
+ "type": "object",
120
+ "additionalProperties": {
121
+ "$ref": "#/$defs/expr"
122
+ },
123
+ "description": "Each load case's weight in the optimisation (default 1); 0 analyses it without optimising for it"
124
+ },
125
+ "outline": {
126
+ "type": "object",
127
+ "additionalProperties": false,
128
+ "properties": {
129
+ "smooth": {
130
+ "type": "integer",
131
+ "description": "Smoothing passes for the outline (2D) or surface (3D), default 4"
132
+ },
133
+ "min_area": {
134
+ "$ref": "#/$defs/expr",
135
+ "description": "Holes and islands smaller than this (mm²) are dropped"
136
+ }
137
+ }
138
+ },
139
+ "overhang": {
140
+ "type": "string",
141
+ "description": "3D: printable this way up ('+z', '-y', …), or a variable holding it, or 'none': only material supported from below at 45° or less"
142
+ }
143
+ },
144
+ "$defs": {
145
+ "expr": {
146
+ "type": [
147
+ "number",
148
+ "string"
149
+ ]
150
+ },
151
+ "point": {
152
+ "type": "array",
153
+ "items": {
154
+ "$ref": "#/$defs/expr"
155
+ },
156
+ "minItems": 2,
157
+ "maxItems": 3
158
+ },
159
+ "region": {
160
+ "type": "object",
161
+ "additionalProperties": false,
162
+ "properties": {
163
+ "at": {
164
+ "$ref": "#/$defs/point",
165
+ "description": "The centre, mm: [x, y] in 2D, [x, y, z] in 3D"
166
+ },
167
+ "r": {
168
+ "$ref": "#/$defs/expr",
169
+ "description": "A circle's or ball's radius, or a cylinder's"
170
+ },
171
+ "size": {
172
+ "type": "array",
173
+ "items": {
174
+ "$ref": "#/$defs/expr"
175
+ },
176
+ "minItems": 2,
177
+ "maxItems": 3,
178
+ "description": "A rectangle's or box's sides"
179
+ },
180
+ "length": {
181
+ "$ref": "#/$defs/expr",
182
+ "description": "3D: a cylinder's length (with r)"
183
+ },
184
+ "axis": {
185
+ "enum": [
186
+ "x",
187
+ "y",
188
+ "z"
189
+ ],
190
+ "description": "3D: the cylinder's axis (default z)"
191
+ },
192
+ "points": {
193
+ "type": "array",
194
+ "items": {
195
+ "$ref": "#/$defs/point"
196
+ },
197
+ "minItems": 3,
198
+ "description": "2D: a polygon's corners"
199
+ },
200
+ "part": {
201
+ "type": "string",
202
+ "description": "3D: a named part of another design in the project, as it's built: object.part"
203
+ },
204
+ "label": {
205
+ "type": "string"
206
+ },
207
+ "teardrop": {
208
+ "enum": [
209
+ "-z",
210
+ "+z"
211
+ ],
212
+ "description": "3D: a cylinder along x or y with a 45° point that way, so it prints without support: '-z' for a boss (its underside), '+z' for a hole (its roof)"
213
+ }
214
+ }
215
+ },
216
+ "support": {
217
+ "type": "object",
218
+ "required": [],
219
+ "additionalProperties": false,
220
+ "properties": {
221
+ "at": {
222
+ "$ref": "#/$defs/point",
223
+ "description": "The centre, mm: [x, y] in 2D, [x, y, z] in 3D"
224
+ },
225
+ "r": {
226
+ "$ref": "#/$defs/expr",
227
+ "description": "A circle's or ball's radius, or a cylinder's"
228
+ },
229
+ "size": {
230
+ "type": "array",
231
+ "items": {
232
+ "$ref": "#/$defs/expr"
233
+ },
234
+ "minItems": 2,
235
+ "maxItems": 3,
236
+ "description": "A rectangle's or box's sides"
237
+ },
238
+ "length": {
239
+ "$ref": "#/$defs/expr",
240
+ "description": "3D: a cylinder's length (with r)"
241
+ },
242
+ "axis": {
243
+ "enum": [
244
+ "x",
245
+ "y",
246
+ "z"
247
+ ],
248
+ "description": "3D: the cylinder's axis (default z)"
249
+ },
250
+ "points": {
251
+ "type": "array",
252
+ "items": {
253
+ "$ref": "#/$defs/point"
254
+ },
255
+ "minItems": 3,
256
+ "description": "2D: a polygon's corners"
257
+ },
258
+ "part": {
259
+ "type": "string",
260
+ "description": "3D: a named part of another design in the project, as it's built: object.part"
261
+ },
262
+ "label": {
263
+ "type": "string"
264
+ },
265
+ "fix": {
266
+ "type": "string",
267
+ "pattern": "^[xyz]+$",
268
+ "description": "Which ways it's held: x, y, z (default all)"
269
+ },
270
+ "teardrop": {
271
+ "enum": [
272
+ "-z",
273
+ "+z"
274
+ ],
275
+ "description": "3D: a cylinder along x or y with a 45° point that way, so it prints without support: '-z' for a boss (its underside), '+z' for a hole (its roof)"
276
+ }
277
+ }
278
+ },
279
+ "load": {
280
+ "type": "object",
281
+ "required": [
282
+ "force"
283
+ ],
284
+ "additionalProperties": false,
285
+ "properties": {
286
+ "at": {
287
+ "$ref": "#/$defs/point",
288
+ "description": "The centre, mm: [x, y] in 2D, [x, y, z] in 3D"
289
+ },
290
+ "r": {
291
+ "$ref": "#/$defs/expr",
292
+ "description": "A circle's or ball's radius, or a cylinder's"
293
+ },
294
+ "size": {
295
+ "type": "array",
296
+ "items": {
297
+ "$ref": "#/$defs/expr"
298
+ },
299
+ "minItems": 2,
300
+ "maxItems": 3,
301
+ "description": "A rectangle's or box's sides"
302
+ },
303
+ "length": {
304
+ "$ref": "#/$defs/expr",
305
+ "description": "3D: a cylinder's length (with r)"
306
+ },
307
+ "axis": {
308
+ "enum": [
309
+ "x",
310
+ "y",
311
+ "z"
312
+ ],
313
+ "description": "3D: the cylinder's axis (default z)"
314
+ },
315
+ "points": {
316
+ "type": "array",
317
+ "items": {
318
+ "$ref": "#/$defs/point"
319
+ },
320
+ "minItems": 3,
321
+ "description": "2D: a polygon's corners"
322
+ },
323
+ "part": {
324
+ "type": "string",
325
+ "description": "3D: a named part of another design in the project, as it's built: object.part"
326
+ },
327
+ "label": {
328
+ "type": "string"
329
+ },
330
+ "force": {
331
+ "$ref": "#/$defs/point",
332
+ "description": "x, y (and z), in N"
333
+ },
334
+ "case": {
335
+ "type": "string",
336
+ "description": "Its load case (default load)"
337
+ },
338
+ "teardrop": {
339
+ "enum": [
340
+ "-z",
341
+ "+z"
342
+ ],
343
+ "description": "3D: a cylinder along x or y with a 45° point that way, so it prints without support: '-z' for a boss (its underside), '+z' for a hole (its roof)"
344
+ }
345
+ }
346
+ }
347
+ }
348
+ }