@rulecad/cad 0.7.3 → 0.7.4
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 +4 -0
- package/bin/cad.mjs +13 -2
- package/lib/live.mjs +108 -0
- package/lib/optimise.mjs +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -369,6 +369,10 @@ 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
|
+
`cad optimise <project>/<problem> --watch [port]` runs it afresh and serves a live view at `http://127.0.0.1:8090/`:
|
|
373
|
+
the densities as they change (a 3D part from three sides), a chart of its compliance, and a button that stops the run.
|
|
374
|
+
It listens on this computer only. To watch from elsewhere, reach it through a private network such as Tailscale.
|
|
375
|
+
|
|
372
376
|
A design uses it through a variable of type `problem`, which picks a problem by name:
|
|
373
377
|
|
|
374
378
|
```json
|
package/bin/cad.mjs
CHANGED
|
@@ -20,6 +20,7 @@ import { optimised, readProblem, analysePart, picture, problemFile } from '../li
|
|
|
20
20
|
import { evaluate } from '../lib/rules.mjs';
|
|
21
21
|
import { setVariables, addToAssembly, parseValue } from '../lib/edit.mjs';
|
|
22
22
|
import { threemf, slotOf } from '../lib/threemf.mjs';
|
|
23
|
+
import { liveView } from '../lib/live.mjs';
|
|
23
24
|
import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW } from '../lib/links.mjs';
|
|
24
25
|
|
|
25
26
|
// What the print file asks of the AMS: which filament each kind of part prints in
|
|
@@ -48,6 +49,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
48
49
|
cad preview <project>/<object> four views as a PNG in .preview/ (prints the path)
|
|
49
50
|
cad optimise <project>/<problem> the stiffest layout for a problem in the project's problems/ (name:variant for a
|
|
50
51
|
variant): a picture in .preview/, the result kept for designs [--fresh] [--json]
|
|
52
|
+
[--watch [port]: a live view of it at http://127.0.0.1:8090/, with a stop button]
|
|
51
53
|
cad export <project>/<object> a 3MF for Bambu Studio in exports/ [--open: open it in Bambu Studio]
|
|
52
54
|
cad show <project>/<object> the model on display through your show target, with its rules [--ttl 10m]
|
|
53
55
|
cad link <project>/<object> links to open the model in a browser, and to download its STL or 3MF
|
|
@@ -121,8 +123,17 @@ async function optimiseProblem(ref) {
|
|
|
121
123
|
if (bad.length) { report(bad); process.exitCode = 1; return; }
|
|
122
124
|
}
|
|
123
125
|
const live = !opt('json') && process.stderr.isTTY;
|
|
124
|
-
|
|
125
|
-
|
|
126
|
+
// --watch [port]: the live view, served while it runs (a watched run is always run afresh, so there is something to watch)
|
|
127
|
+
const watch = opt('watch'), view = watch ? await liveView({ port: watch === true ? 8090 : Number(watch), title: `cad optimise ${ref}` }) : null;
|
|
128
|
+
if (view) say(`watching at ${view.url}`);
|
|
129
|
+
let r;
|
|
130
|
+
try {
|
|
131
|
+
r = await optimised(project, name, { fresh: !!opt('fresh') || !!view, onStep: (s) => {
|
|
132
|
+
if (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}`);
|
|
133
|
+
if (view) { view.step(s); if (view.stopped()) throw new Error(`stopped from the live view at step ${s.step}`); }
|
|
134
|
+
} });
|
|
135
|
+
} catch (e) { await view?.close(e.message); throw e; } finally { if (live) process.stderr.write('\r\x1b[K'); }
|
|
136
|
+
await view?.close(`finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`);
|
|
126
137
|
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
138
|
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
139
|
`${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)})` : ''}`];
|
package/lib/live.mjs
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// The live view of an optimisation: `cad optimise <ref> --watch [port]` serves a page that draws the densities as
|
|
2
|
+
// they change, charts the progress and can stop the run. The optimiser runs on the main thread and blocks it, so the
|
|
3
|
+
// server runs in a worker: the main thread posts each step to it, and the page's stop button sets a shared flag the
|
|
4
|
+
// main thread reads between steps.
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Starts the server; resolves once it listens.
|
|
10
|
+
* @param {{ port?: number, host?: string, title: string }} o host: 127.0.0.1 unless asked (Tailscale's userspace mode
|
|
11
|
+
* forwards to it; plain 0.0.0.0 would open it to the local network)
|
|
12
|
+
* @returns {Promise<{ url: string, step: (s: object) => void, stopped: () => boolean, close: (summary?: string) => Promise<void> }>}
|
|
13
|
+
*/
|
|
14
|
+
export function liveView({ port = 8090, host = '127.0.0.1', title }) {
|
|
15
|
+
const flag = new Int32Array(new SharedArrayBuffer(4));
|
|
16
|
+
const worker = new Worker(new URL(import.meta.url), { workerData: { port, host, title, flag } });
|
|
17
|
+
return new Promise((resolve, reject) => {
|
|
18
|
+
worker.once('error', reject);
|
|
19
|
+
worker.once('message', (m) => {
|
|
20
|
+
if (m.error) { worker.terminate(); reject(new Error(`the live view can't listen on ${host}:${port}: ${m.error}`)); return; }
|
|
21
|
+
worker.off('error', reject).on('error', (e) => console.error(`the live view stopped: ${e.message}`));
|
|
22
|
+
resolve({
|
|
23
|
+
url: `http://${host === '0.0.0.0' ? 'localhost' : host}:${m.listening}/`,
|
|
24
|
+
step: (s) => {
|
|
25
|
+
const list = views(s.density, s.grid);
|
|
26
|
+
worker.postMessage({ step: s.step, steps: s.steps, compliance: s.compliance, change: s.change, beta: s.beta, volume: s.volume, stress: s.stress, views: list }, list.map((v) => v.image.buffer));
|
|
27
|
+
},
|
|
28
|
+
stopped: () => Atomics.load(flag, 0) === 1,
|
|
29
|
+
close: (summary) => new Promise((done) => { worker.once('exit', () => done()); worker.postMessage({ done: summary ?? 'finished' }); }),
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Densities as bytes, one per pixel: a 2D layout as it is, a 3D grid as three views, each pixel the densest cell
|
|
36
|
+
// along its line of sight
|
|
37
|
+
function views(d, { nx, ny, nz = 1 }) {
|
|
38
|
+
const view = (name, w, h) => ({ name, w, h, image: new Uint8Array(w * h) });
|
|
39
|
+
const z = view(nz > 1 ? 'along z' : '', nx, ny), y = view('along y', nx, nz), x = view('along x', ny, nz);
|
|
40
|
+
for (let k = 0; k < nz; k++) for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
|
|
41
|
+
const v = Math.round(d[(k * ny + j) * nx + i] * 255);
|
|
42
|
+
if (v > z.image[j * nx + i]) z.image[j * nx + i] = v;
|
|
43
|
+
if (v > y.image[k * nx + i]) y.image[k * nx + i] = v;
|
|
44
|
+
if (v > x.image[k * ny + j]) x.image[k * ny + j] = v;
|
|
45
|
+
}
|
|
46
|
+
return nz > 1 ? [y, x, z] : [z];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const page = (title) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
50
|
+
<title>${title}</title>
|
|
51
|
+
<style>body{font:15px system-ui;background:#111;color:#eee;margin:16px;max-width:900px}canvas{background:#000;border-radius:6px}#chart{width:100%}#views{display:flex;gap:8px;align-items:flex-end}figure{flex:1;min-width:0;margin:0;text-align:center}figure canvas{width:100%;height:40vh;object-fit:contain;background:none}figcaption{color:#aaa;font-size:13px;text-align:center}
|
|
52
|
+
#chart{height:140px;image-rendering:auto}button{font:inherit;padding:8px 16px;border-radius:6px;border:0;background:#d33;color:#fff}button:disabled{background:#555}#state{margin:10px 0}</style>
|
|
53
|
+
<h2>${title}</h2><div id="state">waiting for the first step…</div><div id="views"></div><canvas id="chart" width="900" height="140"></canvas>
|
|
54
|
+
<p><button id="stop">Stop the run</button> <span id="note"></span></p>
|
|
55
|
+
<script>
|
|
56
|
+
const views = document.getElementById('views'), chart = document.getElementById('chart'), state = document.getElementById('state'), stop = document.getElementById('stop');
|
|
57
|
+
let history = [];
|
|
58
|
+
const fig = (n) => Number(n.toPrecision(3));
|
|
59
|
+
function draw(f) {
|
|
60
|
+
if (views.children.length !== f.views.length) views.innerHTML = f.views.map((v) => '<figure><canvas></canvas><figcaption>' + v.name + '</figcaption></figure>').join('');
|
|
61
|
+
f.views.forEach((v, n) => {
|
|
62
|
+
const c = views.children[n].firstChild; if (c.width !== v.w) { c.width = v.w; c.height = v.h; }
|
|
63
|
+
const ctx = c.getContext('2d'), img = ctx.createImageData(v.w, v.h), d = atob(v.image);
|
|
64
|
+
for (let j = 0; j < v.h; j++) for (let i = 0; i < v.w; i++) { const g = 255 - d.charCodeAt(j * v.w + i), o = ((v.h - 1 - j) * v.w + i) * 4; img.data[o] = img.data[o + 1] = img.data[o + 2] = g; img.data[o + 3] = 255; }
|
|
65
|
+
ctx.putImageData(img, 0, 0);
|
|
66
|
+
});
|
|
67
|
+
state.textContent = 'step ' + f.step + ' of ' + f.steps + ' · compliance ' + fig(f.compliance) + ' N·mm' + (f.volume != null ? ' · ' + fig(f.volume * 100) + '% of the space' : '') + (f.stress != null ? ' · peak stress ' + fig(f.stress) + ' MPa' : '') + ' · sharpness ' + f.beta;
|
|
68
|
+
}
|
|
69
|
+
function plot() {
|
|
70
|
+
const c = chart.getContext('2d'), w = chart.width, h = chart.height; c.clearRect(0, 0, w, h);
|
|
71
|
+
if (history.length < 2) return;
|
|
72
|
+
const lo = Math.min(...history), hi = Math.max(...history) || 1; c.strokeStyle = '#6cf'; c.lineWidth = 2; c.beginPath();
|
|
73
|
+
history.forEach((v, k) => { const x = k / (history.length - 1) * w, y = h - 8 - (v - lo) / (hi - lo || 1) * (h - 16); k ? c.lineTo(x, y) : c.moveTo(x, y); });
|
|
74
|
+
c.stroke(); c.fillStyle = '#aaa'; c.fillText('compliance: ' + fig(hi) + ' to ' + fig(history.at(-1)) + ' N·mm', 8, 14);
|
|
75
|
+
}
|
|
76
|
+
const events = new EventSource('events');
|
|
77
|
+
events.onmessage = (e) => { const m = JSON.parse(e.data); if (m.history) history = m.history; if (m.frame) draw(m.frame); plot();
|
|
78
|
+
if (m.done) { state.textContent += ' · ' + m.done; stop.disabled = true; events.close(); } };
|
|
79
|
+
stop.onclick = async () => { stop.disabled = true; await fetch('stop', { method: 'POST' }); document.getElementById('note').textContent = 'stopping after this step'; };
|
|
80
|
+
</script>`;
|
|
81
|
+
|
|
82
|
+
if (!isMainThread && workerData?.flag) {
|
|
83
|
+
const { port, host, title, flag } = workerData, clients = new Set(), history = [];
|
|
84
|
+
let latest = null, sent = null, done = null;
|
|
85
|
+
const send = (res, m) => res.write(`data: ${JSON.stringify(m)}\n\n`);
|
|
86
|
+
const frame = (f) => ({ ...f, views: f.views.map((v) => ({ ...v, image: Buffer.from(v.image).toString('base64') })) });
|
|
87
|
+
const server = http.createServer((req, res) => {
|
|
88
|
+
if (req.url === '/events') {
|
|
89
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
|
|
90
|
+
send(res, { history, ...(latest ? { frame: frame(latest) } : {}), ...(done ? { done } : {}) });
|
|
91
|
+
clients.add(res); req.on('close', () => clients.delete(res));
|
|
92
|
+
} else if (req.url === '/stop' && req.method === 'POST') { Atomics.store(flag, 0, 1); res.end('stopping'); }
|
|
93
|
+
else if (req.url === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(page(title)); }
|
|
94
|
+
else { res.writeHead(404); res.end(); }
|
|
95
|
+
});
|
|
96
|
+
// At most four frames a second, whatever the optimiser's pace
|
|
97
|
+
const tick = setInterval(() => { if (latest && latest !== sent) { sent = latest; const m = { history, frame: frame(latest) }; for (const c of clients) send(c, m); } }, 250);
|
|
98
|
+
parentPort.on('message', (m) => {
|
|
99
|
+
if (m.done) {
|
|
100
|
+
done = m.done; clearInterval(tick);
|
|
101
|
+
for (const c of clients) { send(c, { history, ...(latest ? { frame: frame(latest) } : {}), done }); c.end(); }
|
|
102
|
+
server.close(); server.closeAllConnections(); parentPort.close(); return;
|
|
103
|
+
}
|
|
104
|
+
latest = m; history.push(m.compliance);
|
|
105
|
+
});
|
|
106
|
+
server.once('error', (e) => parentPort.postMessage({ error: e.code || e.message }));
|
|
107
|
+
server.listen(port, host, () => parentPort.postMessage({ listening: server.address().port }));
|
|
108
|
+
}
|
package/lib/optimise.mjs
CHANGED
|
@@ -93,7 +93,7 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
|
|
|
93
93
|
const hash = digest([VERSION, r.problem, r.outline, topopt, source('@rulecad/fea')]), file = paths.cache('optimise', `${hash}.json`);
|
|
94
94
|
if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file)) return { ...JSON.parse(host.readText(file)), cached: true };
|
|
95
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 });
|
|
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: onStep && ((st) => onStep({ ...st, grid: spec.grid })) });
|
|
97
97
|
if (!host.exists(densities)) host.writeText(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
|
|
98
98
|
// Regions as data: a part's triangles are named, not copied
|
|
99
99
|
const named = (list) => list.map(({ triangles, ...x }) => x);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/cad",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.4",
|
|
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": {
|