@rulecad/cad 0.7.12 → 0.7.26

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/lib/links.mjs CHANGED
@@ -4,13 +4,13 @@ import path from 'node:path';
4
4
  import { fromParts, fromShapes, encode, check as checkLink, expand } from '@rulecad/model-link';
5
5
  import { fmt } from './rules.mjs';
6
6
  import { paths, config } from './workspace.mjs';
7
- import { host } from './host.mjs';
7
+ import { host, readJson } from './host.mjs';
8
8
  import { pcbEngine } from './design.mjs';
9
9
  import { shapes, motionData } from './assembly.mjs';
10
10
  import { slotOf } from './threemf.mjs';
11
11
 
12
12
  /** The project's filaments: { base: { slot: 1, … }, legend: { slot: 2, … } } in project.json. @param {string} project */
13
- export const filaments = (project) => JSON.parse(host.readText(path.join(paths.project(project), 'project.json'))).filaments || {};
13
+ export const filaments = (project) => readJson(path.join(paths.project(project), 'project.json')).filaments || {};
14
14
  /** The filaments in AMS slot order, for the print file: [{ colour }, …], slot 1 first. */
15
15
  export const slots = (fil) => { const out = []; for (const f of Object.values(fil)) out[(f.slot || 1) - 1] = f; return Array.from(out, (f) => f || {}); };
16
16
 
@@ -54,6 +54,19 @@ export async function objectModel(b, { title, version, src, set, filaments: fil
54
54
 
55
55
  /** A built assembly as a model: each shape once and placed (nine keys cost one keycap), its boards' views, its joints. */
56
56
  export async function assemblyModel(s, { title, versions, filaments: fil = {}, noRules = false }) {
57
+ const placed = shapes(s.parts), list = placed.shapes.length ? placed.place.map(([i, ...m], n) => { const p = placed.shapes[i].part; return { shape: i, role: p.role, label: p.object || p.label, slot: slotOf(fil, p.filament), triangles: triangles(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; }) : [];
58
+ // A pose that sets items' variables draws some parts differently (a flexure bent): each such part's shape in that
59
+ // pose goes in the link as a "pose" part, placed as the part is, to be swapped in when the page shows the pose
60
+ const alts = [];
61
+ if (list.length) for (const pose of Object.keys(s.motion?.poses || {})) {
62
+ const t = s.at(pose);
63
+ t.parts.forEach((q, n) => {
64
+ const p = s.parts[n];
65
+ if (!p || !q || q.name !== p.name || q.hash === p.hash) return;
66
+ alts.push({ of: n, pose });
67
+ list.push({ shape: `${q.hash}@pose`, role: 'pose', label: list[n].label, triangles: triangles(q.localTriangles), matrix: list[n].matrix, name: `${p.name}@${pose}` });
68
+ });
69
+ }
57
70
  const model = {
58
71
  title, version: versions, src: `${s.project}/${s.name}`, // object versions are in version: the file name stays short
59
72
  rules: [],
@@ -66,10 +79,13 @@ export async function assemblyModel(s, { title, versions, filaments: fil = {}, n
66
79
  for (const o of boards) for (const [n, svg] of await pcb.views(o.built.circuit)) views.push([boards.length > 1 ? `${o.objName} ${n}` : n, svg]);
67
80
  return { views };
68
81
  })()),
69
- ...fromShapes(shapes(s.parts).shapes.length ? (() => {
70
- const placed = shapes(s.parts);
71
- return placed.place.map(([i, ...m], n) => { const p = placed.shapes[i].part; return { shape: i, role: p.role, label: p.object || p.label, slot: slotOf(fil, p.filament), triangles: triangles(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; });
72
- })() : []),
82
+ ...fromShapes(list),
73
83
  };
74
- return Object.assign(model, motionData(s));
84
+ Object.assign(model, motionData(s));
85
+ if (alts.length) { // the shapes parts take in other poses, on the same items, and which pose shows which
86
+ model.motion.part.push(...alts.map((x) => model.motion.part[x.of]));
87
+ model.motion.swap = {};
88
+ alts.forEach((x, i) => (model.motion.swap[x.pose] ||= []).push([x.of, list.length - alts.length + i]));
89
+ }
90
+ return model;
75
91
  }
@@ -0,0 +1,131 @@
1
+ // The live view of a flexure being shaped (@rulecad/flexures shapeCurve): a page that draws each round of the search
2
+ // as it goes (every shape tried, faint; the best so far at its thickness, mirrored if it is, with how it bends when
3
+ // drawn), charts its peak strain and stored energy, can look back at any round, and can stop the run. Like the
4
+ // optimiser's live view (live.mjs), the server runs in a worker, since the search blocks the main thread: the main
5
+ // thread posts each round, and the page's stop button sets a shared flag it reads between rounds.
6
+ import http from 'node:http';
7
+ import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
8
+
9
+ /**
10
+ * Starts the server; resolves once it listens.
11
+ * @param {{ port?: number, host?: string, title: string, job: { region: { lo: number[], hi: number[] }, root: number[], tip: number[], mirror?: number, travel?: number, moves?: string } }} o
12
+ * @returns {Promise<{ url: string, round: (r: object) => void, stopped: () => boolean, close: (summary?: string, o?: { hold?: number }) => Promise<void> }>}
13
+ */
14
+ export function liveShape({ port = 8090, host = '127.0.0.1', title, job }) {
15
+ const flag = new Int32Array(new SharedArrayBuffer(4));
16
+ const setup = { room: job.region, root: job.root, tip: job.tip, mirror: job.mirror ?? null, travel: job.travel ?? 0, moves: job.moves ?? 'y' };
17
+ const worker = new Worker(new URL(import.meta.url), { workerData: { port, host, title, flag, setup } });
18
+ return new Promise((resolve, reject) => {
19
+ worker.once('error', reject);
20
+ worker.once('message', (m) => {
21
+ if (m.error) { worker.terminate(); reject(new Error(`the live view can't listen on ${host}:${port}: ${m.error}`)); return; }
22
+ worker.off('error', reject).on('error', (e) => console.error(`the live view stopped: ${e.message}`));
23
+ resolve({
24
+ url: `http://${host === '0.0.0.0' ? 'localhost' : host}:${m.listening}/`,
25
+ // A round: the paths thinned to every other point (plenty to see by), numbers to three figures
26
+ round: (r) => {
27
+ const thin = (p) => p?.filter((_, i, a) => i % 2 === 0 || i === a.length - 1).map(([x, y]) => [+x.toFixed(2), +y.toFixed(2)]);
28
+ worker.postMessage({ phase: r.phase, round: r.round, evaluations: r.evaluations, limit: r.limit, want: r.want,
29
+ tried: r.tried.map(thin), best: r.best && { ...r.best, path: r.best.path.map(([x, y]) => [+x.toFixed(2), +y.toFixed(2)]), at: r.best.at?.map((t) => +t.toFixed(3)), drawn: thin(r.best.drawn) } });
30
+ },
31
+ stopped: () => Atomics.load(flag, 0) === 1,
32
+ close: (summary, { hold = 0 } = {}) => new Promise((done) => { worker.once('exit', () => done()); worker.postMessage({ done: summary ?? 'finished', hold }); }),
33
+ });
34
+ });
35
+ });
36
+ }
37
+
38
+ const page = (title) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
39
+ <title>${title}</title>
40
+ <style>body{font:15px system-ui;background:#111;color:#eee;margin:16px;max-width:900px}svg{width:100%;background:#000;border-radius:6px}#view{height:55vh}
41
+ #chart{height:150px;margin-top:8px}#scrub{display:flex;gap:8px;align-items:center;position:sticky;bottom:0;background:#111;padding:10px 0;border-top:1px solid #222}#scrub input{flex:1;height:32px}#at-round{color:#aaa;font-size:13px;min-width:6em}
42
+ table{border-collapse:collapse;margin:10px 0;width:100%}td{padding:3px 8px 3px 0;vertical-align:top}td:first-child{color:#999;white-space:nowrap;width:1%}button{font:inherit;padding:8px 16px;border-radius:6px;border:0;background:#d33;color:#fff}button:disabled{background:#555}#live{background:#357}.key{color:#aaa;font-size:13px}.key b{display:inline-block;width:14px;height:4px;vertical-align:middle;margin:0 4px 0 12px}</style>
43
+ <h2>${title}</h2><div id="state">waiting for the first round…</div>
44
+ <svg id="view"></svg>
45
+ <div class="key"><b style="background:#e07a1f"></b>best so far<b style="background:#e07a1f55"></b>tried this round<b style="background:#999"></b>the best, drawn back<b style="background:#4a8"></b>its room</div>
46
+ <svg id="chart" viewBox="0 0 900 150" preserveAspectRatio="none"></svg>
47
+ <div class="key"><b style="background:#6cf"></b>peak strain, share of the limit<b style="background:#fc6"></b>energy stored, share of what's asked</div>
48
+ <div id="scrub"><span id="at-round"></span><input type="range" id="at" min="0" max="0" value="0"><button id="live" disabled>Live</button></div>
49
+ <table id="facts"></table><p><button id="stop">Stop the run</button> <span id="note"></span></p>
50
+ <script>
51
+ const view = document.getElementById('view'), chart = document.getElementById('chart'), facts = document.getElementById('facts'), state = document.getElementById('state');
52
+ const at = document.getElementById('at'), live = document.getElementById('live'), stop = document.getElementById('stop');
53
+ let setup = null, history = [], newest = null, follow = true, finished = null, t0 = Date.now();
54
+ const esc = (t) => String(t).replace(/[&<]/g, (c) => c === '&' ? '&amp;' : '&lt;'), pct = (x) => (x * 100).toFixed(2) + '%';
55
+ const line = (p, attrs) => p && p.length ? '<polyline points="' + p.map(([x, y]) => x + ',' + (-y)).join(' ') + '" fill="none" ' + attrs + '/>' : '';
56
+ const mirrored = (p) => setup.mirror == null ? null : p && p.map(([x, y]) => [x, 2 * setup.mirror - y]);
57
+ // The best shape at its thickness: each span a line as thick as the arm is there, round-capped
58
+ const thick = (p, at) => p.slice(1).map((b, i) => { const a = p[i]; return '<line x1="' + a[0] + '" y1="' + (-a[1]) + '" x2="' + b[0] + '" y2="' + (-b[1]) + '" stroke="#e07a1f" stroke-width="' + ((at[i] + at[i + 1]) / 2 || 1) + '" stroke-linecap="round"/>'; }).join('');
59
+ function draw(f) {
60
+ const r = setup.room, ys = [r.lo[1], r.hi[1], ...(setup.mirror != null ? [2 * setup.mirror - r.lo[1], 2 * setup.mirror - r.hi[1]] : [])];
61
+ const lo = [Math.min(r.lo[0], setup.tip[0], setup.root[0]) - 4, Math.min(...ys) - 4], hi = [Math.max(r.hi[0], setup.tip[0], setup.root[0]) + 4, Math.max(...ys) + 4];
62
+ view.setAttribute('viewBox', lo[0] + ' ' + (-hi[1]) + ' ' + (hi[0] - lo[0]) + ' ' + (hi[1] - lo[1]));
63
+ const box = (y0, y1) => '<rect x="' + r.lo[0] + '" y="' + (-Math.max(y0, y1)) + '" width="' + (r.hi[0] - r.lo[0]) + '" height="' + Math.abs(y1 - y0) + '" fill="none" stroke="#4a8" stroke-width="0.25" stroke-dasharray="1 1"/>';
64
+ let s = box(r.lo[1], r.hi[1]) + (setup.mirror != null ? box(2 * setup.mirror - r.lo[1], 2 * setup.mirror - r.hi[1]) : '');
65
+ for (const p of f.tried || []) s += line(p, 'stroke="#e07a1f" stroke-opacity="0.25" stroke-width="0.3"') + line(mirrored(p), 'stroke="#e07a1f" stroke-opacity="0.25" stroke-width="0.3"');
66
+ if (f.best) {
67
+ s += line(f.best.drawn, 'stroke="#999" stroke-width="0.4"') + line(mirrored(f.best.drawn), 'stroke="#999" stroke-width="0.4"');
68
+ if (f.best.at) s += thick(f.best.path, f.best.at) + (setup.mirror != null ? thick(mirrored(f.best.path), f.best.at) : '');
69
+ }
70
+ s += [setup.root, setup.tip].map(([x, y]) => '<circle cx="' + x + '" cy="' + (-y) + '" r="0.8" fill="#4a8"/>').join('');
71
+ view.innerHTML = s;
72
+ const b = f.best || {};
73
+ const rows = [['Round', f.round + ' (' + f.phase + ')'], ['Shapes tried', f.evaluations], ['Run time', (f.elapsed ?? 0).toFixed(0) + ' s'],
74
+ ...(b.strain != null ? [['Peak strain', pct(b.strain) + ' (' + pct(b.strain / f.limit) + ' of the ' + pct(f.limit) + ' it may reach)'], ['Energy stored', b.energy.toFixed(1) + ' mJ printed ' + b.width.toFixed(1) + ' mm tall (asked: ' + f.want.toFixed(1) + ')']] : []),
75
+ ...(b.why && b.why.length ? [['Still wrong', b.why.join('; ')]] : b.strain != null ? [['Still wrong', 'nothing']] : [])];
76
+ facts.innerHTML = [...(finished ? [['Result', finished]] : []), ...rows].map(([k, v]) => '<tr><td>' + esc(k) + '</td><td>' + esc(v) + '</td></tr>').join('');
77
+ document.getElementById('at-round').textContent = 'round ' + f.round;
78
+ state.textContent = finished || (f.phase + ' · round ' + f.round);
79
+ }
80
+ function plot(shown) {
81
+ const n = history.length; if (n < 2) { chart.innerHTML = ''; return; }
82
+ const path = (k, colour) => { const ys = history.map((h) => Math.min(2, h[k] ?? 2)); return '<polyline points="' + ys.map((v, i) => (i / (n - 1) * 900) + ',' + (145 - v / 2 * 140)).join(' ') + '" fill="none" stroke="' + colour + '" stroke-width="2"/>'; };
83
+ const one = 145 - 70, x = shown / (n - 1) * 900;
84
+ chart.innerHTML = '<line x1="0" x2="900" y1="' + one + '" y2="' + one + '" stroke="#555" stroke-dasharray="4 4"/><text x="4" y="' + (one - 4) + '" fill="#888" font-size="11">100%</text>' + path('strain', '#6cf') + path('energy', '#fc6') + '<line x1="' + x + '" x2="' + x + '" y1="0" y2="150" stroke="#fff8"/>';
85
+ }
86
+ async function lookAt(k) {
87
+ const n = history.length; k = Math.max(0, Math.min(n - 1, k)); at.value = k; follow = k === n - 1; live.disabled = follow;
88
+ const f = follow && newest ? newest : await (await fetch('round/' + k)).json();
89
+ draw(f); plot(k);
90
+ }
91
+ at.oninput = () => lookAt(Number(at.value)); live.onclick = () => lookAt(history.length - 1);
92
+ const events = new EventSource('events');
93
+ events.onmessage = (e) => { const m = JSON.parse(e.data);
94
+ if (m.setup) setup = m.setup; if (m.t0) t0 = m.t0; if (m.history) history = m.history; if (m.frame) newest = m.frame;
95
+ if (m.done) { finished = m.done; stop.disabled = true; events.close(); }
96
+ at.max = Math.max(0, history.length - 1);
97
+ if (follow && newest && setup) { at.value = at.max; draw(newest); }
98
+ plot(Number(at.value)); };
99
+ stop.onclick = async () => { stop.disabled = true; await fetch('stop', { method: 'POST' }); document.getElementById('note').textContent = 'stopping after this round'; };
100
+ </script>`;
101
+
102
+ if (!isMainThread && workerData?.flag && workerData?.setup) {
103
+ const { port, host, title, flag, setup } = workerData, clients = new Set(), frames = [], history = [], t0 = Date.now();
104
+ let latest = null, sent = null, done = null;
105
+ const send = (res, m) => res.write(`data: ${JSON.stringify(m)}\n\n`);
106
+ const server = http.createServer((req, res) => {
107
+ if (req.url === '/events') {
108
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
109
+ send(res, { setup, t0, history, ...(latest ? { frame: latest } : {}), ...(done ? { done } : {}) });
110
+ clients.add(res); req.on('close', () => clients.delete(res));
111
+ } else if (req.url.startsWith('/round/') && frames[Number(req.url.slice(7))]) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(frames[Number(req.url.slice(7))]));
112
+ } else if (req.url === '/stop' && req.method === 'POST') { Atomics.store(flag, 0, 1); res.end('stopping'); }
113
+ else if (req.url === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(page(title)); }
114
+ else { res.writeHead(404); res.end(); }
115
+ });
116
+ // At most four updates a second, whatever the search's pace
117
+ const tick = setInterval(() => { if (latest && latest !== sent) { sent = latest; const m = { history, frame: latest }; for (const c of clients) send(c, m); } }, 250);
118
+ parentPort.on('message', (m) => {
119
+ if (m.done) {
120
+ done = m.done; clearInterval(tick);
121
+ for (const c of clients) { send(c, { history, ...(latest ? { frame: latest } : {}), done }); c.end(); }
122
+ const shut = () => { server.close(); server.closeAllConnections(); parentPort.close(); };
123
+ if (m.hold) setTimeout(shut, m.hold); else shut();
124
+ return;
125
+ }
126
+ m.elapsed = (Date.now() - t0) / 1000; latest = m; frames.push(m);
127
+ history.push({ strain: m.best?.strain != null ? m.best.strain / m.limit : null, energy: m.best?.energy != null ? m.best.energy / m.want : null });
128
+ });
129
+ server.once('error', (e) => parentPort.postMessage({ error: e.code || e.message }));
130
+ server.listen(port, host, () => parentPort.postMessage({ listening: server.address().port }));
131
+ }
package/lib/live.mjs CHANGED
@@ -31,7 +31,7 @@ export function liveView({ port = 8090, host = '127.0.0.1', title }) {
31
31
  const { nx, ny, nz, h } = s.grid;
32
32
  // A 3D grid's densities too, a byte a cell, for its surface (drawn when the page asks for it)
33
33
  const cells = nz > 1 ? Uint8Array.from(s.density, (d) => Math.round(d * 255)) : null;
34
- worker.postMessage({ grid: { nx, ny, nz, h }, step: s.step, steps: s.steps, compliance: s.compliance, change: s.change, beta: s.beta, volume: s.volume, stress: s.stress, views: list, cells },
34
+ worker.postMessage({ grid: { nx, ny, nz, h }, step: s.step, steps: s.steps, compliance: s.compliance, change: s.change, beta: s.beta, volume: s.volume, stress: s.stress, travel: s.travel, views: list, cells },
35
35
  [...list.map((v) => v.image.buffer), ...(cells ? [cells.buffer] : [])]);
36
36
  },
37
37
  stopped: () => Atomics.load(flag, 0) === 1,
@@ -75,7 +75,7 @@ function table() {
75
75
  ...(finished || !follow ? [] : [['Time left', 'at most ' + time(f.left) + ' (it may settle sooner)']]),
76
76
  ['Compliance', fig(f.compliance) + ' N·mm, from ' + fig(history.compliance[0]) + (history.compliance[0] > f.compliance ? ': ' + fig(history.compliance[0] / f.compliance) + ' times as stiff' : '')],
77
77
  ['Change', fig(f.change) + ' (the most any cell moved this step)'], ['Sharpness', f.beta],
78
- ...(f.volume != null ? [['Material', fig(f.volume * 100) + '% of the space']] : []), ...(f.stress != null ? [['Peak stress', fig(f.stress) + ' MPa']] : []),
78
+ ...(f.volume != null ? [['Material', fig(f.volume * 100) + '% of the space']] : []), ...(f.stress != null ? [['Peak stress', fig(f.stress) + ' MPa']] : []), ...(f.travel != null ? [['Output travel', fig(f.travel) + ' mm its way']] : []),
79
79
  ['Cells', [f.grid.nx, f.grid.ny, f.grid.nz].filter(Boolean).join(' × ') + (f.grid.h ? ' of ' + f.grid.h + ' mm' : '') + ' (' + (f.grid.nx * f.grid.ny * (f.grid.nz || 1)).toLocaleString('en-GB') + ')'],
80
80
  ] : [];
81
81
  document.getElementById('at-step').textContent = f ? 'step ' + f.step : '';
package/lib/optimise.mjs CHANGED
@@ -7,11 +7,12 @@
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import crypto from 'node:crypto';
10
- import { host } from './host.mjs';
10
+ import { host, readJson } 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, bounds, resultant, printable } from '@rulecad/topopt';
14
+ import { discretise, optimise, outlines, surface, area, bounds, resultant, printable, refine, despike } from '@rulecad/topopt';
15
+ import { islands } from '@rulecad/printcheck';
15
16
  import { threadsBackend } from '@rulecad/fea/threads'; // the solver's products shared over the machine's cores
16
17
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
17
18
 
@@ -26,7 +27,7 @@ export const hasProblem = (project, ref) => host.exists(problemFile(project, Str
26
27
  export async function readProblem(project, ref) {
27
28
  const [name, variant] = String(ref).split(':'), file = problemFile(project, name);
28
29
  if (!host.exists(file)) throw new Error(`no problem "${name}" (projects/${project}/problems/${name}.json)`);
29
- const p = JSON.parse(host.readText(file));
30
+ const p = readJson(file);
30
31
  if (variant && !p.variants?.[variant]) throw new Error(`problem ${name} has no variant "${variant}" (variants: ${Object.keys(p.variants || {}).join(', ') || 'none'})`);
31
32
  const uses = [...new Set([...(p.uses || []), p.material])];
32
33
  let values;
@@ -53,7 +54,11 @@ export async function readProblem(project, ref) {
53
54
  // A teardrop's point: a direction, or up or down the build direction (+z, as drawn, when it's free)
54
55
  const point = (t) => { const up = overhang && overhang !== 'none' ? overhang : '+z'; return t === 'up' ? up : t === 'down' ? (up[0] === '-' ? '+' : '-') + up[1] : t; };
55
56
  const region = async (r) => {
56
- if (r.part) return { triangles: await part(r.part), part: r.part };
57
+ if (r.part) { // with where it is (its box's centre), for a load's or support's resultant
58
+ const triangles = await part(r.part), lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
59
+ for (const t of triangles) for (const q of t) for (let a = 0; a < 3; a++) { lo[a] = Math.min(lo[a], q[a]); hi[a] = Math.max(hi[a], q[a]); }
60
+ return { triangles, part: r.part, at: lo.map((x, a) => (x + hi[a]) / 2) };
61
+ }
57
62
  if (r.points) return { points: r.points.map(pt) };
58
63
  if (r.size) return { at: pt(r.at), size: r.size.map(ev) };
59
64
  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
@@ -72,11 +77,16 @@ export async function readProblem(project, ref) {
72
77
  ...(p.filter != null ? { filter: ev(p.filter) } : {}), ...(p.penal != null ? { penal: ev(p.penal) } : {}),
73
78
  ...(p.projection != null ? { projection: p.projection } : {}), ...(p.steps != null ? { steps: p.steps } : {}),
74
79
  ...(overhang && overhang !== 'none' ? { overhang } : {}),
80
+ // A mechanism: where the output should move, along one axis, against a spring; a spring the input pushes against
81
+ ...(p.output ? { output: { ...(await region(p.output)), direction: pt(p.output.direction), ...(p.output.spring != null ? { spring: ev(p.output.spring) } : {}) } } : {}),
82
+ ...(p.input_spring != null ? { input_spring: ev(p.input_spring) } : {}),
75
83
  };
76
84
  if (dim === 2 && !(problem.thickness > 0)) throw new Error(`${path.basename(file)}: a flat (2D) problem needs a thickness`);
77
- const outline = { smooth: p.outline?.smooth ?? 4, minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2 };
85
+ const outline = { smooth: p.outline?.smooth ?? 4, minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2, fine: p.outline?.fine != null ? ev(p.outline.fine) : 1.25 }; // fine: the cells a printable solid is cleaned and drawn on, mm (its own cells if smaller)
78
86
  // A printable solid's surface is kept within the printer's overhang limit too (smoothing can tip faces past it)
79
- if (dim === 3 && problem.overhang) { const n = printerOf(project), pr = resolve({ uses: [n] }).values[n]; outline.overhang = { up: problem.overhang, angle: pr?.overhang ?? 45, bridge: pr?.bridge ?? 5 }; problem.bridge = outline.overhang.bridge; } // (the optimiser bridges half that)
87
+ // (outline.tip: faces the smoothing left steeper than the limit are tipped back to it too; off unless asked, since
88
+ // tipped corners leave dips that slice as islands, and the layers step out no further for it)
89
+ if (dim === 3 && problem.overhang) { const n = printerOf(project), pr = resolve({ uses: [n] }).values[n]; outline.overhang = { up: problem.overhang, angle: pr?.overhang ?? 45, bridge: pr?.bridge ?? 5, layer: pr?.layer ?? 0.2, line: pr?.line ?? 0.42, ...(p.outline?.tip ? { tip: true } : {}) }; problem.bridge = outline.overhang.bridge; } // (the optimiser bridges half that)
80
90
  return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline, critical: !!p.critical };
81
91
  }
82
92
 
@@ -84,9 +94,18 @@ export async function readProblem(project, ref) {
84
94
  * The optimised layout for a problem, from the cache when nothing it depends on has changed. A 2D result has outlines
85
95
  * (closed loops in mm); a 3D one has a mesh ({ vertices, faces }, a closed surface in mm).
86
96
  * @param {string} project @param {string} ref
87
- * @param {{ onStep?: Function, fresh?: boolean }} [options] fresh: run it even if it's cached
97
+ * @param {{ onStep?: Function, onRun?: (why: string) => void, fresh?: boolean }} [options] fresh: run it even if it's cached;
98
+ * onRun: called once if it has to optimise, with why (no result yet, or the solver has changed since the last one)
88
99
  */
89
- export async function optimised(project, ref, { onStep, fresh = false } = {}) {
100
+ // Nodes no cell that may be solid touches (the grid's corners outside a shaped space, the inside of avoided pockets)
101
+ // are held: at the void's near-nothing stiffness they are what the solver crawls through, and they carry no material
102
+ function holdEmpty(spec) {
103
+ const g = makeGrid(spec.grid), dim = spec.grid.nz ? 3 : 2, corners = 1 << dim, on = new Uint8Array(g.nodes);
104
+ for (let e = 0; e < g.cells; e++) if (spec.passive[e] >= 0) for (let k = 0; k < corners; k++) on[g.edof[e * g.cellDofs + dim * k] / dim] = 1;
105
+ for (let m = 0; m < g.nodes; m++) if (!on[m]) for (let a = 0; a < dim; a++) spec.fixed[dim * m + a] = 1;
106
+ return spec;
107
+ }
108
+ export async function optimised(project, ref, { onStep, onRun, fresh = false } = {}) {
90
109
  const r = await readProblem(project, ref), topopt = source('@rulecad/topopt'), [solver] = topopt.split('// ---------- shapes from results ----------');
91
110
  const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
92
111
  // Two keeps: the densities, by the problem and the code that decides them (the slow part), and the shape drawn from
@@ -94,9 +113,14 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
94
113
  // The shape's key holds this file too, so a change to how cad draws a result (anchored below) redraws it
95
114
  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`);
96
115
  if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file)) return { ...JSON.parse(host.readText(file)), cached: true };
97
- const spec = discretise(r.problem), densities = paths.cache('densities', `${digest([VERSION, r.problem, solver, source('@rulecad/fea')])}.json`);
116
+ const spec = holdEmpty(discretise(r.problem)), densities = paths.cache('densities', `${digest([VERSION, r.problem, solver, source('@rulecad/fea')])}.json`);
117
+ // A mark that this problem has been optimised before (by any solver), so a run can say whether it's the solver that changed
118
+ const seen = paths.cache('densities', `${digest([VERSION, r.problem])}.seen`);
119
+ if (!fresh && !process.env.CAD_NO_CACHE && !host.exists(densities)) onRun?.(host.exists(seen) ? 'the solver has changed since its last result' : 'no result yet');
120
+ else if (fresh) onRun?.('asked to run afresh');
98
121
  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, { backend: threadsBackend, onStep: onStep && ((st) => onStep({ ...st, grid: spec.grid })) });
99
122
  if (!host.exists(densities)) host.writeText(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
123
+ if (!host.exists(seen)) host.writeText(seen, '');
100
124
  // Regions as data: a part's triangles are named, not copied
101
125
  const named = (list) => list.map(({ triangles, ...x }) => x);
102
126
  const shape = r.dim === 2 ? (() => {
@@ -107,27 +131,67 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
107
131
  // thin members come out thinner than they are)
108
132
  // Printed without supports: before it's drawn at a level, whatever wouldn't print at that level (hanging with nothing
109
133
  // under it) is emptied (printable, in topopt); kept regions stay. A bridge may run out half the printer's span.
110
- const ov = r.outline.overhang, keep = Uint8Array.from(spec.passive, (p) => (p === 1 ? 1 : 0)), emptied = new Map();
111
- const clean = (iso) => {
112
- if (!ov) return o.density;
113
- const c = printable(spec.grid, o.density, { up: ov.up, iso, keep, reach: Math.floor(ov.bridge / 2 / spec.grid.h) });
114
- emptied.set(iso, c.emptied);
115
- return c.density;
134
+ const ov = r.outline.overhang, coarseKeep = Uint8Array.from(spec.passive, (p) => (p === 1 ? 1 : 0)), emptied = new Map();
135
+ const cleaned = (grid, density, keep, iso) => {
136
+ if (!ov) return density;
137
+ const reach = Math.floor(ov.bridge / 2 / grid.h);
138
+ // Spikes off the underside first (a hanging cell with few neighbours), then whatever is left hanging, in turn until neither finds any
139
+ let d = density, gone = 0;
140
+ for (let round = 0; round < 10; round++) {
141
+ const sp = despike(grid, d, { up: ov.up, iso, keep }), c = printable(grid, sp.density, { up: ov.up, iso, keep, reach });
142
+ d = c.density; gone += sp.emptied + c.emptied;
143
+ if (!sp.emptied && !c.emptied) break;
144
+ }
145
+ emptied.set(iso, gone);
146
+ return d;
116
147
  };
117
- const want = o.density.reduce((t, d) => t + d, 0) * spec.grid.h ** 3, at = (iso) => surface(spec.grid, clean(iso), spec.origin, { smooth: r.outline.smooth, iso, overhang: ov });
118
- let lo = 0.2, hi = 0.8, best = at(0.5), iso = 0.5;
148
+ // The surface's level, found so the solid holds as much material as the optimised densities do (drawn at 0.5,
149
+ // thin members come out thinner than they are): found on the grid it was optimised on, which is quick
150
+ const want = o.density.reduce((t, d) => t + d, 0) * spec.grid.h ** 3, draw = (grid, density, keep, iso) => surface(grid, cleaned(grid, density, keep, iso), spec.origin, { smooth: r.outline.smooth, iso, overhang: ov });
151
+ let lo = 0.2, hi = 0.8, best = draw(spec.grid, o.density, coarseKeep, 0.5), iso = 0.5;
119
152
  for (let k = 0; k < 10 && Math.abs(meshVolume(best.vertices, best.faces) / want - 1) > 0.003; k++) {
120
153
  if (meshVolume(best.vertices, best.faces) < want) hi = iso; else lo = iso; // a lower level encloses more
121
- iso = (lo + hi) / 2; best = at(iso);
154
+ iso = (lo + hi) / 2; best = draw(spec.grid, o.density, coarseKeep, iso);
155
+ }
156
+ // Then drawn on a finer grid (cells no bigger than the outline's fine size, 1 mm), so the cleaning works at nearer
157
+ // the printer's resolution: between two coarse cells the surface can dip under the overhang line, which sliced is an
158
+ // island; on the fine grid those dips are cells of their own, and go. One correction of the level for the volume.
159
+ const cells = spec.grid.nx * spec.grid.ny * spec.grid.nz, factor = ov ? Math.max(1, Math.min(Math.ceil(spec.grid.h / (r.outline.fine ?? 1) - 1e-9), Math.floor(Math.cbrt(2e6 / cells)))) : 1; // and no more than about two million fine cells
160
+ const fine = factor > 1 ? refine(spec.grid, o.density, factor, { keep: coarseKeep, smooth: 1 }) : null;
161
+ let cleared = 0;
162
+ if (fine) {
163
+ best = draw(fine.grid, fine.density, fine.keep, iso);
164
+ const ratio = meshVolume(best.vertices, best.faces) / want;
165
+ if (Math.abs(ratio - 1) > 0.01) { iso = Math.min(0.8, Math.max(0.2, iso + (ratio - 1) * 0.3)); best = draw(fine.grid, fine.density, fine.keep, iso); } // a touch up or down the level
166
+ // Then as the printer will see it: sliced into layers, each against the one below. Wherever a layer's region has
167
+ // nothing under it (an island, which the printer lays on air), the fine cells it starts from are emptied, the
168
+ // cleaning takes whatever hung on them, and it's drawn again, until a slice finds none (each round a redraw)
169
+ const { nx, ny, nz, h } = fine.grid, [ox, oy, oz] = spec.origin;
170
+ if ('xyz'.indexOf(ov.up[1]) === 2) for (let round = 0; round < 4; round++) { // (the slicer's layers are along z: a part is drawn in its print orientation); a safety net: the drawing leaves none as a rule
171
+ const found = islands(best.faces.map((f) => f.map((n) => best.vertices[n])), { layer: ov.layer, overhang: ov.angle, line: ov.line }).islands;
172
+ if (!found.length) break;
173
+ let hit = 0;
174
+ const clear = (i, j, k) => { if (i < 0 || i >= nx || j < 0 || j >= ny || k < 0 || k >= nz) return 0; const e = (k * ny + j) * nx + i; if (fine.density[e] > 0 && !fine.keep[e]) { fine.density[e] = 0; return 1; } return 0; };
175
+ for (const isl of found) {
176
+ let own = 0;
177
+ for (const [x, y] of isl.cells) { const i = Math.floor((x - ox) / h), j = Math.floor((y - oy) / h), k0 = Math.floor((isl.z - oz) / h); own += clear(i, j, k0) + clear(i, j, k0 + 1); } // the cell the island starts in and the one above it
178
+ // Its own cells already empty: the island is drawn from the cells round them, so those go too
179
+ if (!own) for (const [x, y] of isl.cells) { const i0 = Math.floor((x - ox) / h), j0 = Math.floor((y - oy) / h), k0 = Math.floor((isl.z - oz) / h); for (let k = k0; k <= k0 + 1; k++) for (let j = j0 - 1; j <= j0 + 1; j++) for (let i = i0 - 1; i <= i0 + 1; i++) own += clear(i, j, k); }
180
+ hit += own;
181
+ }
182
+ cleared += hit;
183
+ if (!hit) break;
184
+ best = draw(fine.grid, fine.density, fine.keep, iso);
185
+ }
122
186
  }
123
187
  const anchors = [...r.problem.supports, ...r.problem.loads, ...(r.problem.keep || [])].map(bounds);
124
- const { vertices, faces, dropped } = anchored(best, anchors, spec.grid.h);
125
- return { mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces }, solid: meshVolume(vertices, faces), iso, ...(dropped.length ? { dropped } : {}), ...(emptied.get(iso) ? { emptied: emptied.get(iso) } : {}) };
188
+ const { vertices, faces, dropped } = anchored(best, anchors, (fine ?? { grid: spec.grid }).grid.h);
189
+ return { mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces }, solid: meshVolume(vertices, faces), iso, ...(dropped.length ? { dropped } : {}), ...(emptied.get(iso) ? { emptied: emptied.get(iso) } : {}), ...(cleared ? { cleared } : {}) };
126
190
  })();
127
191
  const result = {
128
192
  problem: ref, title: r.title, hash, dim: r.dim, material: r.material.name, ...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
129
193
  grid: spec.grid, origin: spec.origin, regions: { keep: named(spec.regions.keep), avoid: named(spec.regions.avoid) }, ...shape,
130
- volume: o.volume, compliance: o.compliance, cases: o.cases, ...(o.unsupported ? { unsupported: o.unsupported } : {}), ...(o.stress ? { stress: o.stress } : {}), overhang: r.problem.overhang || null,
194
+ volume: o.volume, compliance: o.compliance, cases: o.cases, ...(o.unsupported ? { unsupported: o.unsupported } : {}), ...(o.mechanism ? { mechanism: o.mechanism } : {}), ...(o.stress ? { stress: o.stress } : {}), overhang: r.problem.overhang || null,
131
195
  steps: o.steps, converged: o.converged, seconds: o.seconds, history: o.history, density: Array.from(o.density, (d) => round(d, 3)),
132
196
  supports: named(r.problem.supports), loads: named(r.problem.loads),
133
197
  };
@@ -190,7 +254,7 @@ export async function analysePart(triangles, project, ref, { cell } = {}) {
190
254
  const { size, moment } = resultant(problem.loads.filter((l) => l.case === name));
191
255
  return measures(name, size, moment, a, c, density, { nx, ny, nz: 1, h }, [x0, y0]);
192
256
  });
193
- return { problem: ref, dim: 2, material: r.material, critical: r.critical, cases, volume: volume(triangles), grid: { nx, ny, h }, origin: [x0, y0], density };
257
+ return { problem: ref, dim: 2, material: r.material, critical: r.critical, cases, thin: a.thin, volume: volume(triangles), grid: { nx, ny, h }, origin: [x0, y0], density };
194
258
  }
195
259
 
196
260
  // A solid part on the problem's grid: the part itself is the space (keep and avoid regions don't apply), so the
@@ -201,7 +265,7 @@ function analyseSolid(triangles, r, cell) {
201
265
  if (!density.some((d) => d)) throw new Error('the part is smaller than one cell of the problem: use a smaller cell');
202
266
  const a = analyse({ grid: g, density, material: problem.material, fixed: spec.fixed, loads: spec.loads.map((l) => l.force), backend: threadsBackend });
203
267
  const cases = spec.loads.map((l, c) => measures(l.name, l.size, l.moment, a, c, density, spec.grid, spec.origin));
204
- return { problem: r.ref, dim: 3, material: r.material, critical: r.critical, cases, volume: volume(triangles), grid: spec.grid, origin: spec.origin, density };
268
+ return { problem: r.ref, dim: 3, material: r.material, critical: r.critical, cases, thin: a.thin, volume: volume(triangles), grid: spec.grid, origin: spec.origin, density };
205
269
  }
206
270
 
207
271
  // A load case's numbers: how far the load moves along itself (compliance over force) and the stiffness (a twist: the
package/lib/parts.mjs CHANGED
@@ -1,12 +1,38 @@
1
1
  // A design's result as parts, and its shapes as faces: no file or process access, so the sandboxed runner
2
2
  // (sandbox-run.mjs) uses them as the build does.
3
3
  import jscad from '@jscad/modeling';
4
+ import { CadError, near } from './errors.mjs';
5
+
6
+ // A design's result split into its shapes and, for a lamina mechanism (@rulecad/flexures lamina()), what its checks
7
+ // found and how it moves: plain data, so it crosses the sandbox and the cache with the parts.
8
+ export function unpack(made) {
9
+ const isLamina = made && typeof made === 'object' && !Array.isArray(made) && made.mechanism && made.parts && Array.isArray(made.findings);
10
+ if (!isLamina) return { shapes: made, mechanism: null };
11
+ return { shapes: made.parts, mechanism: { ...made.mechanism, findings: made.findings, energy: made.energy, ...(made.frames ? { frames: made.frames } : {}) } };
12
+ }
13
+
14
+ // What main(v) is given: the values and the tool's helpers (extras). Rules the code reads directly
15
+ // (v.mx.housing_top) are noted in `read`, so estimates a design relies on get flagged. A name that isn't there is
16
+ // refused: a misspelt v.widht would otherwise come through as undefined, and quietly draw another shape. `optional`
17
+ // names may be absent: the display's own inputs, and what only some designs get (layouts, problems, the board engine).
18
+ export function watch(values, extras = {}, optional = []) {
19
+ const read = new Set(), may = new Set([...optional, 'layouts', 'problems', 'pcb', 'then', 'toJSON']);
20
+ const given = { ...Object.fromEntries(Object.entries(values).map(([k, x]) => [k, x && typeof x === 'object'
21
+ ? new Proxy(x, { get: (t, r) => { if (typeof r === 'string' && r in t) read.add(`${k}.${r}`); return t[r]; } }) : x])), ...extras };
22
+ const v = new Proxy(given, { get: (t, r) => {
23
+ if (typeof r !== 'string' || r in t || may.has(r)) return t[r];
24
+ const guess = near(r, Object.keys(t));
25
+ throw new CadError('design.unknown', `v.${r}: the design has no variable "${r}"${guess ? ` (did you mean "${guess}"?)` : ''}. Add it to the .json's variables, or its rule set to "uses"`);
26
+ } });
27
+ return { v, read };
28
+ }
4
29
 
5
30
  // A design's result as parts: named ({ cap, pillar }) or one unnamed shape ("body").
6
31
  export function named(result, meta) {
7
32
  const isShape = (r) => Array.isArray(r) || jscad.geometries.geom3.isA(r) || jscad.geometries.geom2.isA(r);
8
33
  const entries = isShape(result) ? [['body', result]] : Object.entries(result || {});
9
34
  const empty = (g) => g == null || (Array.isArray(g) && !g.length);
35
+ if (!entries.some(([, g]) => !empty(g))) throw new CadError('design.empty', 'main() returned no shape: return a JSCAD solid, or named parts ({ cap, pillar })');
10
36
  for (const k of Object.keys(meta)) if (!meta[k].optional && !entries.some(([n, g]) => n === k && !empty(g))) throw new Error(`parts in the .json lists "${k}", but main() returns no such part`);
11
37
  return entries.filter(([name, g]) => !(empty(g) && meta[name]?.optional)).map(([name, g]) => {
12
38
  const m = meta[name] || {};