@rulecad/cad 0.7.1 → 0.7.3
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 +8 -2
- package/README.md +36 -2
- package/bin/cad.mjs +66 -7
- package/lib/optimise.mjs +71 -21
- package/package.json +3 -3
- package/schemas/object.schema.json +18 -2
- package/schemas/problem.schema.json +11 -3
package/AGENTS.md
CHANGED
|
@@ -90,8 +90,14 @@ variable says which rule it comes from. Follow these steps; they're what makes a
|
|
|
90
90
|
`"overhang"` to the way up it will print, so the result needs no supports, and give horizontal bosses and holes a
|
|
91
91
|
`teardrop` (`"down"`, `"up"`). Draw the part as it prints; if that isn't the problem's frame, give its `analysis` a
|
|
92
92
|
`rotate` and `move` back. Build with `v.shapes.optimisedSolid(...)` and `"engine": "manifold"`; look at the four views.
|
|
93
|
-
-
|
|
94
|
-
|
|
93
|
+
- Before reporting numbers for a final shape, verify them: give the `analysis` a smaller `cell` (solids: about a
|
|
94
|
+
third of the problem's) and check the stiffness has settled (`fea.settled`). Report the verified numbers, the safety
|
|
95
|
+
factor, and where the peak stress is.
|
|
96
|
+
- For a part that must not break (a lever, a pedal), give its problem a `"stress"` limit (the material's strength
|
|
97
|
+
over a safety factor) instead of a `"volume"`: the lightest layout under it. Then verify it on finer cells.
|
|
98
|
+
- Mark a problem `"critical": true` if the part could hurt someone if it broke. Say plainly that the analysis is a
|
|
99
|
+
design aid and the material values are data-sheet figures: such a part needs testing, recorded under
|
|
100
|
+
`"verification"`, not just a check.
|
|
95
101
|
|
|
96
102
|
## Talking to the person
|
|
97
103
|
- Give links as one labelled line (`npx cad link <project>/<object> --md`), never a raw URL. If it says
|
package/README.md
CHANGED
|
@@ -357,6 +357,12 @@ with numbers as expressions like an object's (schema: `schemas/problem.schema.js
|
|
|
357
357
|
`ss304`, `ti64` come with rulecad. Printed values vary: measure yours.
|
|
358
358
|
- **Settings:** `volume`, the share of the space to fill; `cell`, the grid (smaller is finer and slower: a 140 × 40
|
|
359
359
|
grid takes about half a minute); `filter`, about the thinnest member, in mm.
|
|
360
|
+
- **Or a stress limit instead of a volume:** `"stress": "pla.strength / 3"` (MPa) finds the lightest layout that keeps
|
|
361
|
+
every cell's von Mises stress under it, which rounds off the sharp inside corners where cracks start. It takes about
|
|
362
|
+
a thousand steps, each with two solves, so it's slower: give it a coarse cell first. Give supports and loads some
|
|
363
|
+
area (a hole's edge, a pad), as stress where a load meets a point has no limit. `cad optimise` reports the peak
|
|
364
|
+
stress against the limit. Check the final part with an `analysis` on a finer `cell`: a sharp corner that's
|
|
365
|
+
within the limit on the optimiser's cells can still be over it on finer ones.
|
|
360
366
|
- **Variants**, picked as `name:variant`, set variables that have a tweak range, as an object's do.
|
|
361
367
|
|
|
362
368
|
`cad optimise <project>/<problem>` runs it, reports how far each load case moves its load and the stiffness that
|
|
@@ -420,8 +426,36 @@ the problem, and optionally a limit:
|
|
|
420
426
|
`cad check` then reports, for each load case, how far the part moves its load, its stiffness (N/mm) and its peak
|
|
421
427
|
stress against the material's strength, and the part's volume and weight. With `max_deflection` a case that moves
|
|
422
428
|
further fails; with `volume` a part whose volume is further than `tolerance` (a share) from it fails. A picture goes in
|
|
423
|
-
`.preview/`.
|
|
424
|
-
|
|
429
|
+
`.preview/`.
|
|
430
|
+
|
|
431
|
+
On the problem's own cells the analysis is quick and coarse. A solid part's cubes are filled by the share of each the
|
|
432
|
+
part takes up, so a wall between cell centres still counts, but thin walls on big cubes still come out too stiff when
|
|
433
|
+
they bend. To check a final shape, give the analysis a smaller `cell`:
|
|
434
|
+
|
|
435
|
+
```json
|
|
436
|
+
"analysis": [{ "problem": "bracket", "cell": 0.8, "min_safety": 3 }]
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
The part is then analysed on those cells and again on cells a quarter bigger. For each load case, `cad check`
|
|
440
|
+
reports:
|
|
441
|
+
- **Stiffness and its change:** under 5% from the bigger cells and it has settled; more, and the cells are too big.
|
|
442
|
+
- **Peak stress, where it is, and the safety factor:** against the material's strength (its weaker one across a
|
|
443
|
+
print's layers, where the rule set has `strength_z`), and its fatigue strength where it has one. With
|
|
444
|
+
`min_safety`, a case below it fails. Peak stress at a sharp inside corner keeps rising as cells shrink, so read it
|
|
445
|
+
with its change.
|
|
446
|
+
- **The largest movement anywhere, and where.**
|
|
447
|
+
|
|
448
|
+
A report goes in `.preview/` (`<object>-report-<problem>.md`, and `.json`), with what the analysis doesn't cover. A
|
|
449
|
+
solid's analysis is kept in `.cache/analysis/`, so it runs once.
|
|
450
|
+
|
|
451
|
+
**Safety-critical parts.** A problem with `"critical": true` (a pedal, a lever, a bracket that holds people) marks
|
|
452
|
+
every part analysed under it as unverified, until a test or an independent analysis is recorded in the object:
|
|
453
|
+
|
|
454
|
+
```json
|
|
455
|
+
"verification": [{ "kind": "test", "date": "2026-11-02", "by": "J. Smith", "summary": "20 N straight down, three prints: 0.21 mm, 95 N/mm", "source": "results.json" }]
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
The analysis is a design aid, not engineering sign-off: anything that could hurt someone if it failed needs testing.
|
|
425
459
|
|
|
426
460
|
## Boards
|
|
427
461
|
|
package/bin/cad.mjs
CHANGED
|
@@ -125,7 +125,7 @@ async function optimiseProblem(ref) {
|
|
|
125
125
|
if (live) process.stderr.write('\r\x1b[K');
|
|
126
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
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}` : ''}`];
|
|
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}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}`];
|
|
129
129
|
let out;
|
|
130
130
|
if (r.dim === 3) {
|
|
131
131
|
out = paths.preview(project, `${name.replace(':', '-')}-optimised.png`);
|
|
@@ -139,6 +139,7 @@ async function optimiseProblem(ref) {
|
|
|
139
139
|
if (opt('json')) return console.log(JSON.stringify((({ density, history, mesh, ...x }) => x)(r), null, 2));
|
|
140
140
|
console.log(`${r.title}${r.cached ? ' (cached)' : ` (${fmt(r.seconds)} s)`}`);
|
|
141
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.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)' : ''}`);
|
|
142
143
|
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
144
|
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
145
|
console.log(` ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? ', settled' : ': stopped before it settled (raise steps)'}`);
|
|
@@ -157,6 +158,28 @@ function place(triangles, [rx, ry, rz], move) {
|
|
|
157
158
|
}));
|
|
158
159
|
}
|
|
159
160
|
|
|
161
|
+
// A part's analysis report, in Markdown: what was analysed, how, each load case's numbers and where, and what it
|
|
162
|
+
// doesn't cover
|
|
163
|
+
function reportText({ turn, object, title, version, a, r, m, strength, weaker, grid, limit, minSafety, records, found }) {
|
|
164
|
+
const at = (p) => `(${p.map(fmt).join(', ')})`;
|
|
165
|
+
const pct = (x) => `${x >= 0 ? '+' : ''}${fmt(x * 100)}%`;
|
|
166
|
+
const rows = r.cases.map((c) => `| ${c.name} | ${fmt(c.force)} | ${sig(c.deflection)} | ${sig(c.stiffness)}${c.change ? ` (${pct(c.change.stiffness)})` : ''} | ${sig(c.stress)}${c.change ? ` (${pct(c.change.stress)})` : ''} at ${at(c.stressAt)} | ${strength ? `${sig(strength / c.stress)}×` : '–'}${m.fatigue ? ` (fatigue ${sig(m.fatigue / c.stress)}×)` : ''} | ${sig(c.movement)} at ${at(c.movementAt)} |`);
|
|
167
|
+
return [
|
|
168
|
+
`# ${title}: analysed under ${a.problem}`, '',
|
|
169
|
+
`${object} ${version || ''}. Analysed on ${grid}, ${m.name} (modulus ${fmt(m.modulus)} MPa${strength ? `, strength ${fmt(strength)} MPa${weaker ? ' across its layers' : ''}` : ''}${m.fatigue ? `, fatigue strength ${fmt(m.fatigue)} MPa` : ''}). Positions are in mm, in the problem's frame${turn ? ' (the part turned back from how it prints)' : ''}.${r.cases[0]?.change ? ` In brackets: the change from ${fmt(r.cases[0].change.cell)} mm cells. Stiffness that changes by 5% or less has settled; peak stress at a sharp inside corner keeps rising as cells shrink, so read it with its change.` : ' On the problem\'s own cells: a quick check. Give the analysis a smaller cell to verify it.'}`, '',
|
|
170
|
+
'| Load case | Force (N) | Moves its load (mm) | Stiffness (N/mm) | Peak stress (MPa) | Safety factor | Largest movement (mm) |',
|
|
171
|
+
'|---|---|---|---|---|---|---|', ...rows, '',
|
|
172
|
+
`Volume ${fmt(r.volume)} mm³.${limit != null ? ` Limit on movement: ${fmt(limit)} mm.` : ''}${minSafety != null ? ` Least safety factor: ${fmt(minSafety)}×.` : ''}`, '',
|
|
173
|
+
'## Findings', '', ...found.map((f) => `- ${f.level}: ${f.text}`), '',
|
|
174
|
+
'## Verification', '',
|
|
175
|
+
...(records.length ? records.map((v) => `- ${v.kind}, ${v.date}${v.by ? `, by ${v.by}` : ''}: ${v.summary}${v.source ? ` (${v.source})` : ''}`) : [r.critical ? '**Unverified.** This part is safety-critical: do not rely on it until a test or an independent analysis is recorded.' : 'None recorded.']), '',
|
|
176
|
+
'## What this doesn\'t cover', '',
|
|
177
|
+
'- The analysis is linear and static, on cubes: a design aid, not engineering sign-off. Stress at sharp inside corners, and where supports and loads are applied, depends on the cell size; compare a finer cell before trusting a peak.',
|
|
178
|
+
'- Material values are data-sheet figures. Printed parts vary with the printer, settings and spool, and are weaker across their layers; measure your own.',
|
|
179
|
+
'- Buckling, impact, creep, heat and wear are not checked.', '',
|
|
180
|
+
].join('\n');
|
|
181
|
+
}
|
|
182
|
+
|
|
160
183
|
async function analyses(b, d, tag) {
|
|
161
184
|
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; };
|
|
162
185
|
const all = [];
|
|
@@ -165,25 +188,61 @@ async function analyses(b, d, tag) {
|
|
|
165
188
|
if (!part) return [{ level: 'fail', text: `analysis: no part "${a.part}"`, code: 'fea.part' }];
|
|
166
189
|
// A part drawn in its print orientation, turned back into the problem's frame: rotated (degrees about x, then y,
|
|
167
190
|
// then z, as JSCAD's rotate), then moved
|
|
168
|
-
const
|
|
169
|
-
const
|
|
191
|
+
const turn = (a.rotate || []).map((x) => evaluate(x, lookup)).some(Boolean) || (a.move || []).map((x) => evaluate(x, lookup)).some(Boolean);
|
|
192
|
+
const turned = turn ? place(part.triangles, (a.rotate || [0, 0, 0]).map((x) => evaluate(x, lookup)), (a.move || [0, 0, 0]).map((x) => evaluate(x, lookup))) : part.triangles;
|
|
193
|
+
const cell = a.cell != null ? evaluate(a.cell, lookup) : undefined;
|
|
194
|
+
const r = await analysePart(turned, d.project, a.problem, { cell }), m = r.material;
|
|
195
|
+
// A check of the check: with a cell given, the part is analysed again on cells a quarter bigger, and how much each
|
|
196
|
+
// number changes says whether the cells are small enough. Peak stress at a sharp inside corner never settles (in
|
|
197
|
+
// theory it's endless there), so it's reported, not judged.
|
|
198
|
+
if (cell) {
|
|
199
|
+
const coarser = await analysePart(turned, d.project, a.problem, { cell: cell * 1.25 });
|
|
200
|
+
r.cases.forEach((c, n) => { const o = coarser.cases[n]; c.change = { stiffness: c.stiffness / o.stiffness - 1, stress: c.stress / o.stress - 1, cell: coarser.grid.h }; });
|
|
201
|
+
}
|
|
202
|
+
const limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
|
|
203
|
+
const minSafety = a.min_safety != null ? evaluate(a.min_safety, lookup) : null;
|
|
170
204
|
let out = null;
|
|
171
205
|
if (r.dim !== 3) { // a flat part's picture: its cells as analysed, with the supports and loads
|
|
172
206
|
out = paths.preview(d.project, `${d.name}${tag}-analysis-${a.problem.replace(':', '-')}.svg`);
|
|
173
207
|
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
174
208
|
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`) }));
|
|
175
209
|
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
210
|
+
// Safety factors: against the material's strength (its weaker one across a print's layers, where it has one), and
|
|
211
|
+
// its fatigue strength where it has one
|
|
212
|
+
const strength = m.strength ? Math.min(m.strength, m.strength_z ?? Infinity) : null, weaker = m.strength_z != null && m.strength_z < m.strength;
|
|
213
|
+
const grid = `${[r.grid.nx, r.grid.ny, r.grid.nz].filter(Boolean).join(' × ')} cells of ${fmt(r.grid.h)} mm`;
|
|
214
|
+
const at = (p) => `(${p.map(fmt).join(', ')})`;
|
|
215
|
+
const found = r.cases.flatMap((c) => {
|
|
216
|
+
const safety = strength ? strength / c.stress : null, fatigue = m.fatigue ? m.fatigue / c.stress : null;
|
|
217
|
+
const text = `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm`;
|
|
179
218
|
const values = { deflection: c.deflection, force: c.force, stiffness: c.stiffness, stress: c.stress, ...(limit != null ? { limit } : {}) };
|
|
180
|
-
|
|
219
|
+
const refs = { problem: a.problem, part: part.name, ...(out ? { picture: path.relative(WS, out) } : {}) };
|
|
220
|
+
const strong = `peak stress ${sig(c.stress)} MPa at ${at(c.stressAt)}${safety != null ? `: ${sig(safety)}× under ${m.name}'s ${weaker ? 'strength across its layers' : 'strength'}${fatigue != null ? `, ${sig(fatigue)}× under its fatigue strength` : ''}` : ''}`;
|
|
221
|
+
const least = Math.min(safety ?? Infinity, fatigue ?? Infinity);
|
|
222
|
+
const settled = c.change ? [{ level: Math.abs(c.change.stiffness) <= 0.05 ? 'pass' : 'warn', code: 'fea.settled', values: c.change,
|
|
223
|
+
text: `${a.problem} ${c.name}: stiffness ${c.change.stiffness >= 0 ? '+' : ''}${fmt(c.change.stiffness * 100)}% from ${fmt(c.change.cell)} mm cells${Math.abs(c.change.stiffness) <= 0.05 ? ', settled (within 5%)' : ': not settled, use a smaller cell'}` }] : [];
|
|
224
|
+
return [
|
|
225
|
+
{ level: limit == null ? 'info' : c.deflection <= limit ? 'pass' : 'fail', text: limit == null ? text : `${text} (at most ${fmt(limit)})`, code: 'fea.deflection', values, refs }, ...settled,
|
|
226
|
+
{ level: minSafety == null ? 'info' : least >= minSafety ? 'pass' : 'fail', text: `${a.problem} ${c.name}: ${strong}${minSafety != null ? ` (at least ${fmt(minSafety)}×)` : ''}`, code: 'fea.strength',
|
|
227
|
+
values: { stress: c.stress, at: c.stressAt, ...(safety != null ? { safety } : {}), ...(fatigue != null ? { fatigue } : {}), ...(minSafety != null ? { min: minSafety } : {}) }, refs },
|
|
228
|
+
];
|
|
181
229
|
});
|
|
182
230
|
const grams = m.density ? ` (${fmt((r.volume / 1000) * m.density)} g of ${m.name})` : '';
|
|
183
231
|
if (a.volume != null) {
|
|
184
232
|
const want = evaluate(a.volume, lookup), tol = a.tolerance ?? 0.01, off = (r.volume - want) / want;
|
|
185
233
|
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 } });
|
|
186
234
|
} else found.push({ level: 'info', text: `volume ${fmt(r.volume)} mm³${grams}`, code: 'fea.volume', values: { volume: r.volume } });
|
|
235
|
+
// A safety-critical part stays unverified until a test or an independent analysis is recorded against it
|
|
236
|
+
const records = b.object.verification || [];
|
|
237
|
+
if (r.critical) found.push(records.length
|
|
238
|
+
? { level: 'pass', text: `${a.problem} is safety-critical: verified by ${records.map((v) => `${v.kind} (${v.date})`).join(', ')}`, code: 'fea.verified', values: { records } }
|
|
239
|
+
: { level: 'warn', text: `${a.problem} is safety-critical and unverified: rulecad's analysis is a design aid. Test it, or have it analysed independently, and record that under "verification"`, code: 'fea.unverified' });
|
|
240
|
+
// The report: everything above, with where, written next to the previews
|
|
241
|
+
const report = paths.preview(d.project, `${d.name}${tag}-report-${a.problem.replace(':', '-')}.md`);
|
|
242
|
+
fs.mkdirSync(path.dirname(report), { recursive: true });
|
|
243
|
+
fs.writeFileSync(report, reportText({ turn, object: `${d.project}/${d.name}${tag}`, title: b.object.title || d.name, version: b.object.version, a, r, m, strength, weaker, grid, limit, minSafety, records, found }));
|
|
244
|
+
fs.writeFileSync(report.replace(/\.md$/, '.json'), JSON.stringify({ object: `${d.project}/${d.name}${tag}`, version: b.object.version, problem: a.problem, critical: r.critical, verification: records, material: { name: m.name, modulus: m.modulus, strength: m.strength, ...(m.strength_z != null ? { strength_z: m.strength_z } : {}), ...(m.fatigue != null ? { fatigue: m.fatigue } : {}) }, grid: r.grid, volume: r.volume, cases: r.cases, findings: found.map(({ level, code, text }) => ({ level, code, text })) }, null, 2) + '\n');
|
|
245
|
+
found.push({ level: 'info', text: `report (${grid}): ${path.relative(WS, report)}`, code: 'fea.report', refs: { report: path.relative(WS, report) } });
|
|
187
246
|
return found;
|
|
188
247
|
})());
|
|
189
248
|
return all;
|
package/lib/optimise.mjs
CHANGED
|
@@ -67,7 +67,7 @@ export async function readProblem(project, ref) {
|
|
|
67
67
|
supports: await Promise.all(p.supports.map(async (s) => ({ ...(await region(s)), fix: s.fix || 'xyz'.slice(0, dim) }))),
|
|
68
68
|
loads: await Promise.all(p.loads.map(async (l) => ({ ...(await region(l)), force: pt(l.force), case: l.case || 'load' }))),
|
|
69
69
|
cases: Object.fromEntries(Object.entries(p.cases || {}).map(([k, w]) => [k, ev(w)])),
|
|
70
|
-
material: { E: m.modulus, nu: m.poisson }, ...(dim === 2 ? { thickness: ev(p.thickness) } : {}), cell: ev(p.cell), volume: ev(p.volume),
|
|
70
|
+
material: { E: m.modulus, nu: m.poisson }, ...(dim === 2 ? { thickness: ev(p.thickness) } : {}), cell: ev(p.cell), ...(p.volume != null ? { volume: ev(p.volume) } : {}), ...(p.stress != null ? { stress: ev(p.stress) } : {}),
|
|
71
71
|
...(p.filter != null ? { filter: ev(p.filter) } : {}), ...(p.penal != null ? { penal: ev(p.penal) } : {}),
|
|
72
72
|
...(p.projection != null ? { projection: p.projection } : {}), ...(p.steps != null ? { steps: p.steps } : {}),
|
|
73
73
|
...(overhang && overhang !== 'none' ? { overhang } : {}),
|
|
@@ -76,7 +76,7 @@ export async function readProblem(project, ref) {
|
|
|
76
76
|
const outline = { smooth: p.outline?.smooth ?? 4, minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2 };
|
|
77
77
|
// A printable solid's surface is kept within the printer's overhang limit too (smoothing can tip faces past it)
|
|
78
78
|
if (dim === 3 && problem.overhang) { const n = printerOf(project), pr = resolve({ uses: [n] }).values[n]; outline.overhang = { up: problem.overhang, angle: pr?.overhang ?? 45 }; }
|
|
79
|
-
return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline };
|
|
79
|
+
return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline, critical: !!p.critical };
|
|
80
80
|
}
|
|
81
81
|
|
|
82
82
|
/**
|
|
@@ -115,7 +115,7 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
|
|
|
115
115
|
const result = {
|
|
116
116
|
problem: ref, title: r.title, hash, dim: r.dim, material: r.material.name, ...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
|
|
117
117
|
grid: spec.grid, origin: spec.origin, regions: { keep: named(spec.regions.keep), avoid: named(spec.regions.avoid) }, ...shape,
|
|
118
|
-
volume: o.volume, compliance: o.compliance, cases: o.cases, overhang: r.problem.overhang || null,
|
|
118
|
+
volume: o.volume, compliance: o.compliance, cases: o.cases, ...(o.stress ? { stress: o.stress } : {}), overhang: r.problem.overhang || null,
|
|
119
119
|
steps: o.steps, converged: o.converged, seconds: o.seconds, history: o.history, density: Array.from(o.density, (d) => round(d, 3)),
|
|
120
120
|
supports: named(r.problem.supports), loads: named(r.problem.loads),
|
|
121
121
|
};
|
|
@@ -136,12 +136,20 @@ export const forDesign = ({ density, history, ...r }) => r;
|
|
|
136
136
|
/**
|
|
137
137
|
* Analyse a part under a problem's supports and loads, on its grid. A flat part (2D problem: triangles, z up, the
|
|
138
138
|
* plate lying on the bed): each cell is as solid as the share of the problem's thickness the part fills above it. A
|
|
139
|
-
* solid part (3D): each cube is solid if its centre is inside the part.
|
|
139
|
+
* solid part (3D): each cube is solid if its centre is inside the part. Each load case reports how far it moves its load
|
|
140
|
+
* (and the stiffness), the largest stress and where, and the largest movement anywhere and where.
|
|
140
141
|
* @param {number[][][]} triangles @param {string} project @param {string} ref
|
|
142
|
+
* @param {{ cell?: number }} [options] cell: a finer cell size than the problem's, to check a final shape
|
|
141
143
|
*/
|
|
142
|
-
export async function analysePart(triangles, project, ref) {
|
|
143
|
-
const r = await readProblem(project, ref), { problem } = r, h = problem.cell;
|
|
144
|
-
if (r.dim === 3)
|
|
144
|
+
export async function analysePart(triangles, project, ref, { cell } = {}) {
|
|
145
|
+
const r = await readProblem(project, ref), { problem } = r, h = cell || problem.cell;
|
|
146
|
+
if (r.dim === 3) { // kept: a fine analysis of a solid takes minutes
|
|
147
|
+
const file = paths.cache('analysis', `${crypto.createHash('sha256').update(JSON.stringify([VERSION, triangles, problem, h, source('@rulecad/topopt'), source('@rulecad/fea'), fs.readFileSync(new URL(import.meta.url), 'utf8')])).digest('hex')}.json`);
|
|
148
|
+
if (!process.env.CAD_NO_CACHE && host.exists(file)) { const { density, ...x } = JSON.parse(host.readText(file)); return { ...x, density: Float64Array.from(density) }; }
|
|
149
|
+
const out = analyseSolid(triangles, r, h);
|
|
150
|
+
host.writeText(file, JSON.stringify({ ...out, density: Array.from(out.density) }));
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
145
153
|
// The grid covers the part and the problem's space
|
|
146
154
|
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
|
|
147
155
|
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); }
|
|
@@ -168,28 +176,70 @@ export async function analysePart(triangles, project, ref) {
|
|
|
168
176
|
const a = analyse({ grid: g, density, material: problem.material, thickness: problem.thickness, fixed, loads });
|
|
169
177
|
const cases = names.map((name, c) => {
|
|
170
178
|
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]));
|
|
171
|
-
|
|
172
|
-
let most = 0;
|
|
173
|
-
for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) most = Math.max(most, a.stress[c][e]);
|
|
174
|
-
return { name, force: size, deflection, stiffness: deflection ? size / deflection : Infinity, stress: most };
|
|
179
|
+
return measures(name, size, a, c, density, { nx, ny, nz: 1, h }, [x0, y0]);
|
|
175
180
|
});
|
|
176
|
-
return { problem: ref, material: r.material, cases, volume: volume(triangles), grid: { nx, ny, h }, origin: [x0, y0], density };
|
|
181
|
+
return { problem: ref, dim: 2, material: r.material, critical: r.critical, cases, volume: volume(triangles), grid: { nx, ny, h }, origin: [x0, y0], density };
|
|
177
182
|
}
|
|
178
183
|
|
|
179
184
|
// A solid part on the problem's grid: the part itself is the space (keep and avoid regions don't apply), so the
|
|
180
185
|
// supports and loads land on it as they would on an optimised layout
|
|
181
|
-
function analyseSolid(triangles, r) {
|
|
182
|
-
const { problem } = r, spec = discretise({ ...problem, space: { triangles }, keep: [], avoid: [], volume: 1 });
|
|
183
|
-
const g = makeGrid(spec.grid), density =
|
|
186
|
+
function analyseSolid(triangles, r, cell) {
|
|
187
|
+
const { problem } = r, spec = discretise({ ...problem, cell, space: { triangles }, keep: [], avoid: [], volume: 1 });
|
|
188
|
+
const g = makeGrid(spec.grid), density = solidFill(triangles, spec.grid, spec.origin);
|
|
184
189
|
if (!density.some((d) => d)) throw new Error('the part is smaller than one cell of the problem: use a smaller cell');
|
|
185
190
|
const a = analyse({ grid: g, density, material: problem.material, fixed: spec.fixed, loads: spec.loads.map((l) => l.force) });
|
|
186
|
-
const cases = spec.loads.map((l, c) =>
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
+
const cases = spec.loads.map((l, c) => measures(l.name, l.size, a, c, density, spec.grid, spec.origin));
|
|
192
|
+
return { problem: r.ref, dim: 3, material: r.material, critical: r.critical, cases, volume: volume(triangles), grid: spec.grid, origin: spec.origin, density };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// A load case's numbers: how far the load moves along itself (compliance over force) and the stiffness, the largest
|
|
196
|
+
// stress in the part and the centre of the cell it's in, and the largest movement of any point of the part and where
|
|
197
|
+
function measures(name, force, a, c, density, { nx, ny, h }, origin) {
|
|
198
|
+
const deflection = force ? a.compliance[c] / force : 0;
|
|
199
|
+
let most = 0, cellAt = 0;
|
|
200
|
+
for (let e = 0; e < density.length; e++) if (density[e] >= 0.5 && a.stress[c][e] > most) { most = a.stress[c][e]; cellAt = e; }
|
|
201
|
+
const index = [cellAt % nx, Math.floor(cellAt / nx) % ny, Math.floor(cellAt / (nx * ny))];
|
|
202
|
+
const stressAt = origin.map((o, q) => round(o + (index[q] + 0.5) * h, 2)), d = a.deflection[c];
|
|
203
|
+
return {
|
|
204
|
+
name, force, deflection, stiffness: deflection ? force / deflection : Infinity, stress: most, stressAt,
|
|
205
|
+
movement: d.most, movementAt: d.at.map((x, q) => round(x + origin[q], 2)),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// How much of each cube the part fills, from 0 to 1, so a wall between cell centres counts for what it is (a 6 mm
|
|
210
|
+
// plate on 2.5 mm cubes, solid only where a cube's centre is inside, is 5 mm thick, and bends 40% more). Rays run up
|
|
211
|
+
// through each column of cubes, n × n of them (exact up the column, to within half their spacing across it); each enters the part through a face facing down and leaves through
|
|
212
|
+
// one facing up, and the lengths inside each cube are averaged.
|
|
213
|
+
export function solidFill(triangles, { nx, ny, nz, h }, origin, n = 4) {
|
|
214
|
+
const R = nx * n, hits = Array.from({ length: R * ny * n }, () => []), jx = h * 1e-4 * Math.SQRT2, jy = h * 1e-4 * Math.PI;
|
|
215
|
+
for (const [a, b, c] of triangles) {
|
|
216
|
+
const d = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
|
217
|
+
if (Math.abs(d) < 1e-12) continue; // a wall: the ray runs alongside it
|
|
218
|
+
const i0 = Math.max(0, Math.floor(((Math.min(a[0], b[0], c[0]) - origin[0]) / h) * n - 1)), i1 = Math.min(R - 1, Math.ceil(((Math.max(a[0], b[0], c[0]) - origin[0]) / h) * n));
|
|
219
|
+
const j0 = Math.max(0, Math.floor(((Math.min(a[1], b[1], c[1]) - origin[1]) / h) * n - 1)), j1 = Math.min(ny * n - 1, Math.ceil(((Math.max(a[1], b[1], c[1]) - origin[1]) / h) * n));
|
|
220
|
+
for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
|
|
221
|
+
const x = origin[0] + ((i + 0.5) / n) * h + jx, y = origin[1] + ((j + 0.5) / n) * h + jy;
|
|
222
|
+
const w0 = ((b[0] - x) * (c[1] - y) - (b[1] - y) * (c[0] - x)) / d, w1 = ((c[0] - x) * (a[1] - y) - (c[1] - y) * (a[0] - x)) / d, w2 = 1 - w0 - w1;
|
|
223
|
+
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
|
|
224
|
+
hits[j * R + i].push([w0 * a[2] + w1 * b[2] + w2 * c[2], Math.sign(d)]);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const density = new Float64Array(nx * ny * nz), share = 1 / (n * n * h);
|
|
228
|
+
hits.forEach((list, ray) => {
|
|
229
|
+
if (!list.length) return;
|
|
230
|
+
list.sort((p, q) => p[0] - q[0]);
|
|
231
|
+
const ci = Math.floor((ray % R) / n), cj = Math.floor(Math.floor(ray / R) / n);
|
|
232
|
+
let depth = 0, from = 0;
|
|
233
|
+
for (const [z, sign] of list) {
|
|
234
|
+
const was = depth; depth -= sign; // a face facing down (its normal's z below 0, counter-clockwise from above: sign -1) is the way in
|
|
235
|
+
if (was <= 0 && depth > 0) from = z;
|
|
236
|
+
else if (was > 0 && depth <= 0) for (let k = Math.max(0, Math.floor((from - origin[2]) / h)); k < nz && origin[2] + k * h < z; k++) {
|
|
237
|
+
const lo = Math.max(from, origin[2] + k * h), hi = Math.min(z, origin[2] + (k + 1) * h);
|
|
238
|
+
if (hi > lo) density[(k * ny + cj) * nx + ci] += (hi - lo) * share;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
191
241
|
});
|
|
192
|
-
return
|
|
242
|
+
return density.map((x) => Math.min(1, x));
|
|
193
243
|
}
|
|
194
244
|
|
|
195
245
|
// How much of the thickness the part fills over each cell's centre: a ray straight up through the part enters it
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/cad",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.3",
|
|
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": {
|
|
@@ -54,8 +54,8 @@
|
|
|
54
54
|
"@rulecad/rules": "^0.3.0",
|
|
55
55
|
"@jscad/modeling": "^2.12.0",
|
|
56
56
|
"three": "^0.186.1",
|
|
57
|
-
"@rulecad/fea": "^0.2.
|
|
58
|
-
"@rulecad/topopt": "^0.2.
|
|
57
|
+
"@rulecad/fea": "^0.2.1",
|
|
58
|
+
"@rulecad/topopt": "^0.2.2"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
61
|
"@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0"
|
|
@@ -25,7 +25,21 @@
|
|
|
25
25
|
"variants": { "type": "object", "additionalProperties": { "type": "object" } },
|
|
26
26
|
"anchors": { "type": "object", "additionalProperties": { "$ref": "#/$defs/anchor" } },
|
|
27
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
|
+
"analysis": { "type": "array", "items": { "$ref": "#/$defs/analysis" }, "description": "Checks of how the part bends under a problem's loads (cad check)" },
|
|
29
|
+
"verification": {
|
|
30
|
+
"type": "array",
|
|
31
|
+
"description": "Tests or independent analyses of the part: a safety-critical part's analysis stays unverified without one",
|
|
32
|
+
"items": {
|
|
33
|
+
"type": "object", "required": ["kind", "date", "summary"], "additionalProperties": false,
|
|
34
|
+
"properties": {
|
|
35
|
+
"kind": { "enum": ["test", "analysis"], "description": "test: the part was loaded and measured; analysis: someone else analysed it independently" },
|
|
36
|
+
"date": { "type": "string" },
|
|
37
|
+
"by": { "type": "string" },
|
|
38
|
+
"summary": { "type": "string", "description": "What was done and what it showed, with numbers" },
|
|
39
|
+
"source": { "type": "string", "description": "Where the record is: a results file, a report, a link" }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
29
43
|
},
|
|
30
44
|
"$defs": {
|
|
31
45
|
"expr": { "type": ["number", "string"] },
|
|
@@ -61,7 +75,9 @@
|
|
|
61
75
|
"volume": { "$ref": "#/$defs/expr", "description": "Fail if the part's volume differs from this (mm³) by more than tolerance" },
|
|
62
76
|
"tolerance": { "type": "number", "description": "For volume: the share it may differ by (default 0.01)" },
|
|
63
77
|
"rotate": { "type": "array", "items": { "$ref": "#/$defs/expr" }, "minItems": 3, "maxItems": 3, "description": "Turns the part into the problem's frame first, for a part drawn as it prints: degrees about x, then y, then z (as JSCAD's rotate)" },
|
|
64
|
-
"move": { "type": "array", "items": { "$ref": "#/$defs/expr" }, "minItems": 2, "maxItems": 3, "description": "Then moves it, in mm" }
|
|
78
|
+
"move": { "type": "array", "items": { "$ref": "#/$defs/expr" }, "minItems": 2, "maxItems": 3, "description": "Then moves it, in mm" },
|
|
79
|
+
"cell": { "$ref": "#/$defs/expr", "description": "Analyse on cells this size (mm) rather than the problem's: finer, to check a final shape" },
|
|
80
|
+
"min_safety": { "$ref": "#/$defs/expr", "description": "Fail if any load case's safety factor (strength, or fatigue strength where the material has one, over the peak stress) is below this" }
|
|
65
81
|
}
|
|
66
82
|
},
|
|
67
83
|
"part": {
|
|
@@ -7,7 +7,6 @@
|
|
|
7
7
|
"required": [
|
|
8
8
|
"material",
|
|
9
9
|
"cell",
|
|
10
|
-
"volume",
|
|
11
10
|
"space",
|
|
12
11
|
"supports",
|
|
13
12
|
"loads"
|
|
@@ -55,7 +54,11 @@
|
|
|
55
54
|
},
|
|
56
55
|
"volume": {
|
|
57
56
|
"$ref": "#/$defs/expr",
|
|
58
|
-
"description": "The share of the space to fill, 0 to 1 (keep regions count towards it)"
|
|
57
|
+
"description": "The share of the space to fill, 0 to 1 (keep regions count towards it): the stiffest layout that fills it. Give this or a stress limit"
|
|
58
|
+
},
|
|
59
|
+
"stress": {
|
|
60
|
+
"$ref": "#/$defs/expr",
|
|
61
|
+
"description": "A limit on von Mises stress (MPa), such as \"pla.strength / 3\": the lightest layout that keeps every cell under it (Senhora et al. 2020). Give this or a volume"
|
|
59
62
|
},
|
|
60
63
|
"filter": {
|
|
61
64
|
"$ref": "#/$defs/expr",
|
|
@@ -136,6 +139,10 @@
|
|
|
136
139
|
}
|
|
137
140
|
}
|
|
138
141
|
},
|
|
142
|
+
"critical": {
|
|
143
|
+
"type": "boolean",
|
|
144
|
+
"description": "Safety-critical (a pedal, a lever, a bracket that holds people): parts analysed under it are reported unverified until a test or an independent analysis is recorded against them"
|
|
145
|
+
},
|
|
139
146
|
"overhang": {
|
|
140
147
|
"type": "string",
|
|
141
148
|
"description": "3D: printable this way up ('+z', '-y', …), or a variable holding it, or 'none': only material supported from below at 45° or less"
|
|
@@ -335,5 +342,6 @@
|
|
|
335
342
|
}
|
|
336
343
|
}
|
|
337
344
|
}
|
|
338
|
-
}
|
|
345
|
+
},
|
|
346
|
+
"anyOf": [{ "required": ["volume"] }, { "required": ["stress"] }]
|
|
339
347
|
}
|