@rulecad/cad 0.7.0 → 0.7.2

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
@@ -88,9 +88,14 @@ variable says which rule it comes from. Follow these steps; they're what makes a
88
88
  `analysis` to the object so `cad check` reports its stiffness; report those numbers with their load and material.
89
89
  - Solid parts (brackets, joints) are 3D problems: regions with a z, a named part as the space if it helps. Set
90
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.
91
+ `teardrop` (`"down"`, `"up"`). Draw the part as it prints; if that isn't the problem's frame, give its `analysis` a
92
+ `rotate` and `move` back. Build with `v.shapes.optimisedSolid(...)` and `"engine": "manifold"`; look at the four views.
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
+ - Mark a problem `"critical": true` if the part could hurt someone if it broke. Say plainly that the analysis is a
97
+ design aid and the material values are data-sheet figures: such a part needs testing, recorded under
98
+ `"verification"`, not just a check.
94
99
 
95
100
  ## Talking to the person
96
101
  - Give links as one labelled line (`npx cad link <project>/<object> --md`), never a raw URL. If it says
package/README.md CHANGED
@@ -382,8 +382,9 @@ holes come out true.
382
382
 
383
383
  A problem whose regions have a z is solid. It has no thickness, and takes more kinds of region:
384
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.
385
+ - **A cylinder:** `r`, `length` and `axis`. It can be a teardrop: `"teardrop": "down"` for a boss, `"up"` for a
386
+ hole. It gets a 45° point that way, so it prints. Up is the problem's `overhang` (+z when it's free), so the same
387
+ problem prints either way up; `"+y"` and the like point it a fixed way. Along its axis, it has no point.
387
388
  - **A ball:** `r`.
388
389
  - **A named part of another design in the project:** `{ "part": "envelope.body" }`.
389
390
 
@@ -392,8 +393,17 @@ without supports standing that way up (a variable holding `"+z"` or `"none"` wor
392
393
 
393
394
  `cad optimise` draws the result's four views in `.preview/`. A design builds the result with
394
395
  `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.
396
+ regions exactly. The surface is a big mesh, so set the object's `"engine": "manifold"`. With `"overhang"` set, the
397
+ surface is also kept within the printer's overhang limit: faces smoothing tipped past it are tipped back. An
398
+ `analysis` of a solid part voxelises it on the problem's grid.
399
+
400
+ A part prints in one orientation and is loaded in another. Draw it as it prints, and turn it back for its analysis:
401
+ `"rotate"` (degrees about x, then y, then z, as JSCAD's `rotate`) then `"move"` (mm) put it in the problem's frame.
402
+ Both take expressions, so a variant can lie the part down:
403
+
404
+ ```json
405
+ "analysis": [{ "problem": "bracket", "rotate": ["0 - 90 * side", 0, 0], "move": [0, "0 - side * bench.bracket_h / 2", 0] }]
406
+ ```
397
407
 
398
408
  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
409
  optimisation takes a few minutes. The result is kept, so it's worked out once.
@@ -410,8 +420,36 @@ the problem, and optionally a limit:
410
420
  `cad check` then reports, for each load case, how far the part moves its load, its stiffness (N/mm) and its peak
411
421
  stress against the material's strength, and the part's volume and weight. With `max_deflection` a case that moves
412
422
  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.
423
+ `.preview/`.
424
+
425
+ 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
426
+ part takes up, so a wall between cell centres still counts, but thin walls on big cubes still come out too stiff when
427
+ they bend. To check a final shape, give the analysis a smaller `cell`:
428
+
429
+ ```json
430
+ "analysis": [{ "problem": "bracket", "cell": 0.8, "min_safety": 3 }]
431
+ ```
432
+
433
+ The part is then analysed on those cells and again on cells a quarter bigger. For each load case, `cad check`
434
+ reports:
435
+ - **Stiffness and its change:** under 5% from the bigger cells and it has settled; more, and the cells are too big.
436
+ - **Peak stress, where it is, and the safety factor:** against the material's strength (its weaker one across a
437
+ print's layers, where the rule set has `strength_z`), and its fatigue strength where it has one. With
438
+ `min_safety`, a case below it fails. Peak stress at a sharp inside corner keeps rising as cells shrink, so read it
439
+ with its change.
440
+ - **The largest movement anywhere, and where.**
441
+
442
+ A report goes in `.preview/` (`<object>-report-<problem>.md`, and `.json`), with what the analysis doesn't cover. A
443
+ solid's analysis is kept in `.cache/analysis/`, so it runs once.
444
+
445
+ **Safety-critical parts.** A problem with `"critical": true` (a pedal, a lever, a bracket that holds people) marks
446
+ every part analysed under it as unverified, until a test or an independent analysis is recorded in the object:
447
+
448
+ ```json
449
+ "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" }]
450
+ ```
451
+
452
+ The analysis is a design aid, not engineering sign-off: anything that could hurt someone if it failed needs testing.
415
453
 
416
454
  ## Boards
417
455
 
package/bin/cad.mjs CHANGED
@@ -146,30 +146,102 @@ async function optimiseProblem(ref) {
146
146
  }
147
147
 
148
148
  // An object's analyses for cad check: each problem's load cases on the part, and its volume against a target
149
+ function place(triangles, [rx, ry, rz], move) {
150
+ const [cx, sx, cy, sy, cz, sz] = [rx, ry, rz].flatMap((deg) => [Math.cos((deg * Math.PI) / 180), Math.sin((deg * Math.PI) / 180)]);
151
+ return triangles.map((t) => t.map((p) => {
152
+ let [x, y, z = 0] = p;
153
+ [y, z] = [y * cx - z * sx, y * sx + z * cx];
154
+ [x, z] = [x * cy + z * sy, -x * sy + z * cy];
155
+ [x, y] = [x * cz - y * sz, x * sz + y * cz];
156
+ return [x + move[0], y + move[1], z + (move[2] || 0)].slice(0, p.length);
157
+ }));
158
+ }
159
+
160
+ // A part's analysis report, in Markdown: what was analysed, how, each load case's numbers and where, and what it
161
+ // doesn't cover
162
+ function reportText({ turn, object, title, version, a, r, m, strength, weaker, grid, limit, minSafety, records, found }) {
163
+ const at = (p) => `(${p.map(fmt).join(', ')})`;
164
+ const pct = (x) => `${x >= 0 ? '+' : ''}${fmt(x * 100)}%`;
165
+ 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)} |`);
166
+ return [
167
+ `# ${title}: analysed under ${a.problem}`, '',
168
+ `${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.'}`, '',
169
+ '| Load case | Force (N) | Moves its load (mm) | Stiffness (N/mm) | Peak stress (MPa) | Safety factor | Largest movement (mm) |',
170
+ '|---|---|---|---|---|---|---|', ...rows, '',
171
+ `Volume ${fmt(r.volume)} mm³.${limit != null ? ` Limit on movement: ${fmt(limit)} mm.` : ''}${minSafety != null ? ` Least safety factor: ${fmt(minSafety)}×.` : ''}`, '',
172
+ '## Findings', '', ...found.map((f) => `- ${f.level}: ${f.text}`), '',
173
+ '## Verification', '',
174
+ ...(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.']), '',
175
+ '## What this doesn\'t cover', '',
176
+ '- 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.',
177
+ '- Material values are data-sheet figures. Printed parts vary with the printer, settings and spool, and are weaker across their layers; measure your own.',
178
+ '- Buckling, impact, creep, heat and wear are not checked.', '',
179
+ ].join('\n');
180
+ }
181
+
149
182
  async function analyses(b, d, tag) {
150
183
  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
184
  const all = [];
152
185
  for (const a of b.object.analysis || []) all.push(...await (async () => {
153
186
  const part = a.part ? b.parts.find((p) => p.name === a.part) : b.parts.find((p) => p.role !== 'support');
154
187
  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;
188
+ // A part drawn in its print orientation, turned back into the problem's frame: rotated (degrees about x, then y,
189
+ // then z, as JSCAD's rotate), then moved
190
+ const turn = (a.rotate || []).map((x) => evaluate(x, lookup)).some(Boolean) || (a.move || []).map((x) => evaluate(x, lookup)).some(Boolean);
191
+ 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;
192
+ const cell = a.cell != null ? evaluate(a.cell, lookup) : undefined;
193
+ const r = await analysePart(turned, d.project, a.problem, { cell }), m = r.material;
194
+ // A check of the check: with a cell given, the part is analysed again on cells a quarter bigger, and how much each
195
+ // number changes says whether the cells are small enough. Peak stress at a sharp inside corner never settles (in
196
+ // theory it's endless there), so it's reported, not judged.
197
+ if (cell) {
198
+ const coarser = await analysePart(turned, d.project, a.problem, { cell: cell * 1.25 });
199
+ 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 }; });
200
+ }
201
+ const limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
202
+ const minSafety = a.min_safety != null ? evaluate(a.min_safety, lookup) : null;
156
203
  let out = null;
157
204
  if (r.dim !== 3) { // a flat part's picture: its cells as analysed, with the supports and loads
158
205
  out = paths.preview(d.project, `${d.name}${tag}-analysis-${a.problem.replace(':', '-')}.svg`);
159
206
  fs.mkdirSync(path.dirname(out), { recursive: true });
160
207
  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
208
  }
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}`;
209
+ // Safety factors: against the material's strength (its weaker one across a print's layers, where it has one), and
210
+ // its fatigue strength where it has one
211
+ const strength = m.strength ? Math.min(m.strength, m.strength_z ?? Infinity) : null, weaker = m.strength_z != null && m.strength_z < m.strength;
212
+ const grid = `${[r.grid.nx, r.grid.ny, r.grid.nz].filter(Boolean).join(' × ')} cells of ${fmt(r.grid.h)} mm`;
213
+ const at = (p) => `(${p.map(fmt).join(', ')})`;
214
+ const found = r.cases.flatMap((c) => {
215
+ const safety = strength ? strength / c.stress : null, fatigue = m.fatigue ? m.fatigue / c.stress : null;
216
+ const text = `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm`;
165
217
  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) } : {}) } };
218
+ const refs = { problem: a.problem, part: part.name, ...(out ? { picture: path.relative(WS, out) } : {}) };
219
+ 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` : ''}` : ''}`;
220
+ const least = Math.min(safety ?? Infinity, fatigue ?? Infinity);
221
+ const settled = c.change ? [{ level: Math.abs(c.change.stiffness) <= 0.05 ? 'pass' : 'warn', code: 'fea.settled', values: c.change,
222
+ 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'}` }] : [];
223
+ return [
224
+ { level: limit == null ? 'info' : c.deflection <= limit ? 'pass' : 'fail', text: limit == null ? text : `${text} (at most ${fmt(limit)})`, code: 'fea.deflection', values, refs }, ...settled,
225
+ { level: minSafety == null ? 'info' : least >= minSafety ? 'pass' : 'fail', text: `${a.problem} ${c.name}: ${strong}${minSafety != null ? ` (at least ${fmt(minSafety)}×)` : ''}`, code: 'fea.strength',
226
+ values: { stress: c.stress, at: c.stressAt, ...(safety != null ? { safety } : {}), ...(fatigue != null ? { fatigue } : {}), ...(minSafety != null ? { min: minSafety } : {}) }, refs },
227
+ ];
167
228
  });
168
229
  const grams = m.density ? ` (${fmt((r.volume / 1000) * m.density)} g of ${m.name})` : '';
169
230
  if (a.volume != null) {
170
231
  const want = evaluate(a.volume, lookup), tol = a.tolerance ?? 0.01, off = (r.volume - want) / want;
171
232
  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
233
  } else found.push({ level: 'info', text: `volume ${fmt(r.volume)} mm³${grams}`, code: 'fea.volume', values: { volume: r.volume } });
234
+ // A safety-critical part stays unverified until a test or an independent analysis is recorded against it
235
+ const records = b.object.verification || [];
236
+ if (r.critical) found.push(records.length
237
+ ? { level: 'pass', text: `${a.problem} is safety-critical: verified by ${records.map((v) => `${v.kind} (${v.date})`).join(', ')}`, code: 'fea.verified', values: { records } }
238
+ : { 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' });
239
+ // The report: everything above, with where, written next to the previews
240
+ const report = paths.preview(d.project, `${d.name}${tag}-report-${a.problem.replace(':', '-')}.md`);
241
+ fs.mkdirSync(path.dirname(report), { recursive: true });
242
+ 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 }));
243
+ 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');
244
+ found.push({ level: 'info', text: `report (${grid}): ${path.relative(WS, report)}`, code: 'fea.report', refs: { report: path.relative(WS, report) } });
173
245
  return found;
174
246
  })());
175
247
  return all;
package/lib/optimise.mjs CHANGED
@@ -8,7 +8,7 @@ import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import crypto from 'node:crypto';
10
10
  import { host } from './host.mjs';
11
- import { paths } from './workspace.mjs';
11
+ import { paths, printerOf } from './workspace.mjs';
12
12
  import { resolve, evaluate } from './rules.mjs';
13
13
  import { located } from './errors.mjs';
14
14
  import { discretise, optimise, outlines, surface, area } from '@rulecad/topopt';
@@ -47,19 +47,21 @@ export async function readProblem(project, ref) {
47
47
  }
48
48
  return parts.get(ref);
49
49
  };
50
+ // The build direction: a direction ('+z'), or a variable holding one
51
+ const overhang = p.overhang ? (typeof values[p.overhang] === 'string' ? values[p.overhang] : p.overhang) : null;
52
+ // A teardrop's point: a direction, or up or down the build direction (+z, as drawn, when it's free)
53
+ const point = (t) => { const up = overhang && overhang !== 'none' ? overhang : '+z'; return t === 'up' ? up : t === 'down' ? (up[0] === '-' ? '+' : '-') + up[1] : t; };
50
54
  const region = async (r) => {
51
55
  if (r.part) return { triangles: await part(r.part), part: r.part };
52
56
  if (r.points) return { points: r.points.map(pt) };
53
57
  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 } : {}) };
58
+ if (r.length != null) { const axis = r.axis || 'z', t = r.teardrop && point(r.teardrop); return { at: pt(r.at), r: ev(r.r), length: ev(r.length), axis, ...(t && t[1] !== axis ? { teardrop: t } : {}) }; } // along its axis, a teardrop has no point
55
59
  return { at: pt(r.at), ...(r.r != null ? { r: ev(r.r) } : {}) };
56
60
  };
57
61
  const regions = (list) => Promise.all([list || []].flat().map(region));
58
62
  const m = values[p.material];
59
63
  if (typeof m?.modulus !== 'number' || typeof m?.poisson !== 'number') throw new Error(`material ${p.material}: its rule set needs modulus (MPa) and poisson`);
60
64
  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
65
  const problem = {
64
66
  space, keep: await regions(p.keep), avoid: await regions(p.avoid),
65
67
  supports: await Promise.all(p.supports.map(async (s) => ({ ...(await region(s)), fix: s.fix || 'xyz'.slice(0, dim) }))),
@@ -72,7 +74,9 @@ export async function readProblem(project, ref) {
72
74
  };
73
75
  if (dim === 2 && !(problem.thickness > 0)) throw new Error(`${path.basename(file)}: a flat (2D) problem needs a thickness`);
74
76
  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 };
77
+ // A printable solid's surface is kept within the printer's overhang limit too (smoothing can tip faces past it)
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, critical: !!p.critical };
76
80
  }
77
81
 
78
82
  /**
@@ -99,7 +103,7 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
99
103
  })() : (() => {
100
104
  // The surface's level, found so the solid holds as much material as the optimised densities do (drawn at 0.5,
101
105
  // 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 });
106
+ 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, overhang: r.outline.overhang });
103
107
  let lo = 0.2, hi = 0.8, best = at(0.5), iso = 0.5;
104
108
  for (let k = 0; k < 10 && Math.abs(meshVolume(best.vertices, best.faces) / want - 1) > 0.003; k++) {
105
109
  if (meshVolume(best.vertices, best.faces) < want) hi = iso; else lo = iso; // a lower level encloses more
@@ -132,12 +136,20 @@ export const forDesign = ({ density, history, ...r }) => r;
132
136
  /**
133
137
  * Analyse a part under a problem's supports and loads, on its grid. A flat part (2D problem: triangles, z up, the
134
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
135
- * 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.
136
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
137
143
  */
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);
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
+ }
141
153
  // The grid covers the part and the problem's space
142
154
  let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
143
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); }
@@ -164,28 +176,70 @@ export async function analysePart(triangles, project, ref) {
164
176
  const a = analyse({ grid: g, density, material: problem.material, thickness: problem.thickness, fixed, loads });
165
177
  const cases = names.map((name, c) => {
166
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]));
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 };
179
+ return measures(name, size, a, c, density, { nx, ny, nz: 1, h }, [x0, y0]);
171
180
  });
172
- 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 };
173
182
  }
174
183
 
175
184
  // A solid part on the problem's grid: the part itself is the space (keep and avoid regions don't apply), so the
176
185
  // 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));
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);
180
189
  if (!density.some((d) => d)) throw new Error('the part is smaller than one cell of the problem: use a smaller cell');
181
190
  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 };
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
+ }
187
241
  });
188
- return { problem: r.ref, dim: 3, material: r.material, cases, volume: volume(triangles), grid: spec.grid, origin: spec.origin, density };
242
+ return density.map((x) => Math.min(1, x));
189
243
  }
190
244
 
191
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.0",
3
+ "version": "0.7.2",
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": {
@@ -50,12 +50,12 @@
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.4.0",
53
+ "@rulecad/shapes": "^0.4.1",
54
54
  "@rulecad/rules": "^0.3.0",
55
55
  "@jscad/modeling": "^2.12.0",
56
56
  "three": "^0.186.1",
57
57
  "@rulecad/fea": "^0.2.0",
58
- "@rulecad/topopt": "^0.2.0"
58
+ "@rulecad/topopt": "^0.2.1"
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"] },
@@ -59,7 +73,11 @@
59
73
  "part": { "type": "string", "description": "The part analysed (default: the first that isn't a support)" },
60
74
  "max_deflection": { "$ref": "#/$defs/expr", "description": "Fail if any load case moves its load further than this, in mm" },
61
75
  "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)" }
76
+ "tolerance": { "type": "number", "description": "For volume: the share it may differ by (default 0.01)" },
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)" },
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" }
63
81
  }
64
82
  },
65
83
  "part": {
@@ -136,6 +136,10 @@
136
136
  }
137
137
  }
138
138
  },
139
+ "critical": {
140
+ "type": "boolean",
141
+ "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"
142
+ },
139
143
  "overhang": {
140
144
  "type": "string",
141
145
  "description": "3D: printable this way up ('+z', '-y', …), or a variable holding it, or 'none': only material supported from below at 45° or less"
@@ -205,11 +209,8 @@
205
209
  "type": "string"
206
210
  },
207
211
  "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)"
212
+ "enum": ["up", "down", "+z", "-z", "+y", "-y", "+x", "-x"],
213
+ "description": "3D: a 45° point on the cylinder that way, so it prints without support: down for a boss (its underside), up for a hole (its roof). up and down follow the problem's overhang (+z when it's free); along the cylinder's axis it has none"
213
214
  }
214
215
  }
215
216
  },
@@ -268,11 +269,8 @@
268
269
  "description": "Which ways it's held: x, y, z (default all)"
269
270
  },
270
271
  "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)"
272
+ "enum": ["up", "down", "+z", "-z", "+y", "-y", "+x", "-x"],
273
+ "description": "3D: a 45° point on the cylinder that way, so it prints without support: down for a boss (its underside), up for a hole (its roof). up and down follow the problem's overhang (+z when it's free); along the cylinder's axis it has none"
276
274
  }
277
275
  }
278
276
  },
@@ -336,11 +334,8 @@
336
334
  "description": "Its load case (default load)"
337
335
  },
338
336
  "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)"
337
+ "enum": ["up", "down", "+z", "-z", "+y", "-y", "+x", "-x"],
338
+ "description": "3D: a 45° point on the cylinder that way, so it prints without support: down for a boss (its underside), up for a hole (its roof). up and down follow the problem's overhang (+z when it's free); along the cylinder's axis it has none"
344
339
  }
345
340
  }
346
341
  }