@rulecad/cad 0.6.0 → 0.7.1

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
@@ -86,6 +86,10 @@ variable says which rule it comes from. Follow these steps; they're what makes a
86
86
  material's rule set. `npx cad optimise <project>/<problem>` and **look at the picture** in `.preview/`.
87
87
  - A design reads the result through a `problem` variable and builds it with `v.shapes.optimisedOutline(...)`. Add an
88
88
  `analysis` to the object so `cad check` reports its stiffness; report those numbers with their load and material.
89
+ - Solid parts (brackets, joints) are 3D problems: regions with a z, a named part as the space if it helps. Set
90
+ `"overhang"` to the way up it will print, so the result needs no supports, and give horizontal bosses and holes a
91
+ `teardrop` (`"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.
89
93
  - Say plainly that the analysis is coarse and the material values are data-sheet figures: anything that could hurt
90
94
  someone if it broke needs testing, not just a check.
91
95
 
package/README.md CHANGED
@@ -378,6 +378,36 @@ export function main (v) {
378
378
  `optimisedOutline` gives the outline as a 2D shape, its keep regions added and avoid regions cut exactly, so bolt
379
379
  holes come out true.
380
380
 
381
+ ### Solid parts (3D)
382
+
383
+ A problem whose regions have a z is solid. It has no thickness, and takes more kinds of region:
384
+ - **A box:** `size`.
385
+ - **A cylinder:** `r`, `length` and `axis`. 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.
388
+ - **A ball:** `r`.
389
+ - **A named part of another design in the project:** `{ "part": "envelope.body" }`.
390
+
391
+ Supports and loads can be any region; a force has x, y and z. `"overhang": "+z"` keeps only material that prints
392
+ without supports standing that way up (a variable holding `"+z"` or `"none"` works too, so a variant can switch it).
393
+
394
+ `cad optimise` draws the result's four views in `.preview/`. A design builds the result with
395
+ `v.shapes.optimisedSolid(v.problems[v.problem], { ops: v.ops })`, which adds the keep regions and cuts the avoid
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
+ ```
407
+
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
409
+ optimisation takes a few minutes. The result is kept, so it's worked out once.
410
+
381
411
  ### Analysis
382
412
 
383
413
  Any flat part, optimised or not, can be checked under a problem's supports and loads. An object's `analysis` names
package/bin/cad.mjs CHANGED
@@ -110,8 +110,9 @@ function report(findings, about = {}) {
110
110
  const say = (...a) => { if (!opt('json')) console.log(...a); }; // text output that --json leaves out
111
111
 
112
112
  const sig = (n) => (Number.isFinite(n) ? String(Number(n.toPrecision(3))) : String(n)); // three significant figures
113
- // cad optimise: run a problem (with a progress line), then report it and draw it
114
- function optimiseProblem(ref) {
113
+ // cad optimise: run a problem (with a progress line), then report it and draw it: a 2D layout as an SVG of its
114
+ // densities, a 3D one as the preview's four views of its surface
115
+ async function optimiseProblem(ref) {
115
116
  const [project, name] = String(ref).split('/');
116
117
  if (!project || !name) throw new Error('usage: cad optimise <project>/<problem>[:variant]');
117
118
  const file = problemFile(project, name.split(':')[0]);
@@ -120,36 +121,63 @@ function optimiseProblem(ref) {
120
121
  if (bad.length) { report(bad); process.exitCode = 1; return; }
121
122
  }
122
123
  const live = !opt('json') && process.stderr.isTTY;
123
- const r = optimised(project, name, { fresh: !!opt('fresh'), onStep: (s) => live && process.stderr.write(`\r\x1b[Kstep ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm change ${s.change.toFixed(3)} sharpness ${s.beta}`) });
124
+ const r = await optimised(project, name, { fresh: !!opt('fresh'), onStep: (s) => live && process.stderr.write(`\r\x1b[Kstep ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm change ${s.change.toFixed(3)} sharpness ${s.beta}`) });
124
125
  if (live) process.stderr.write('\r\x1b[K');
125
- const out = paths.preview(project, `${name.replace(':', '-')}-optimised.svg`), p = readProblem(project, name);
126
- const lines = [`${p.material.name}, ${fmt(r.thickness)} mm thick: ${r.cases.map((c) => `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
127
- `${fmt(r.volume * 100)}% of the space, ${r.grid.nx} × ${r.grid.ny} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}`];
128
- fs.mkdirSync(path.dirname(out), { recursive: true });
129
- fs.writeFileSync(out, picture(r, { title: r.title, lines }));
130
- if (opt('json')) return console.log(JSON.stringify((({ density, history, ...x }) => x)(r), null, 2));
126
+ const p = await readProblem(project, name), cells = r.dim === 3 ? `${r.grid.nx} × ${r.grid.ny} × ${r.grid.nz}` : `${r.grid.nx} × ${r.grid.ny}`;
127
+ const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
128
+ `${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}`];
129
+ let out;
130
+ if (r.dim === 3) {
131
+ out = paths.preview(project, `${name.replace(':', '-')}-optimised.png`);
132
+ const triangles = r.mesh.faces.map((f) => f.map((i) => r.mesh.vertices[i]));
133
+ await preview([{ name: 'body', label: r.title, triangles }], { title: r.title, meta: lines.join(' · '), out });
134
+ } else {
135
+ out = paths.preview(project, `${name.replace(':', '-')}-optimised.svg`);
136
+ fs.mkdirSync(path.dirname(out), { recursive: true });
137
+ fs.writeFileSync(out, picture(r, { title: r.title, lines }));
138
+ }
139
+ if (opt('json')) return console.log(JSON.stringify((({ density, history, mesh, ...x }) => x)(r), null, 2));
131
140
  console.log(`${r.title}${r.cached ? ' (cached)' : ` (${fmt(r.seconds)} s)`}`);
132
141
  for (const c of r.cases) console.log(` ${c.name}: moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
133
- 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)`);
134
- console.log(` ${r.grid.nx} × ${r.grid.ny} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? ', settled' : ': stopped before it settled (raise steps)'}`);
142
+ if (r.dim === 3) console.log(` ${fmt(r.volume * 100)}% of the space filled: ${fmt(r.solid / 1000)} cm³ (${fmt(r.solid / 1000 * (p.material.density || 0))} g of ${p.material.name})${r.overhang ? `, printable built ${r.overhang}` : ''}`);
143
+ else console.log(` ${fmt(r.volume * 100)}% of the space filled, outline ${fmt(r.area)} mm² (${fmt(r.area * r.thickness / 1000)} cm³ before bosses and holes are made exact)`);
144
+ console.log(` ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? ', settled' : ': stopped before it settled (raise steps)'}`);
135
145
  console.log(out);
136
146
  }
137
147
 
138
148
  // An object's analyses for cad check: each problem's load cases on the part, and its volume against a target
139
- function analyses(b, d, tag) {
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
+ async function analyses(b, d, tag) {
140
161
  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; };
141
- return (b.object.analysis || []).flatMap((a) => {
162
+ const all = [];
163
+ for (const a of b.object.analysis || []) all.push(...await (async () => {
142
164
  const part = a.part ? b.parts.find((p) => p.name === a.part) : b.parts.find((p) => p.role !== 'support');
143
165
  if (!part) return [{ level: 'fail', text: `analysis: no part "${a.part}"`, code: 'fea.part' }];
144
- const r = analysePart(part.triangles, d.project, a.problem), m = r.material, limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
145
- const out = paths.preview(d.project, `${d.name}${tag}-analysis-${a.problem.replace(':', '-')}.svg`);
146
- fs.mkdirSync(path.dirname(out), { recursive: true });
147
- fs.writeFileSync(out, picture({ ...r, ...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`) }));
166
+ // A part drawn in its print orientation, turned back into the problem's frame: rotated (degrees about x, then y,
167
+ // then z, as JSCAD's rotate), then moved
168
+ const turned = a.rotate || a.move ? 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;
169
+ const r = await analysePart(turned, d.project, a.problem), m = r.material, limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
170
+ let out = null;
171
+ if (r.dim !== 3) { // a flat part's picture: its cells as analysed, with the supports and loads
172
+ out = paths.preview(d.project, `${d.name}${tag}-analysis-${a.problem.replace(':', '-')}.svg`);
173
+ fs.mkdirSync(path.dirname(out), { recursive: true });
174
+ 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
+ }
148
176
  const found = r.cases.map((c) => {
149
177
  const safety = m.strength ? `, peak stress ${sig(c.stress)} MPa (${sig(m.strength / c.stress)}× under ${m.name}'s strength; coarse)` : '';
150
178
  const text = `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm${safety}`;
151
179
  const values = { deflection: c.deflection, force: c.force, stiffness: c.stiffness, stress: c.stress, ...(limit != null ? { limit } : {}) };
152
- 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, picture: path.relative(WS, out) } };
180
+ 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) } : {}) } };
153
181
  });
154
182
  const grams = m.density ? ` (${fmt((r.volume / 1000) * m.density)} g of ${m.name})` : '';
155
183
  if (a.volume != null) {
@@ -157,7 +185,8 @@ function analyses(b, d, tag) {
157
185
  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 } });
158
186
  } else found.push({ level: 'info', text: `volume ${fmt(r.volume)} mm³${grams}`, code: 'fea.volume', values: { volume: r.volume } });
159
187
  return found;
160
- });
188
+ })());
189
+ return all;
161
190
  }
162
191
 
163
192
  async function main() {
@@ -217,7 +246,7 @@ async function main() {
217
246
  if (cmd === 'why') return explainValue(ref);
218
247
  if (cmd === 'set') return editVariables(ref);
219
248
  if (cmd === 'add') return editAssembly(args[1], args[2]);
220
- if (cmd === 'optimise' || cmd === 'optimize') return optimiseProblem(ref);
249
+ if (cmd === 'optimise' || cmd === 'optimize') return await optimiseProblem(ref);
221
250
  if (isAssembly(ref)) return assembly(cmd, ref);
222
251
  const [base, at] = ref.split('@');
223
252
  const d = at ? materialise(locate(base), at) : locate(ref), set = sets();
@@ -264,7 +293,7 @@ async function main() {
264
293
  ...(b.object.role === 'reference'
265
294
  ? [{ level: 'pass', text: `a reference (${(await import('@rulecad/printcheck')).bounds(b.triangles).size.map(fmt).join(' × ')} mm), not printed: no print checks`, code: 'print.reference' }]
266
295
  : check(b.triangles, printer(b, d), { parts: b.parts })),
267
- ...analyses(b, d, tag),
296
+ ...(await analyses(b, d, tag)),
268
297
  ], { object: `${d.project}/${d.name}`, title, version, ...(Object.keys(set).length ? { set } : {}), orientation: b.object.orientation, parts: b.parts.map((p) => ({ name: p.name, role: p.role || 'part' })) });
269
298
  if (b.object.orientation) say(` orientation: ${b.object.orientation}`);
270
299
  if (b.parts.length > 1) say(` parts: ${b.parts.map((p) => `${p.name}${p.role === 'support' ? ' (support)' : ''}`).join(', ')}`);
package/lib/design.mjs CHANGED
@@ -21,7 +21,7 @@ import { runSandboxed, sandboxed } from './sandbox.mjs';
21
21
  export { polygons };
22
22
  import fs from 'node:fs';
23
23
  import path from 'node:path';
24
- import { pathToFileURL } from 'node:url';
24
+ import { pathToFileURL, fileURLToPath } from 'node:url';
25
25
  import { createRequire } from 'node:module';
26
26
  import crypto from 'node:crypto';
27
27
  import { resolve, loadRuleSet } from './rules.mjs';
@@ -91,12 +91,12 @@ export function layoutsOf(d, object) {
91
91
  }
92
92
 
93
93
  // The optimised layouts an object's problem variables pick, by name, for v.problems
94
- export function problemsOf(d, object, values) {
94
+ export async function problemsOf(d, object, values) {
95
95
  const out = {};
96
96
  for (const [name, v] of Object.entries(object.variables || {})) if (v.type === 'problem') {
97
97
  const ref = values[name];
98
98
  if (!out[ref]) {
99
- const r = optimised(d.project, ref, { onStep: (s) => s.step === 1 && console.error(`optimising ${ref} (once: the result is cached until the problem changes)…`) });
99
+ const r = await optimised(d.project, ref, { onStep: (s) => s.step === 1 && console.error(`optimising ${ref} (once: the result is cached until the problem changes)…`) });
100
100
  out[ref] = forDesign(r);
101
101
  }
102
102
  }
@@ -115,7 +115,8 @@ const CACHE = paths.cache('builds'), CACHE_VERSION = 2;
115
115
  const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
116
116
  // What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
117
117
  // boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
118
- const own = source(import.meta.url) + source(import.meta.resolve('@rulecad/shapes')) + packageVersion('@jscad/modeling');
118
+ const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes')));
119
+ const own = source(import.meta.url) + fs.readdirSync(shapesDir).filter((f) => f.endsWith('.mjs')).sort().map((f) => source(pathToFileURL(path.join(shapesDir, f)).href)).join('') + packageVersion('@jscad/modeling'); // every shapes module, not just its entry
119
120
  export const pcbEngine = () => import('@rulecad/pcb').catch((e) => {
120
121
  if (e.code === 'ERR_MODULE_NOT_FOUND' && /@rulecad\/pcb/.test(e.message)) throw new Error('boards need the board engine: npm install @rulecad/pcb');
121
122
  throw e;
@@ -150,7 +151,7 @@ export async function build(d, set = {}, { mirror = false } = {}) {
150
151
  if (Object.keys(files).length) values.layouts = Object.fromEntries(Object.entries(files).map(([n, l]) => [n, { ...l, keys: keys(l), width: width(l), depth: depth(l) }]));
151
152
  // Optimised layouts: a "type": "problem" variable picks a problem in the project's problems/; the design gets the
152
153
  // one it picked as v.problems[name] (lib/optimise.mjs), optimised the first time and cached after
153
- const problems = problemsOf(d, object, values);
154
+ const problems = await problemsOf(d, object, values);
154
155
  if (Object.keys(problems).length) values.problems = problems;
155
156
 
156
157
  // The cache: everything the build is made from. A hit skips running the design (and its booleans) altogether
package/lib/optimise.mjs CHANGED
@@ -1,19 +1,20 @@
1
- // Optimisation problems and analysis: problems/<name>.json in a project describes a flat part to optimise (where
2
- // material may go, what stays solid or empty, supports, loads, material); @rulecad/topopt finds the stiffest layout,
3
- // and @rulecad/fea analyses any flat part under the same problem's loads (an object's "analysis", run by cad check).
4
- // The problem file is the source: a result is derived from it, cached by everything it's made from, and remade only
5
- // when one of those changes. A name may pick a variant: lever:both.
1
+ // Optimisation problems and analysis: problems/<name>.json in a project describes a part to optimise, flat (2D) or
2
+ // solid (3D): where material may go, what stays solid or empty, supports, loads, material. @rulecad/topopt finds the
3
+ // stiffest layout, and @rulecad/fea analyses any part under the same problem's loads (an object's "analysis", run by
4
+ // cad check). The problem file is the source: a result is derived from it, cached by everything it's made from, and
5
+ // remade only when one of those changes. A name may pick a variant: lever:both. A 3D region can be a named part of
6
+ // another design in the project ({ "part": "envelope.body" }), as it's built.
6
7
  import fs from 'node:fs';
7
8
  import path from 'node:path';
8
9
  import crypto from 'node:crypto';
9
10
  import { host } from './host.mjs';
10
- import { paths } from './workspace.mjs';
11
- import { resolve, loadRuleSet, evaluate } from './rules.mjs';
11
+ import { paths, printerOf } from './workspace.mjs';
12
+ import { resolve, evaluate } from './rules.mjs';
12
13
  import { located } from './errors.mjs';
13
- import { discretise, optimise, outlines, area } from '@rulecad/topopt';
14
+ import { discretise, optimise, outlines, surface, area } from '@rulecad/topopt';
14
15
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
15
16
 
16
- const VERSION = 1, source = (m) => fs.readFileSync(new URL(import.meta.resolve(m)), 'utf8'); // the solver's code: a change remakes results
17
+ const VERSION = 2, source = (m) => fs.readFileSync(new URL(import.meta.resolve(m)), 'utf8'); // the solver's code: a change remakes results
17
18
  export const problemFile = (project, name) => path.join(paths.project(project), 'problems', `${name}.json`);
18
19
  export const hasProblem = (project, ref) => host.exists(problemFile(project, String(ref).split(':')[0]));
19
20
 
@@ -21,7 +22,7 @@ export const hasProblem = (project, ref) => host.exists(problemFile(project, Str
21
22
  * A problem with every expression worked out: what @rulecad/topopt takes, with its material and settings.
22
23
  * @param {string} project @param {string} ref name, or name:variant
23
24
  */
24
- export function readProblem(project, ref) {
25
+ export async function readProblem(project, ref) {
25
26
  const [name, variant] = String(ref).split(':'), file = problemFile(project, name);
26
27
  if (!host.exists(file)) throw new Error(`no problem "${name}" (projects/${project}/problems/${name}.json)`);
27
28
  const p = JSON.parse(host.readText(file));
@@ -35,56 +36,112 @@ export function readProblem(project, ref) {
35
36
  return v;
36
37
  };
37
38
  const ev = (x) => evaluate(x, lookup), pt = (a) => a.map(ev);
38
- const region = (r) => (r.points ? { points: r.points.map(pt) } : r.size ? { at: pt(r.at), size: r.size.map(ev) } : { at: pt(r.at), r: ev(r.r) });
39
+ // A named part of another design in the project, as triangles (built with its defaults)
40
+ const parts = new Map();
41
+ const part = async (ref) => {
42
+ if (!parts.has(ref)) {
43
+ const [object, partName] = ref.split('.'), { build, locate } = await import('./design.mjs');
44
+ const b = await build(locate(`${project}/${object}`)), found = partName ? b.parts.find((q) => q.name === partName) : b.parts.find((q) => q.role !== 'support');
45
+ if (!found) throw new Error(`${path.basename(file)}: ${object} has no part "${partName}" (parts: ${b.parts.map((q) => q.name).join(', ')})`);
46
+ parts.set(ref, found.triangles);
47
+ }
48
+ return parts.get(ref);
49
+ };
50
+ // 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; };
54
+ const region = async (r) => {
55
+ if (r.part) return { triangles: await part(r.part), part: r.part };
56
+ if (r.points) return { points: r.points.map(pt) };
57
+ if (r.size) return { at: pt(r.at), size: r.size.map(ev) };
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
59
+ return { at: pt(r.at), ...(r.r != null ? { r: ev(r.r) } : {}) };
60
+ };
61
+ const regions = (list) => Promise.all([list || []].flat().map(region));
39
62
  const m = values[p.material];
40
63
  if (typeof m?.modulus !== 'number' || typeof m?.poisson !== 'number') throw new Error(`material ${p.material}: its rule set needs modulus (MPa) and poisson`);
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;
41
65
  const problem = {
42
- space: [p.space].flat().map(region), keep: (p.keep || []).map(region), avoid: (p.avoid || []).map(region),
43
- supports: p.supports.map((s) => ({ at: pt(s.at), ...(s.r != null ? { r: ev(s.r) } : {}), fix: s.fix || 'xy' })),
44
- loads: p.loads.map((l) => ({ at: pt(l.at), ...(l.r != null ? { r: ev(l.r) } : {}), force: pt(l.force), case: l.case || 'load' })),
66
+ space, keep: await regions(p.keep), avoid: await regions(p.avoid),
67
+ supports: await Promise.all(p.supports.map(async (s) => ({ ...(await region(s)), fix: s.fix || 'xyz'.slice(0, dim) }))),
68
+ loads: await Promise.all(p.loads.map(async (l) => ({ ...(await region(l)), force: pt(l.force), case: l.case || 'load' }))),
45
69
  cases: Object.fromEntries(Object.entries(p.cases || {}).map(([k, w]) => [k, ev(w)])),
46
- material: { E: m.modulus, nu: m.poisson }, 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), volume: ev(p.volume),
47
71
  ...(p.filter != null ? { filter: ev(p.filter) } : {}), ...(p.penal != null ? { penal: ev(p.penal) } : {}),
48
72
  ...(p.projection != null ? { projection: p.projection } : {}), ...(p.steps != null ? { steps: p.steps } : {}),
73
+ ...(overhang && overhang !== 'none' ? { overhang } : {}),
49
74
  };
75
+ if (dim === 2 && !(problem.thickness > 0)) throw new Error(`${path.basename(file)}: a flat (2D) problem needs a thickness`);
50
76
  const outline = { smooth: p.outline?.smooth ?? 4, minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2 };
51
- return { ref, name, variant, file, 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 };
52
80
  }
53
81
 
54
82
  /**
55
- * The optimised layout for a problem, from the cache when nothing it depends on has changed.
83
+ * The optimised layout for a problem, from the cache when nothing it depends on has changed. A 2D result has outlines
84
+ * (closed loops in mm); a 3D one has a mesh ({ vertices, faces }, a closed surface in mm).
56
85
  * @param {string} project @param {string} ref
57
86
  * @param {{ onStep?: Function, fresh?: boolean }} [options] fresh: run it even if it's cached
58
87
  */
59
- export function optimised(project, ref, { onStep, fresh = false } = {}) {
60
- const r = readProblem(project, ref);
61
- const hash = crypto.createHash('sha256').update(JSON.stringify([VERSION, r.problem, r.outline, source('@rulecad/topopt'), source('@rulecad/fea')])).digest('hex');
62
- const file = paths.cache('optimise', `${hash}.json`);
88
+ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
89
+ const r = await readProblem(project, ref), topopt = source('@rulecad/topopt'), [solver] = topopt.split('// ---------- shapes from results ----------');
90
+ const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
91
+ // Two keeps: the densities, by the problem and the code that decides them (the slow part), and the shape drawn from
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`);
63
94
  if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file)) return { ...JSON.parse(host.readText(file)), cached: true };
64
- const spec = discretise(r.problem);
65
- const o = optimise(spec, { onStep });
66
- const loops = outlines(spec.grid, o.density, spec.origin, r.outline);
95
+ const spec = discretise(r.problem), densities = paths.cache('densities', `${digest([VERSION, r.problem, solver, source('@rulecad/fea')])}.json`);
96
+ 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 });
97
+ if (!host.exists(densities)) host.writeText(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
98
+ // Regions as data: a part's triangles are named, not copied
99
+ const named = (list) => list.map(({ triangles, ...x }) => x);
100
+ const shape = r.dim === 2 ? (() => {
101
+ const loops = outlines(spec.grid, o.density, spec.origin, r.outline);
102
+ return { outlines: loops.map((l) => l.map(([x, y]) => [round(x), round(y)])), area: loops.reduce((s, l) => s + area(l), 0) };
103
+ })() : (() => {
104
+ // The surface's level, found so the solid holds as much material as the optimised densities do (drawn at 0.5,
105
+ // thin members come out thinner than they are)
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 });
107
+ let lo = 0.2, hi = 0.8, best = at(0.5), iso = 0.5;
108
+ for (let k = 0; k < 10 && Math.abs(meshVolume(best.vertices, best.faces) / want - 1) > 0.003; k++) {
109
+ if (meshVolume(best.vertices, best.faces) < want) hi = iso; else lo = iso; // a lower level encloses more
110
+ iso = (lo + hi) / 2; best = at(iso);
111
+ }
112
+ const { vertices, faces } = best;
113
+ return { mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces }, solid: meshVolume(vertices, faces), iso };
114
+ })();
67
115
  const result = {
68
- problem: ref, title: r.title, hash, material: r.material.name, thickness: r.problem.thickness,
69
- grid: spec.grid, origin: spec.origin, regions: spec.regions, outlines: loops.map((l) => l.map(([x, y]) => [round(x), round(y)])),
70
- area: loops.reduce((s, l) => s + area(l), 0), volume: o.volume, compliance: o.compliance, cases: o.cases,
116
+ problem: ref, title: r.title, hash, dim: r.dim, material: r.material.name, ...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
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,
71
119
  steps: o.steps, converged: o.converged, seconds: o.seconds, history: o.history, density: Array.from(o.density, (d) => round(d, 3)),
72
- supports: r.problem.supports, loads: r.problem.loads,
120
+ supports: named(r.problem.supports), loads: named(r.problem.loads),
73
121
  };
74
122
  host.writeText(file, JSON.stringify(result));
75
123
  return result;
76
124
  }
77
125
 
126
+ // A closed mesh's volume (mm³), by the divergence theorem
127
+ function meshVolume(vertices, faces) {
128
+ let v = 0;
129
+ for (const [i, j, k] of faces) { const a = vertices[i], b = vertices[j], c = vertices[k]; v += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6; }
130
+ return v;
131
+ }
132
+
78
133
  // What a design gets as v.problems[name]: the outlines and regions to build from, and the numbers to report
79
134
  export const forDesign = ({ density, history, ...r }) => r;
80
135
 
81
136
  /**
82
- * Analyse a flat part (triangles, z up, the plate lying on the bed) under a problem's supports and loads, on its grid:
83
- * each cell is as solid as the share of the problem's thickness the part fills above it.
137
+ * Analyse a part under a problem's supports and loads, on its grid. A flat part (2D problem: triangles, z up, the
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.
84
140
  * @param {number[][][]} triangles @param {string} project @param {string} ref
85
141
  */
86
- export function analysePart(triangles, project, ref) {
87
- const r = readProblem(project, ref), { problem } = r, h = problem.cell;
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) return analyseSolid(triangles, r);
88
145
  // The grid covers the part and the problem's space
89
146
  let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
90
147
  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); }
@@ -119,6 +176,22 @@ export function analysePart(triangles, project, ref) {
119
176
  return { problem: ref, material: r.material, cases, volume: volume(triangles), grid: { nx, ny, h }, origin: [x0, y0], density };
120
177
  }
121
178
 
179
+ // A solid part on the problem's grid: the part itself is the space (keep and avoid regions don't apply), so the
180
+ // 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 = Float64Array.from(spec.passive, (p) => (p === 0 ? 1 : 0));
184
+ if (!density.some((d) => d)) throw new Error('the part is smaller than one cell of the problem: use a smaller cell');
185
+ 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
+ const deflection = l.size ? a.compliance[c] / l.size : 0;
188
+ let most = 0;
189
+ for (let e = 0; e < density.length; e++) if (density[e]) most = Math.max(most, a.stress[c][e]);
190
+ return { name: l.name, force: l.size, deflection, stiffness: deflection ? l.size / deflection : Infinity, stress: most };
191
+ });
192
+ return { problem: r.ref, dim: 3, material: r.material, cases, volume: volume(triangles), grid: spec.grid, origin: spec.origin, density };
193
+ }
194
+
122
195
  // How much of the thickness the part fills over each cell's centre: a ray straight up through the part enters it
123
196
  // through faces that face down and leaves through faces that face up, so the filled length is the sum of the up
124
197
  // faces' heights there less the down faces'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
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.3.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
- "@rulecad/fea": "^0.1.0",
58
- "@rulecad/topopt": "^0.1.0"
57
+ "@rulecad/fea": "^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"
@@ -59,7 +59,9 @@
59
59
  "part": { "type": "string", "description": "The part analysed (default: the first that isn't a support)" },
60
60
  "max_deflection": { "$ref": "#/$defs/expr", "description": "Fail if any load case moves its load further than this, in mm" },
61
61
  "volume": { "$ref": "#/$defs/expr", "description": "Fail if the part's volume differs from this (mm³) by more than tolerance" },
62
- "tolerance": { "type": "number", "description": "For volume: the share it may differ by (default 0.01)" }
62
+ "tolerance": { "type": "number", "description": "For volume: the share it may differ by (default 0.01)" },
63
+ "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" }
63
65
  }
64
66
  },
65
67
  "part": {
@@ -2,75 +2,337 @@
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "$id": "https://jonibach.github.io/rulecad/schemas/problem.schema.json",
4
4
  "title": "rulecad optimisation problem",
5
- "description": "A flat part to optimise (projects/<project>/problems/<name>.json): where material may go, what must stay solid or empty, where it's held and loaded, and what it's made of. Numbers are expressions, as in objects: of its variables and the rule sets it uses. cad optimise runs it; a design reads the result through a variable of type problem.",
5
+ "description": "A part to optimise, flat (2D) or solid (3D), in projects/<project>/problems/<name>.json: where material may go, what must stay solid or empty, where it's held and loaded, and what it's made of. Numbers are expressions, as in objects: of its variables and the rule sets it uses. cad optimise runs it; a design reads the result through a variable of type problem.",
6
6
  "type": "object",
7
- "required": ["material", "thickness", "cell", "volume", "space", "supports", "loads"],
7
+ "required": [
8
+ "material",
9
+ "cell",
10
+ "volume",
11
+ "space",
12
+ "supports",
13
+ "loads"
14
+ ],
8
15
  "additionalProperties": false,
9
16
  "properties": {
10
- "$schema": { "type": "string" },
11
- "title": { "type": "string" },
12
- "description": { "type": "string" },
13
- "uses": { "type": "array", "items": { "type": "string" }, "description": "Rule sets: the material's, the printer's, the part's own" },
14
- "variables": { "type": "object", "description": "As in objects" },
15
- "variants": { "type": "object", "additionalProperties": { "type": "object" }, "description": "Named settings of variables with tweak ranges, picked as name:variant" },
16
- "material": { "type": "string", "description": "A rule set with modulus (MPa), poisson and, for safety factors, strength (MPa)" },
17
- "thickness": { "$ref": "#/$defs/expr", "description": "The plate's thickness, mm" },
18
- "cell": { "$ref": "#/$defs/expr", "description": "The grid's cell size, mm: smaller is finer and slower" },
19
- "volume": { "$ref": "#/$defs/expr", "description": "The share of the space to fill, 0 to 1 (keep regions count towards it)" },
20
- "filter": { "$ref": "#/$defs/expr", "description": "Filter radius, mm: about the thinnest member (default 1.5 cells)" },
21
- "penal": { "$ref": "#/$defs/expr", "description": "The penalty on part-solid cells (default 3)" },
22
- "projection": { "type": "boolean", "description": "Sharpen the result to solid and empty (default true)" },
23
- "steps": { "type": "integer", "description": "At most this many steps (default 300)" },
24
- "space": { "oneOf": [{ "$ref": "#/$defs/region" }, { "type": "array", "items": { "$ref": "#/$defs/region" } }], "description": "Where material may go" },
25
- "keep": { "type": "array", "items": { "$ref": "#/$defs/region" }, "description": "Must stay solid: bosses round bolt holes" },
26
- "avoid": { "type": "array", "items": { "$ref": "#/$defs/region" }, "description": "Must stay empty: holes, clearances (avoid wins over keep)" },
27
- "supports": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/support" } },
28
- "loads": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/load" } },
29
- "cases": { "type": "object", "additionalProperties": { "$ref": "#/$defs/expr" }, "description": "Each load case's weight in the optimisation (default 1); 0 analyses it without optimising for it" },
17
+ "$schema": {
18
+ "type": "string"
19
+ },
20
+ "title": {
21
+ "type": "string"
22
+ },
23
+ "description": {
24
+ "type": "string"
25
+ },
26
+ "uses": {
27
+ "type": "array",
28
+ "items": {
29
+ "type": "string"
30
+ },
31
+ "description": "Rule sets: the material's, the printer's, the part's own"
32
+ },
33
+ "variables": {
34
+ "type": "object",
35
+ "description": "As in objects"
36
+ },
37
+ "variants": {
38
+ "type": "object",
39
+ "additionalProperties": {
40
+ "type": "object"
41
+ },
42
+ "description": "Named settings of variables with tweak ranges, picked as name:variant"
43
+ },
44
+ "material": {
45
+ "type": "string",
46
+ "description": "A rule set with modulus (MPa), poisson and, for safety factors, strength (MPa)"
47
+ },
48
+ "thickness": {
49
+ "$ref": "#/$defs/expr",
50
+ "description": "A flat (2D) problem's thickness, mm"
51
+ },
52
+ "cell": {
53
+ "$ref": "#/$defs/expr",
54
+ "description": "The grid's cell size, mm: smaller is finer and slower"
55
+ },
56
+ "volume": {
57
+ "$ref": "#/$defs/expr",
58
+ "description": "The share of the space to fill, 0 to 1 (keep regions count towards it)"
59
+ },
60
+ "filter": {
61
+ "$ref": "#/$defs/expr",
62
+ "description": "Filter radius, mm: about the thinnest member (default 1.5 cells)"
63
+ },
64
+ "penal": {
65
+ "$ref": "#/$defs/expr",
66
+ "description": "The penalty on part-solid cells (default 3)"
67
+ },
68
+ "projection": {
69
+ "type": "boolean",
70
+ "description": "Sharpen the result to solid and empty (default true)"
71
+ },
72
+ "steps": {
73
+ "type": "integer",
74
+ "description": "At most this many steps (default 300)"
75
+ },
76
+ "space": {
77
+ "oneOf": [
78
+ {
79
+ "$ref": "#/$defs/region"
80
+ },
81
+ {
82
+ "type": "array",
83
+ "items": {
84
+ "$ref": "#/$defs/region"
85
+ }
86
+ }
87
+ ],
88
+ "description": "Where material may go"
89
+ },
90
+ "keep": {
91
+ "type": "array",
92
+ "items": {
93
+ "$ref": "#/$defs/region"
94
+ },
95
+ "description": "Must stay solid: bosses round bolt holes"
96
+ },
97
+ "avoid": {
98
+ "type": "array",
99
+ "items": {
100
+ "$ref": "#/$defs/region"
101
+ },
102
+ "description": "Must stay empty: holes, clearances (avoid wins over keep)"
103
+ },
104
+ "supports": {
105
+ "type": "array",
106
+ "minItems": 1,
107
+ "items": {
108
+ "$ref": "#/$defs/support"
109
+ }
110
+ },
111
+ "loads": {
112
+ "type": "array",
113
+ "minItems": 1,
114
+ "items": {
115
+ "$ref": "#/$defs/load"
116
+ }
117
+ },
118
+ "cases": {
119
+ "type": "object",
120
+ "additionalProperties": {
121
+ "$ref": "#/$defs/expr"
122
+ },
123
+ "description": "Each load case's weight in the optimisation (default 1); 0 analyses it without optimising for it"
124
+ },
30
125
  "outline": {
31
126
  "type": "object",
32
127
  "additionalProperties": false,
33
128
  "properties": {
34
- "smooth": { "type": "integer", "description": "Smoothing passes (default 4)" },
35
- "min_area": { "$ref": "#/$defs/expr", "description": "Holes and islands smaller than this (mm²) are dropped" }
129
+ "smooth": {
130
+ "type": "integer",
131
+ "description": "Smoothing passes for the outline (2D) or surface (3D), default 4"
132
+ },
133
+ "min_area": {
134
+ "$ref": "#/$defs/expr",
135
+ "description": "Holes and islands smaller than this (mm²) are dropped"
136
+ }
36
137
  }
138
+ },
139
+ "overhang": {
140
+ "type": "string",
141
+ "description": "3D: printable this way up ('+z', '-y', …), or a variable holding it, or 'none': only material supported from below at 45° or less"
37
142
  }
38
143
  },
39
144
  "$defs": {
40
- "expr": { "type": ["number", "string"] },
41
- "point": { "type": "array", "items": { "$ref": "#/$defs/expr" }, "minItems": 2, "maxItems": 2 },
145
+ "expr": {
146
+ "type": [
147
+ "number",
148
+ "string"
149
+ ]
150
+ },
151
+ "point": {
152
+ "type": "array",
153
+ "items": {
154
+ "$ref": "#/$defs/expr"
155
+ },
156
+ "minItems": 2,
157
+ "maxItems": 3
158
+ },
42
159
  "region": {
43
160
  "type": "object",
44
161
  "additionalProperties": false,
45
162
  "properties": {
46
- "at": { "$ref": "#/$defs/point", "description": "The centre, mm" },
47
- "r": { "$ref": "#/$defs/expr", "description": "A circle's radius" },
48
- "size": { "type": "array", "items": { "$ref": "#/$defs/expr" }, "minItems": 2, "maxItems": 2, "description": "A rectangle's width and depth" },
49
- "points": { "type": "array", "items": { "$ref": "#/$defs/point" }, "minItems": 3, "description": "A polygon's corners" },
50
- "label": { "type": "string" }
163
+ "at": {
164
+ "$ref": "#/$defs/point",
165
+ "description": "The centre, mm: [x, y] in 2D, [x, y, z] in 3D"
166
+ },
167
+ "r": {
168
+ "$ref": "#/$defs/expr",
169
+ "description": "A circle's or ball's radius, or a cylinder's"
170
+ },
171
+ "size": {
172
+ "type": "array",
173
+ "items": {
174
+ "$ref": "#/$defs/expr"
175
+ },
176
+ "minItems": 2,
177
+ "maxItems": 3,
178
+ "description": "A rectangle's or box's sides"
179
+ },
180
+ "length": {
181
+ "$ref": "#/$defs/expr",
182
+ "description": "3D: a cylinder's length (with r)"
183
+ },
184
+ "axis": {
185
+ "enum": [
186
+ "x",
187
+ "y",
188
+ "z"
189
+ ],
190
+ "description": "3D: the cylinder's axis (default z)"
191
+ },
192
+ "points": {
193
+ "type": "array",
194
+ "items": {
195
+ "$ref": "#/$defs/point"
196
+ },
197
+ "minItems": 3,
198
+ "description": "2D: a polygon's corners"
199
+ },
200
+ "part": {
201
+ "type": "string",
202
+ "description": "3D: a named part of another design in the project, as it's built: object.part"
203
+ },
204
+ "label": {
205
+ "type": "string"
206
+ },
207
+ "teardrop": {
208
+ "enum": ["up", "down", "+z", "-z", "+y", "-y", "+x", "-x"],
209
+ "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"
210
+ }
51
211
  }
52
212
  },
53
213
  "support": {
54
214
  "type": "object",
55
- "required": ["at"],
215
+ "required": [],
56
216
  "additionalProperties": false,
57
217
  "properties": {
58
- "at": { "$ref": "#/$defs/point" },
59
- "r": { "$ref": "#/$defs/expr", "description": "Holds the material within this radius (a bolt hole's)" },
60
- "fix": { "enum": ["xy", "x", "y"], "description": "Which ways it's held (default both)" },
61
- "label": { "type": "string" }
218
+ "at": {
219
+ "$ref": "#/$defs/point",
220
+ "description": "The centre, mm: [x, y] in 2D, [x, y, z] in 3D"
221
+ },
222
+ "r": {
223
+ "$ref": "#/$defs/expr",
224
+ "description": "A circle's or ball's radius, or a cylinder's"
225
+ },
226
+ "size": {
227
+ "type": "array",
228
+ "items": {
229
+ "$ref": "#/$defs/expr"
230
+ },
231
+ "minItems": 2,
232
+ "maxItems": 3,
233
+ "description": "A rectangle's or box's sides"
234
+ },
235
+ "length": {
236
+ "$ref": "#/$defs/expr",
237
+ "description": "3D: a cylinder's length (with r)"
238
+ },
239
+ "axis": {
240
+ "enum": [
241
+ "x",
242
+ "y",
243
+ "z"
244
+ ],
245
+ "description": "3D: the cylinder's axis (default z)"
246
+ },
247
+ "points": {
248
+ "type": "array",
249
+ "items": {
250
+ "$ref": "#/$defs/point"
251
+ },
252
+ "minItems": 3,
253
+ "description": "2D: a polygon's corners"
254
+ },
255
+ "part": {
256
+ "type": "string",
257
+ "description": "3D: a named part of another design in the project, as it's built: object.part"
258
+ },
259
+ "label": {
260
+ "type": "string"
261
+ },
262
+ "fix": {
263
+ "type": "string",
264
+ "pattern": "^[xyz]+$",
265
+ "description": "Which ways it's held: x, y, z (default all)"
266
+ },
267
+ "teardrop": {
268
+ "enum": ["up", "down", "+z", "-z", "+y", "-y", "+x", "-x"],
269
+ "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"
270
+ }
62
271
  }
63
272
  },
64
273
  "load": {
65
274
  "type": "object",
66
- "required": ["at", "force"],
275
+ "required": [
276
+ "force"
277
+ ],
67
278
  "additionalProperties": false,
68
279
  "properties": {
69
- "at": { "$ref": "#/$defs/point" },
70
- "r": { "$ref": "#/$defs/expr", "description": "Spread over the material within this radius" },
71
- "force": { "$ref": "#/$defs/point", "description": "x and y, in N" },
72
- "case": { "type": "string", "description": "Its load case (default load)" },
73
- "label": { "type": "string" }
280
+ "at": {
281
+ "$ref": "#/$defs/point",
282
+ "description": "The centre, mm: [x, y] in 2D, [x, y, z] in 3D"
283
+ },
284
+ "r": {
285
+ "$ref": "#/$defs/expr",
286
+ "description": "A circle's or ball's radius, or a cylinder's"
287
+ },
288
+ "size": {
289
+ "type": "array",
290
+ "items": {
291
+ "$ref": "#/$defs/expr"
292
+ },
293
+ "minItems": 2,
294
+ "maxItems": 3,
295
+ "description": "A rectangle's or box's sides"
296
+ },
297
+ "length": {
298
+ "$ref": "#/$defs/expr",
299
+ "description": "3D: a cylinder's length (with r)"
300
+ },
301
+ "axis": {
302
+ "enum": [
303
+ "x",
304
+ "y",
305
+ "z"
306
+ ],
307
+ "description": "3D: the cylinder's axis (default z)"
308
+ },
309
+ "points": {
310
+ "type": "array",
311
+ "items": {
312
+ "$ref": "#/$defs/point"
313
+ },
314
+ "minItems": 3,
315
+ "description": "2D: a polygon's corners"
316
+ },
317
+ "part": {
318
+ "type": "string",
319
+ "description": "3D: a named part of another design in the project, as it's built: object.part"
320
+ },
321
+ "label": {
322
+ "type": "string"
323
+ },
324
+ "force": {
325
+ "$ref": "#/$defs/point",
326
+ "description": "x, y (and z), in N"
327
+ },
328
+ "case": {
329
+ "type": "string",
330
+ "description": "Its load case (default load)"
331
+ },
332
+ "teardrop": {
333
+ "enum": ["up", "down", "+z", "-z", "+y", "-y", "+x", "-x"],
334
+ "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"
335
+ }
74
336
  }
75
337
  }
76
338
  }