@rulecad/cad 0.7.4 → 0.7.5
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 +1 -1
- package/bin/cad.mjs +2 -1
- package/lib/live.mjs +78 -22
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -370,7 +370,7 @@ gives, and draws the layout in `.preview/`. The result is kept, keyed by everyth
|
|
|
370
370
|
worked out again when something it depends on changes.
|
|
371
371
|
|
|
372
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.
|
|
373
|
+
the densities as they change (a 3D part from three sides), a chart of its compliance and how much it still changes, with a scrubber to look back at any earlier step, its run time and time left, the machine it runs on, and a button that stops the run. It shows the end for ten minutes after the run finishes.
|
|
374
374
|
It listens on this computer only. To watch from elsewhere, reach it through a private network such as Tailscale.
|
|
375
375
|
|
|
376
376
|
A design uses it through a variable of type `problem`, which picks a problem by name:
|
package/bin/cad.mjs
CHANGED
|
@@ -133,7 +133,8 @@ async function optimiseProblem(ref) {
|
|
|
133
133
|
if (view) { view.step(s); if (view.stopped()) throw new Error(`stopped from the live view at step ${s.step}`); }
|
|
134
134
|
} });
|
|
135
135
|
} catch (e) { await view?.close(e.message); throw e; } finally { if (live) process.stderr.write('\r\x1b[K'); }
|
|
136
|
-
|
|
136
|
+
// The page keeps showing the end for ten minutes (the process waits for it), so a finished run isn't a dead link
|
|
137
|
+
if (view) { view.close(`finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, { hold: 10 * 60e3 }); say(`the live view shows the result for ten more minutes (Ctrl-C to stop it)`); }
|
|
137
138
|
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}`;
|
|
138
139
|
const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
|
|
139
140
|
`${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}`];
|
package/lib/live.mjs
CHANGED
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
// they change, charts the progress and can stop the run. The optimiser runs on the main thread and blocks it, so the
|
|
3
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
4
|
// main thread reads between steps.
|
|
5
|
+
import fs from 'node:fs';
|
|
5
6
|
import http from 'node:http';
|
|
7
|
+
import os from 'node:os';
|
|
6
8
|
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
7
9
|
|
|
8
10
|
/**
|
|
@@ -23,10 +25,12 @@ export function liveView({ port = 8090, host = '127.0.0.1', title }) {
|
|
|
23
25
|
url: `http://${host === '0.0.0.0' ? 'localhost' : host}:${m.listening}/`,
|
|
24
26
|
step: (s) => {
|
|
25
27
|
const list = views(s.density, s.grid);
|
|
26
|
-
|
|
28
|
+
const { nx, ny, nz, h } = s.grid;
|
|
29
|
+
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 }, list.map((v) => v.image.buffer));
|
|
27
30
|
},
|
|
28
31
|
stopped: () => Atomics.load(flag, 0) === 1,
|
|
29
|
-
|
|
32
|
+
// hold: keep showing the end for this long (ms), for whoever opens the page late
|
|
33
|
+
close: (summary, { hold = 0 } = {}) => new Promise((done) => { worker.once('exit', () => done()); worker.postMessage({ done: summary ?? 'finished', hold }); }),
|
|
30
34
|
});
|
|
31
35
|
});
|
|
32
36
|
});
|
|
@@ -48,14 +52,28 @@ function views(d, { nx, ny, nz = 1 }) {
|
|
|
48
52
|
|
|
49
53
|
const page = (title) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
50
54
|
<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}
|
|
52
|
-
#chart{height:
|
|
53
|
-
<h2>${title}</h2><div id="state">waiting for the first step…</div><div id="views"></div><canvas id="chart" width="900" height="
|
|
55
|
+
<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}
|
|
56
|
+
#chart{height:160px;touch-action:none}#scrub{display:flex;gap:8px;align-items:center}#scrub input{flex:1}#live{background:#357}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}#state{margin:10px 0}</style>
|
|
57
|
+
<h2>${title}</h2><div id="state">waiting for the first step…</div><div id="views"></div><canvas class="chart" id="chart" width="900" height="160"></canvas><div id="scrub"><input type="range" id="at" min="0" max="0" value="0"><button id="live" disabled>Live</button></div><table id="facts"></table>
|
|
54
58
|
<p><button id="stop">Stop the run</button> <span id="note"></span></p>
|
|
55
59
|
<script>
|
|
56
|
-
const views = document.getElementById('views'),
|
|
57
|
-
let history = [];
|
|
58
|
-
const
|
|
60
|
+
const views = document.getElementById('views'), facts = document.getElementById('facts'), state = document.getElementById('state'), stop = document.getElementById('stop');
|
|
61
|
+
let history = { compliance: [], change: [] }, about = [], last = null, finished = null, follow = true, shown = 0, newest = null;
|
|
62
|
+
const at = document.getElementById('at'), live = document.getElementById('live'), chart = document.getElementById('chart');
|
|
63
|
+
const fig = (n) => Number(n.toPrecision(3)), esc = (t) => String(t).replace(/[&<]/g, (c) => c === '&' ? '&' : '<');
|
|
64
|
+
const time = (s) => s == null ? '…' : s < 60 ? s.toFixed(s < 10 ? 1 : 0) + ' s' : Math.floor(s / 60) + ' min ' + Math.round(s % 60) + ' s';
|
|
65
|
+
function table() {
|
|
66
|
+
const f = last, rows = f ? [
|
|
67
|
+
['Step', f.step + ' of at most ' + f.steps + (follow ? '' : ' (looking back: ' + history.compliance.length + ' so far)')],
|
|
68
|
+
['Run time', time(f.elapsed)], ['Per step', time(f.perStep) + ' (the last ten)'],
|
|
69
|
+
...(finished || !follow ? [] : [['Time left', 'at most ' + time(f.left) + ' (it may settle sooner)']]),
|
|
70
|
+
['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' : '')],
|
|
71
|
+
['Change', fig(f.change) + ' (the most any cell moved this step)'], ['Sharpness', f.beta],
|
|
72
|
+
...(f.volume != null ? [['Material', fig(f.volume * 100) + '% of the space']] : []), ...(f.stress != null ? [['Peak stress', fig(f.stress) + ' MPa']] : []),
|
|
73
|
+
['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') + ')'],
|
|
74
|
+
] : [];
|
|
75
|
+
facts.innerHTML = [...(finished ? [['Result', finished]] : []), ...rows, ...about].map(([k, v]) => '<tr><td>' + esc(k) + '</td><td>' + esc(v) + '</td></tr>').join('');
|
|
76
|
+
}
|
|
59
77
|
function draw(f) {
|
|
60
78
|
if (views.children.length !== f.views.length) views.innerHTML = f.views.map((v) => '<figure><canvas></canvas><figcaption>' + v.name + '</figcaption></figure>').join('');
|
|
61
79
|
f.views.forEach((v, n) => {
|
|
@@ -64,44 +82,82 @@ function draw(f) {
|
|
|
64
82
|
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
83
|
ctx.putImageData(img, 0, 0);
|
|
66
84
|
});
|
|
67
|
-
|
|
85
|
+
last = f; state.textContent = finished ? finished : 'step ' + f.step + ' · ' + time(f.elapsed);
|
|
68
86
|
}
|
|
87
|
+
// Both against step: compliance on the left axis, change on the right on a log scale (it falls by orders of
|
|
88
|
+
// magnitude); the step shown marked
|
|
69
89
|
function plot() {
|
|
70
|
-
const c = chart.getContext('2d'), w = chart.width, h = chart.height; c.clearRect(0, 0, w, h);
|
|
71
|
-
if (
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
|
|
90
|
+
const c = chart.getContext('2d'), w = chart.width, h = chart.height, n = history.compliance.length; c.clearRect(0, 0, w, h);
|
|
91
|
+
if (n < 2) return;
|
|
92
|
+
const line = (data, log, colour) => {
|
|
93
|
+
const ys = data.map((v) => log ? Math.log10(Math.max(v, 1e-6)) : v), lo = Math.min(...ys), hi = Math.max(...ys);
|
|
94
|
+
c.strokeStyle = colour; c.lineWidth = 2; c.beginPath();
|
|
95
|
+
ys.forEach((v, k) => { const x = k / (n - 1) * w, y = h - 8 - (v - lo) / (hi - lo || 1) * (h - 28); k ? c.lineTo(x, y) : c.moveTo(x, y); });
|
|
96
|
+
c.stroke();
|
|
97
|
+
};
|
|
98
|
+
line(history.compliance, false, '#6cf'); line(history.change, true, '#fc6');
|
|
99
|
+
const x = shown / (n - 1) * w; c.strokeStyle = '#fff8'; c.lineWidth = 1; c.beginPath(); c.moveTo(x, 0); c.lineTo(x, h); c.stroke();
|
|
100
|
+
c.font = '12px system-ui'; c.fillStyle = '#6cf'; c.fillText('compliance, N·mm: ' + fig(history.compliance[0]) + ' to ' + fig(history.compliance.at(-1)), 8, 14);
|
|
101
|
+
c.fillStyle = '#fc6'; c.textAlign = 'right'; c.fillText('change (log scale): ' + fig(history.change[0]) + ' to ' + fig(history.change.at(-1)), w - 8, 14); c.textAlign = 'left';
|
|
102
|
+
}
|
|
103
|
+
function show(f) { draw(f); plot(); table(); }
|
|
104
|
+
// Scrubbing: any earlier step, fetched when asked for; the newest only while following
|
|
105
|
+
let asked = 0;
|
|
106
|
+
async function lookAt(k) {
|
|
107
|
+
const n = history.compliance.length; k = Math.max(0, Math.min(n - 1, k)); shown = k; at.value = k;
|
|
108
|
+
follow = k === n - 1; live.disabled = follow;
|
|
109
|
+
if (follow && newest) return show(newest);
|
|
110
|
+
const ask = ++asked, f = await (await fetch('frame/' + k)).json();
|
|
111
|
+
if (ask === asked) show(f);
|
|
75
112
|
}
|
|
113
|
+
at.oninput = () => lookAt(Number(at.value));
|
|
114
|
+
live.onclick = () => lookAt(history.compliance.length - 1);
|
|
115
|
+
chart.onpointerdown = chart.onpointermove = (e) => { if (e.type === 'pointermove' && !e.buttons) return; const r = chart.getBoundingClientRect(); lookAt(Math.round((e.clientX - r.left) / r.width * (history.compliance.length - 1))); };
|
|
76
116
|
const events = new EventSource('events');
|
|
77
|
-
events.onmessage = (e) => { const m = JSON.parse(e.data); if (m.
|
|
78
|
-
if (m.done) {
|
|
117
|
+
events.onmessage = (e) => { const m = JSON.parse(e.data); if (m.about) about = m.about; if (m.history) history = m.history;
|
|
118
|
+
if (m.done) { finished = m.done; stop.disabled = true; events.close(); }
|
|
119
|
+
at.max = Math.max(0, history.compliance.length - 1);
|
|
120
|
+
if (m.frame) newest = m.frame;
|
|
121
|
+
if (follow) { shown = Number(at.max); at.value = shown; if (newest) draw(newest); }
|
|
122
|
+
if (finished) state.textContent = finished;
|
|
123
|
+
plot(); table(); };
|
|
79
124
|
stop.onclick = async () => { stop.disabled = true; await fetch('stop', { method: 'POST' }); document.getElementById('note').textContent = 'stopping after this step'; };
|
|
80
125
|
</script>`;
|
|
81
126
|
|
|
82
127
|
if (!isMainThread && workerData?.flag) {
|
|
83
|
-
const { port, host, title, flag } = workerData, clients = new Set(), history = [];
|
|
128
|
+
const { port, host, title, flag } = workerData, clients = new Set(), history = { compliance: [], change: [] }, frames = [], times = [], t0 = Date.now();
|
|
129
|
+
// What a reader might want beside the numbers of each step: what ran it, where and when
|
|
130
|
+
const cpus = os.cpus(), about = [['Started', new Date(t0).toLocaleString('en-GB')], ['Machine', `${cpus[0]?.model.trim() ?? os.arch()}, ${cpus.length} cores, ${Math.round(os.totalmem() / 2 ** 30)} GB`],
|
|
131
|
+
['Software', `@rulecad/cad ${JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version}, Node ${process.versions.node}, ${os.type()}`]];
|
|
84
132
|
let latest = null, sent = null, done = null;
|
|
85
133
|
const send = (res, m) => res.write(`data: ${JSON.stringify(m)}\n\n`);
|
|
86
134
|
const frame = (f) => ({ ...f, views: f.views.map((v) => ({ ...v, image: Buffer.from(v.image).toString('base64') })) });
|
|
87
135
|
const server = http.createServer((req, res) => {
|
|
88
136
|
if (req.url === '/events') {
|
|
89
137
|
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
|
|
90
|
-
send(res, { history, ...(latest ? { frame:
|
|
138
|
+
send(res, { about, history, ...(latest ? { frame: latest } : {}), ...(done ? { done } : {}) });
|
|
91
139
|
clients.add(res); req.on('close', () => clients.delete(res));
|
|
140
|
+
// Any earlier step, for the scrubber: every one is kept (about a byte a pixel of its views)
|
|
141
|
+
} else if (req.url.startsWith('/frame/') && frames[Number(req.url.slice(7))]) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(frames[Number(req.url.slice(7))]));
|
|
92
142
|
} else if (req.url === '/stop' && req.method === 'POST') { Atomics.store(flag, 0, 1); res.end('stopping'); }
|
|
93
143
|
else if (req.url === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(page(title)); }
|
|
94
144
|
else { res.writeHead(404); res.end(); }
|
|
95
145
|
});
|
|
96
146
|
// 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:
|
|
147
|
+
const tick = setInterval(() => { if (latest && latest !== sent) { sent = latest; const m = { history, frame: latest }; for (const c of clients) send(c, m); } }, 250);
|
|
98
148
|
parentPort.on('message', (m) => {
|
|
99
149
|
if (m.done) {
|
|
100
150
|
done = m.done; clearInterval(tick);
|
|
101
|
-
for (const c of clients) { send(c, { history, ...(latest ? { frame:
|
|
102
|
-
server.close(); server.closeAllConnections(); parentPort.close();
|
|
151
|
+
for (const c of clients) { send(c, { history, ...(latest ? { frame: latest } : {}), done }); c.end(); }
|
|
152
|
+
const shut = () => { server.close(); server.closeAllConnections(); parentPort.close(); };
|
|
153
|
+
if (m.hold) setTimeout(shut, m.hold); else shut();
|
|
154
|
+
return;
|
|
103
155
|
}
|
|
104
|
-
|
|
156
|
+
// Timing: the mean of the last ten steps, and what's left at that pace (at most: it may settle sooner)
|
|
157
|
+
const now = Date.now(); times.push(now);
|
|
158
|
+
const last = times.slice(-11), perStep = last.length > 1 ? (last.at(-1) - last[0]) / (last.length - 1) / 1000 : null;
|
|
159
|
+
latest = frame({ ...m, elapsed: (now - t0) / 1000, perStep, left: perStep && (m.steps - m.step) * perStep }); frames.push(latest);
|
|
160
|
+
history.compliance.push(m.compliance); history.change.push(m.change);
|
|
105
161
|
});
|
|
106
162
|
server.once('error', (e) => parentPort.postMessage({ error: e.code || e.message }));
|
|
107
163
|
server.listen(port, host, () => parentPort.postMessage({ listening: server.address().port }));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/cad",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.5",
|
|
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": {
|