@rulecad/cad 0.7.5 → 0.7.7

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/README.md CHANGED
@@ -369,6 +369,9 @@ with numbers as expressions like an object's (schema: `schemas/problem.schema.js
369
369
  gives, and draws the layout in `.preview/`. The result is kept, keyed by everything it's made from, so it's only
370
370
  worked out again when something it depends on changes.
371
371
 
372
+ A 3D result keeps only the pieces that touch a support, a load or a kept region. A few grey cells away from the rest
373
+ can close into a piece of their own, which would print as a stray bit. `cad optimise` says how many it dropped.
374
+
372
375
  `cad optimise <project>/<problem> --watch [port]` runs it afresh and serves a live view at `http://127.0.0.1:8090/`:
373
376
  the densities as they change (a 3D part from three sides), a chart of its compliance and how much it still changes, with a scrubber to look back at any earlier step, its run time and time left, the machine it runs on, and a button that stops the run. It shows the end for ten minutes after the run finishes.
374
377
  It listens on this computer only. To watch from elsewhere, reach it through a private network such as Tailscale.
@@ -430,7 +433,9 @@ the problem, and optionally a limit:
430
433
  `cad check` then reports, for each load case, how far the part moves its load, its stiffness (N/mm) and its peak
431
434
  stress against the material's strength, and the part's volume and weight. With `max_deflection` a case that moves
432
435
  further fails; with `volume` a part whose volume is further than `tolerance` (a share) from it fails. A picture goes in
433
- `.preview/`.
436
+ `.preview/`. A twist (forces that add to nothing, such as four round a rim) has no direction to move along, so it's
437
+ reported as the angle the part turns through, in degrees, under its moment (N·m), and its torsional stiffness (N·m a
438
+ degree).
434
439
 
435
440
  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
436
441
  part takes up, so a wall between cell centres still counts, but thin walls on big cubes still come out too stiff when
package/bin/cad.mjs CHANGED
@@ -112,6 +112,9 @@ function report(findings, about = {}) {
112
112
  const say = (...a) => { if (!opt('json')) console.log(...a); }; // text output that --json leaves out
113
113
 
114
114
  const sig = (n) => (Number.isFinite(n) ? String(Number(n.toPrecision(3))) : String(n)); // three significant figures
115
+ // A case's stiffness, and in words: a twist turns (degrees under N·m, N·m a degree), anything else moves along its load
116
+ const stiffOf = (c) => (c.moment ? c.torsion : c.stiffness);
117
+ const howFar = (c) => (c.moment ? `turns ${sig(c.angle * 180 / Math.PI)}° under ${sig(c.moment / 1000)} N·m, ${sig(c.torsion / 1000 * Math.PI / 180)} N·m a degree` : `moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
115
118
  // cad optimise: run a problem (with a progress line), then report it and draw it: a 2D layout as an SVG of its
116
119
  // densities, a 3D one as the preview's four views of its surface
117
120
  async function optimiseProblem(ref) {
@@ -136,8 +139,8 @@ async function optimiseProblem(ref) {
136
139
  // The page keeps showing the end for ten minutes (the process waits for it), so a finished run isn't a dead link
137
140
  if (view) { view.close(`finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, { hold: 10 * 60e3 }); say(`the live view shows the result for ten more minutes (Ctrl-C to stop it)`); }
138
141
  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}`;
139
- 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(', ')}`,
140
- `${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)})` : ''}`];
142
+ const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => c.moment ? `${c.name} ${sig(c.angle * 180 / Math.PI)}° (${sig(c.torsion / 1000 * Math.PI / 180)} N·m/°)` : `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
143
+ `${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}${r.dropped ? `; ${r.dropped.length} loose ${r.dropped.length === 1 ? 'piece' : 'pieces'} dropped (${sig(r.dropped.reduce((t, v) => t + v, 0))} mm³)` : ''}`];
141
144
  let out;
142
145
  if (r.dim === 3) {
143
146
  out = paths.preview(project, `${name.replace(':', '-')}-optimised.png`);
@@ -150,7 +153,7 @@ async function optimiseProblem(ref) {
150
153
  }
151
154
  if (opt('json')) return console.log(JSON.stringify((({ density, history, mesh, ...x }) => x)(r), null, 2));
152
155
  console.log(`${r.title}${r.cached ? ' (cached)' : ` (${fmt(r.seconds)} s)`}`);
153
- for (const c of r.cases) console.log(` ${c.name}: moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
156
+ for (const c of r.cases) console.log(` ${c.name}: ${howFar(c)}`);
154
157
  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)' : ''}`);
155
158
  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}` : ''}`);
156
159
  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)`);
@@ -175,7 +178,7 @@ function place(triangles, [rx, ry, rz], move) {
175
178
  function reportText({ turn, object, title, version, a, r, m, strength, weaker, grid, limit, minSafety, records, found }) {
176
179
  const at = (p) => `(${p.map(fmt).join(', ')})`;
177
180
  const pct = (x) => `${x >= 0 ? '+' : ''}${fmt(x * 100)}%`;
178
- 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)} |`);
181
+ const rows = r.cases.map((c) => `| ${c.name} | ${c.moment ? `${sig(c.moment / 1000)} N·m | ${sig(c.angle * 180 / Math.PI)}° | ${sig(c.torsion / 1000 * Math.PI / 180)} N·m/°` : `${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)} |`);
179
182
  return [
180
183
  `# ${title}: analysed under ${a.problem}`, '',
181
184
  `${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.'}`, '',
@@ -209,7 +212,7 @@ async function analyses(b, d, tag) {
209
212
  // theory it's endless there), so it's reported, not judged.
210
213
  if (cell) {
211
214
  const coarser = await analysePart(turned, d.project, a.problem, { cell: cell * 1.25 });
212
- 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 }; });
215
+ r.cases.forEach((c, n) => { const o = coarser.cases[n]; c.change = { stiffness: stiffOf(c) / stiffOf(o) - 1, stress: c.stress / o.stress - 1, cell: coarser.grid.h }; });
213
216
  }
214
217
  const limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
215
218
  const minSafety = a.min_safety != null ? evaluate(a.min_safety, lookup) : null;
@@ -226,15 +229,15 @@ async function analyses(b, d, tag) {
226
229
  const at = (p) => `(${p.map(fmt).join(', ')})`;
227
230
  const found = r.cases.flatMap((c) => {
228
231
  const safety = strength ? strength / c.stress : null, fatigue = m.fatigue ? m.fatigue / c.stress : null;
229
- const text = `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm`;
230
- const values = { deflection: c.deflection, force: c.force, stiffness: c.stiffness, stress: c.stress, ...(limit != null ? { limit } : {}) };
232
+ const text = c.moment ? `${a.problem} ${c.name}: ${howFar(c)}` : `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm`;
233
+ const values = { ...(c.moment ? { angle: c.angle, moment: c.moment, torsion: c.torsion } : { deflection: c.deflection, force: c.force, stiffness: c.stiffness }), stress: c.stress, ...(limit != null ? { limit } : {}) };
231
234
  const refs = { problem: a.problem, part: part.name, ...(out ? { picture: path.relative(WS, out) } : {}) };
232
235
  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` : ''}` : ''}`;
233
236
  const least = Math.min(safety ?? Infinity, fatigue ?? Infinity);
234
237
  const settled = c.change ? [{ level: Math.abs(c.change.stiffness) <= 0.05 ? 'pass' : 'warn', code: 'fea.settled', values: c.change,
235
238
  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'}` }] : [];
236
239
  return [
237
- { level: limit == null ? 'info' : c.deflection <= limit ? 'pass' : 'fail', text: limit == null ? text : `${text} (at most ${fmt(limit)})`, code: 'fea.deflection', values, refs }, ...settled,
240
+ { level: limit == null || c.moment ? 'info' : c.deflection <= limit ? 'pass' : 'fail', text: limit == null ? text : `${text} (at most ${fmt(limit)})`, code: 'fea.deflection', values, refs }, ...settled,
238
241
  { level: minSafety == null ? 'info' : least >= minSafety ? 'pass' : 'fail', text: `${a.problem} ${c.name}: ${strong}${minSafety != null ? ` (at least ${fmt(minSafety)}×)` : ''}`, code: 'fea.strength',
239
242
  values: { stress: c.stress, at: c.stressAt, ...(safety != null ? { safety } : {}), ...(fatigue != null ? { fatigue } : {}), ...(minSafety != null ? { min: minSafety } : {}) }, refs },
240
243
  ];
package/lib/optimise.mjs CHANGED
@@ -11,7 +11,7 @@ import { host } from './host.mjs';
11
11
  import { paths, printerOf } from './workspace.mjs';
12
12
  import { resolve, evaluate } from './rules.mjs';
13
13
  import { located } from './errors.mjs';
14
- import { discretise, optimise, outlines, surface, area } from '@rulecad/topopt';
14
+ import { discretise, optimise, outlines, surface, area, bounds, resultant } from '@rulecad/topopt';
15
15
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
16
16
 
17
17
  const VERSION = 2, source = (m) => fs.readFileSync(new URL(import.meta.resolve(m)), 'utf8'); // the solver's code: a change remakes results
@@ -90,7 +90,8 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
90
90
  const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
91
91
  // Two keeps: the densities, by the problem and the code that decides them (the slow part), and the shape drawn from
92
92
  // them, by everything: a change to how shapes are drawn redraws them without optimising again
93
- const hash = digest([VERSION, r.problem, r.outline, topopt, source('@rulecad/fea')]), file = paths.cache('optimise', `${hash}.json`);
93
+ // The shape's key holds this file too, so a change to how cad draws a result (anchored below) redraws it
94
+ const hash = digest([VERSION, r.problem, r.outline, topopt, source('@rulecad/fea'), fs.readFileSync(new URL(import.meta.url), 'utf8')]), file = paths.cache('optimise', `${hash}.json`);
94
95
  if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file)) return { ...JSON.parse(host.readText(file)), cached: true };
95
96
  const spec = discretise(r.problem), densities = paths.cache('densities', `${digest([VERSION, r.problem, solver, source('@rulecad/fea')])}.json`);
96
97
  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: onStep && ((st) => onStep({ ...st, grid: spec.grid })) });
@@ -109,8 +110,9 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
109
110
  if (meshVolume(best.vertices, best.faces) < want) hi = iso; else lo = iso; // a lower level encloses more
110
111
  iso = (lo + hi) / 2; best = at(iso);
111
112
  }
112
- const { vertices, faces } = best;
113
- return { mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces }, solid: meshVolume(vertices, faces), iso };
113
+ const anchors = [...r.problem.supports, ...r.problem.loads, ...(r.problem.keep || [])].map(bounds);
114
+ const { vertices, faces, dropped } = anchored(best, anchors, spec.grid.h);
115
+ return { mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces }, solid: meshVolume(vertices, faces), iso, ...(dropped.length ? { dropped } : {}) };
114
116
  })();
115
117
  const result = {
116
118
  problem: ref, title: r.title, hash, dim: r.dim, material: r.material.name, ...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
@@ -175,8 +177,8 @@ export async function analysePart(triangles, project, ref, { cell } = {}) {
175
177
  });
176
178
  const a = analyse({ grid: g, density, material: problem.material, thickness: problem.thickness, fixed, loads });
177
179
  const cases = names.map((name, c) => {
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]));
179
- return measures(name, size, a, c, density, { nx, ny, nz: 1, h }, [x0, y0]);
180
+ const { size, moment } = resultant(problem.loads.filter((l) => l.case === name));
181
+ return measures(name, size, moment, a, c, density, { nx, ny, nz: 1, h }, [x0, y0]);
180
182
  });
181
183
  return { problem: ref, dim: 2, material: r.material, critical: r.critical, cases, volume: volume(triangles), grid: { nx, ny, h }, origin: [x0, y0], density };
182
184
  }
@@ -188,20 +190,21 @@ function analyseSolid(triangles, r, cell) {
188
190
  const g = makeGrid(spec.grid), density = solidFill(triangles, spec.grid, spec.origin);
189
191
  if (!density.some((d) => d)) throw new Error('the part is smaller than one cell of the problem: use a smaller cell');
190
192
  const a = analyse({ grid: g, density, material: problem.material, fixed: spec.fixed, loads: spec.loads.map((l) => l.force) });
191
- const cases = spec.loads.map((l, c) => measures(l.name, l.size, a, c, density, spec.grid, spec.origin));
193
+ const cases = spec.loads.map((l, c) => measures(l.name, l.size, l.moment, a, c, density, spec.grid, spec.origin));
192
194
  return { problem: r.ref, dim: 3, material: r.material, critical: r.critical, cases, volume: volume(triangles), grid: spec.grid, origin: spec.origin, density };
193
195
  }
194
196
 
195
- // A load case's numbers: how far the load moves along itself (compliance over force) and the stiffness, the largest
197
+ // A load case's numbers: how far the load moves along itself (compliance over force) and the stiffness (a twist: the
198
+ // angle it turns, compliance over its moment, and the torsion, N·mm a radian), the largest
196
199
  // 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;
200
+ function measures(name, force, moment, a, c, density, { nx, ny, h }, origin) {
201
+ const deflection = force ? a.compliance[c] / force : 0, angle = moment ? a.compliance[c] / moment : 0;
199
202
  let most = 0, cellAt = 0;
200
203
  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
204
  const index = [cellAt % nx, Math.floor(cellAt / nx) % ny, Math.floor(cellAt / (nx * ny))];
202
205
  const stressAt = origin.map((o, q) => round(o + (index[q] + 0.5) * h, 2)), d = a.deflection[c];
203
206
  return {
204
- name, force, deflection, stiffness: deflection ? force / deflection : Infinity, stress: most, stressAt,
207
+ name, ...(moment ? { moment, angle, torsion: moment / angle } : { force, deflection, stiffness: deflection ? force / deflection : Infinity }), stress: most, stressAt,
205
208
  movement: d.most, movementAt: d.at.map((x, q) => round(x + origin[q], 2)),
206
209
  };
207
210
  }
@@ -303,3 +306,26 @@ export function picture(r, { title = '', lines = [] } = {}) {
303
306
  </svg>
304
307
  `;
305
308
  }
309
+
310
+ // Loose pieces: drawn from cells, a few grey cells away from the rest can close into a piece of their own, which would
311
+ // print as a stray bit. Only pieces touching a support, a load or a kept region (within a cell) stay; the volumes of
312
+ // the rest, mm³, come back as dropped.
313
+ export function anchored({ vertices, faces }, anchors, h) {
314
+ const up = vertices.map((_, i) => i), find = (i) => { while (up[i] !== i) i = up[i] = up[up[i]]; return i; };
315
+ for (const [a, b, c] of faces) { up[find(a)] = find(b); up[find(b)] = find(c); }
316
+ const pieces = new Map();
317
+ for (const f of faces) {
318
+ const r = find(f[0]), p = pieces.get(r) ?? { faces: [], lo: [Infinity, Infinity, Infinity], hi: [-Infinity, -Infinity, -Infinity] };
319
+ p.faces.push(f);
320
+ for (const v of f) for (let k = 0; k < 3; k++) { p.lo[k] = Math.min(p.lo[k], vertices[v][k]); p.hi[k] = Math.max(p.hi[k], vertices[v][k]); }
321
+ pieces.set(r, p);
322
+ }
323
+ if (pieces.size < 2) return { vertices, faces, dropped: [] };
324
+ const touches = (p) => anchors.some((b) => [0, 1, 2].every((k) => p.lo[k] <= b[3 + k] + h && p.hi[k] >= b[k] - h));
325
+ const kept = [], dropped = [];
326
+ for (const p of pieces.values()) (touches(p) ? kept : dropped).push(p);
327
+ if (!kept.length) return { vertices, faces, dropped: [] }; // nothing anchored: keep it all rather than nothing
328
+ const index = new Map(), out = [];
329
+ const keptFaces = kept.flatMap((p) => p.faces).map((f) => f.map((v) => { if (!index.has(v)) { index.set(v, out.length); out.push(vertices[v]); } return index.get(v); }));
330
+ return { vertices: out, faces: keptFaces, dropped: dropped.map((p) => round(meshVolume(vertices, p.faces), 3)) };
331
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.5",
3
+ "version": "0.7.7",
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": {