@rulecad/cad 0.7.7 → 0.7.8
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/lib/live.mjs +83 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -373,7 +373,7 @@ A 3D result keeps only the pieces that touch a support, a load or a kept region.
|
|
|
373
373
|
can close into a piece of their own, which would print as a stray bit. `cad optimise` says how many it dropped.
|
|
374
374
|
|
|
375
375
|
`cad optimise <project>/<problem> --watch [port]` runs it afresh and serves a live view at `http://127.0.0.1:8090/`:
|
|
376
|
-
the densities as they change (a 3D part from three sides), a chart of its compliance and how much it still changes, with a scrubber to look back at any earlier step, its run time and time left, the machine it runs on, and a button that stops the run. It shows the end for ten minutes after the run finishes.
|
|
376
|
+
the densities as they change (a 3D part as a surface you can turn, and 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.
|
|
377
377
|
It listens on this computer only. To watch from elsewhere, reach it through a private network such as Tailscale.
|
|
378
378
|
|
|
379
379
|
A design uses it through a variable of type `problem`, which picks a problem by name:
|
package/lib/live.mjs
CHANGED
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
import fs from 'node:fs';
|
|
6
6
|
import http from 'node:http';
|
|
7
7
|
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { createRequire } from 'node:module';
|
|
10
|
+
import { surface } from '@rulecad/topopt';
|
|
8
11
|
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
9
12
|
|
|
10
13
|
/**
|
|
@@ -26,7 +29,10 @@ export function liveView({ port = 8090, host = '127.0.0.1', title }) {
|
|
|
26
29
|
step: (s) => {
|
|
27
30
|
const list = views(s.density, s.grid);
|
|
28
31
|
const { nx, ny, nz, h } = s.grid;
|
|
29
|
-
|
|
32
|
+
// A 3D grid's densities too, a byte a cell, for its surface (drawn when the page asks for it)
|
|
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 },
|
|
35
|
+
[...list.map((v) => v.image.buffer), ...(cells ? [cells.buffer] : [])]);
|
|
30
36
|
},
|
|
31
37
|
stopped: () => Atomics.load(flag, 0) === 1,
|
|
32
38
|
// hold: keep showing the end for this long (ms), for whoever opens the page late
|
|
@@ -52,9 +58,9 @@ function views(d, { nx, ny, nz = 1 }) {
|
|
|
52
58
|
|
|
53
59
|
const page = (title) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
54
60
|
<title>${title}</title>
|
|
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}
|
|
61
|
+
<style>body{font:15px system-ui;background:#111;color:#eee;margin:16px;max-width:900px}canvas{background:#000;border-radius:6px}.chart{width:100%}#hint{color:#888;font-size:12px;text-align:center;margin:-4px 0 8px}#model{height:50vh;margin-bottom:8px;border-radius:6px;overflow:hidden;background:#000;cursor:grab;touch-action:none}#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
62
|
#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>
|
|
63
|
+
<h2>${title}</h2><div id="state">waiting for the first step…</div><div id="model" hidden></div><div id="hint" hidden>drag to turn it · double-tap to stop or start it turning</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>
|
|
58
64
|
<p><button id="stop">Stop the run</button> <span id="note"></span></p>
|
|
59
65
|
<script>
|
|
60
66
|
const views = document.getElementById('views'), facts = document.getElementById('facts'), state = document.getElementById('state'), stop = document.getElementById('stop');
|
|
@@ -75,6 +81,7 @@ function table() {
|
|
|
75
81
|
facts.innerHTML = [...(finished ? [['Result', finished]] : []), ...rows, ...about].map(([k, v]) => '<tr><td>' + esc(k) + '</td><td>' + esc(v) + '</td></tr>').join('');
|
|
76
82
|
}
|
|
77
83
|
function draw(f) {
|
|
84
|
+
document.getElementById('model').hidden = document.getElementById('hint').hidden = f.views.length < 3;
|
|
78
85
|
if (views.children.length !== f.views.length) views.innerHTML = f.views.map((v) => '<figure><canvas></canvas><figcaption>' + v.name + '</figcaption></figure>').join('');
|
|
79
86
|
f.views.forEach((v, n) => {
|
|
80
87
|
const c = views.children[n].firstChild; if (c.width !== v.w) { c.width = v.w; c.height = v.h; }
|
|
@@ -100,7 +107,8 @@ function plot() {
|
|
|
100
107
|
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
108
|
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
109
|
}
|
|
103
|
-
function show(f) { draw(f); plot(); table(); }
|
|
110
|
+
function show(f) { draw(f); plot(); table(); window.model3d?.(shown, f.grid); }
|
|
111
|
+
let lastModel = 0; // while following, a new surface at most every two seconds
|
|
104
112
|
// Scrubbing: any earlier step, fetched when asked for; the newest only while following
|
|
105
113
|
let asked = 0;
|
|
106
114
|
async function lookAt(k) {
|
|
@@ -118,14 +126,67 @@ events.onmessage = (e) => { const m = JSON.parse(e.data); if (m.about) about = m
|
|
|
118
126
|
if (m.done) { finished = m.done; stop.disabled = true; events.close(); }
|
|
119
127
|
at.max = Math.max(0, history.compliance.length - 1);
|
|
120
128
|
if (m.frame) newest = m.frame;
|
|
121
|
-
if (follow) { shown = Number(at.max); at.value = shown; if (newest) draw(newest); }
|
|
129
|
+
if (follow) { shown = Number(at.max); at.value = shown; if (newest) draw(newest); if (Date.now() - lastModel > 2000 || finished) { lastModel = Date.now(); window.model3d?.(shown, newest.grid); } }
|
|
122
130
|
if (finished) state.textContent = finished;
|
|
123
131
|
plot(); table(); };
|
|
124
132
|
stop.onclick = async () => { stop.disabled = true; await fetch('stop', { method: 'POST' }); document.getElementById('note').textContent = 'stopping after this step'; };
|
|
133
|
+
</script>
|
|
134
|
+
<script type="importmap">{ "imports": { "three": "/three/three.module.js" } }</script>
|
|
135
|
+
<script type="module">
|
|
136
|
+
// The 3D view: the step's surface, turning slowly; drag to turn it, double-tap to stop or start it turning
|
|
137
|
+
import * as THREE from 'three';
|
|
138
|
+
const box = document.getElementById('model');
|
|
139
|
+
let renderer, scene, camera, mesh, yaw = 0.6, tilt = 0.4, spin = true, size = 1, centre = null, busy = false, wanted = null, current = null;
|
|
140
|
+
function setup() {
|
|
141
|
+
renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true }); box.appendChild(renderer.domElement);
|
|
142
|
+
scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(35, 1, 0.1, 1e6); camera.up.set(0, 0, 1);
|
|
143
|
+
scene.add(new THREE.AmbientLight(0xffffff, 0.6));
|
|
144
|
+
const sun = new THREE.DirectionalLight(0xffffff, 2); sun.position.set(-1, -2, 3); scene.add(sun);
|
|
145
|
+
const fill = new THREE.DirectionalLight(0xffffff, 0.8); fill.position.set(2, 1, -1); scene.add(fill);
|
|
146
|
+
const c = renderer.domElement; let last = null;
|
|
147
|
+
c.onpointerdown = (e) => { last = [e.clientX, e.clientY]; spin = false; c.setPointerCapture(e.pointerId); };
|
|
148
|
+
c.onpointermove = (e) => { if (!last) return; yaw -= (e.clientX - last[0]) * 0.01; tilt = Math.max(-1.4, Math.min(1.4, tilt + (e.clientY - last[1]) * 0.01)); last = [e.clientX, e.clientY]; };
|
|
149
|
+
c.onpointerup = () => { last = null; };
|
|
150
|
+
c.ondblclick = () => { spin = !spin; };
|
|
151
|
+
const tick = () => {
|
|
152
|
+
const w = box.clientWidth, h = box.clientHeight;
|
|
153
|
+
if (w && (c.width !== Math.round(w * devicePixelRatio) || c.height !== Math.round(h * devicePixelRatio))) { renderer.setPixelRatio(devicePixelRatio); renderer.setSize(w, h); camera.aspect = w / h; camera.updateProjectionMatrix(); }
|
|
154
|
+
if (spin) yaw += 0.004;
|
|
155
|
+
const d = size / Math.sin(camera.fov * Math.PI / 360) * 0.8; // the part seldom fills its grid's corners camera.position.set(d * Math.cos(tilt) * Math.cos(yaw), d * Math.cos(tilt) * Math.sin(yaw), d * Math.sin(tilt)); camera.lookAt(0, 0, 0);
|
|
156
|
+
renderer.render(scene, camera); requestAnimationFrame(tick);
|
|
157
|
+
};
|
|
158
|
+
tick();
|
|
159
|
+
}
|
|
160
|
+
async function load(n, grid) {
|
|
161
|
+
if (n === current) return;
|
|
162
|
+
if (busy) { wanted = [n, grid]; return; }
|
|
163
|
+
busy = true;
|
|
164
|
+
try {
|
|
165
|
+
const res = await fetch('mesh/' + n);
|
|
166
|
+
if (!res.ok) return;
|
|
167
|
+
const buf = await res.arrayBuffer(), [nv, nf] = new Uint32Array(buf, 0, 2);
|
|
168
|
+
if (!renderer) setup();
|
|
169
|
+
const g = new THREE.BufferGeometry();
|
|
170
|
+
g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(buf, 8, nv * 3), 3)); g.setIndex(new THREE.BufferAttribute(new Uint32Array(buf, 8 + nv * 12, nf * 3), 1));
|
|
171
|
+
g.computeVertexNormals();
|
|
172
|
+
// Framed on the whole grid, so the part stays put as it changes
|
|
173
|
+
if (!centre) { const e = [grid.nx, grid.ny, grid.nz].map((n) => n * grid.h); centre = new THREE.Vector3(e[0] / 2, e[1] / 2, e[2] / 2); size = Math.hypot(...e) / 2; }
|
|
174
|
+
g.translate(-centre.x, -centre.y, -centre.z);
|
|
175
|
+
if (mesh) { scene.remove(mesh); mesh.geometry.dispose(); }
|
|
176
|
+
mesh = new THREE.Mesh(g, new THREE.MeshStandardMaterial({ color: 0xd9d9d9, roughness: 0.55, metalness: 0.05, side: THREE.DoubleSide }));
|
|
177
|
+
scene.add(mesh); current = n;
|
|
178
|
+
} finally {
|
|
179
|
+
busy = false;
|
|
180
|
+
if (wanted != null) { const [w, wg] = wanted; wanted = null; load(w, wg); }
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
window.model3d = (n, grid) => { if (!box.hidden && grid) load(n, grid); };
|
|
125
184
|
</script>`;
|
|
126
185
|
|
|
186
|
+
const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // three's build files, for the 3D view
|
|
187
|
+
|
|
127
188
|
if (!isMainThread && workerData?.flag) {
|
|
128
|
-
const { port, host, title, flag } = workerData, clients = new Set(), history = { compliance: [], change: [] }, frames = [], times = [], t0 = Date.now();
|
|
189
|
+
const { port, host, title, flag } = workerData, clients = new Set(), history = { compliance: [], change: [] }, frames = [], densities = [], meshes = new Map(), times = [], t0 = Date.now();
|
|
129
190
|
// What a reader might want beside the numbers of each step: what ran it, where and when
|
|
130
191
|
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
192
|
['Software', `@rulecad/cad ${JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version}, Node ${process.versions.node}, ${os.type()}`]];
|
|
@@ -138,6 +199,21 @@ if (!isMainThread && workerData?.flag) {
|
|
|
138
199
|
send(res, { about, history, ...(latest ? { frame: latest } : {}), ...(done ? { done } : {}) });
|
|
139
200
|
clients.add(res); req.on('close', () => clients.delete(res));
|
|
140
201
|
// Any earlier step, for the scrubber: every one is kept (about a byte a pixel of its views)
|
|
202
|
+
} else if (req.url.startsWith('/mesh/') && densities[Number(req.url.slice(6))]) {
|
|
203
|
+
// A step's surface: vertex and face counts, then the vertices (float32 x, y, z) and the faces (uint32 corners).
|
|
204
|
+
// The last few are kept, as the page asks for the same step again while it turns.
|
|
205
|
+
const n = Number(req.url.slice(6));
|
|
206
|
+
if (!meshes.has(n)) {
|
|
207
|
+
const g = frames[n].grid, { vertices, faces } = surface(g, Float64Array.from(densities[n], (d) => d / 255), [0, 0, 0]);
|
|
208
|
+
const buf = Buffer.alloc(8 + vertices.length * 12 + faces.length * 12), out = new DataView(buf.buffer, buf.byteOffset);
|
|
209
|
+
out.setUint32(0, vertices.length, true); out.setUint32(4, faces.length, true);
|
|
210
|
+
vertices.forEach((v, i) => { for (let a = 0; a < 3; a++) out.setFloat32(8 + (i * 3 + a) * 4, v[a], true); });
|
|
211
|
+
faces.forEach((f, i) => { for (let a = 0; a < 3; a++) out.setUint32(8 + vertices.length * 12 + (i * 3 + a) * 4, f[a], true); });
|
|
212
|
+
meshes.set(n, buf); if (meshes.size > 4) meshes.delete(meshes.keys().next().value);
|
|
213
|
+
}
|
|
214
|
+
res.writeHead(200, { 'content-type': 'application/octet-stream' }); res.end(meshes.get(n));
|
|
215
|
+
} else if (req.url.startsWith('/three/') && fs.existsSync(path.join(THREE, path.basename(req.url)))) {
|
|
216
|
+
res.writeHead(200, { 'content-type': 'text/javascript' }); res.end(fs.readFileSync(path.join(THREE, path.basename(req.url))));
|
|
141
217
|
} 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))]));
|
|
142
218
|
} else if (req.url === '/stop' && req.method === 'POST') { Atomics.store(flag, 0, 1); res.end('stopping'); }
|
|
143
219
|
else if (req.url === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(page(title)); }
|
|
@@ -156,6 +232,7 @@ if (!isMainThread && workerData?.flag) {
|
|
|
156
232
|
// Timing: the mean of the last ten steps, and what's left at that pace (at most: it may settle sooner)
|
|
157
233
|
const now = Date.now(); times.push(now);
|
|
158
234
|
const last = times.slice(-11), perStep = last.length > 1 ? (last.at(-1) - last[0]) / (last.length - 1) / 1000 : null;
|
|
235
|
+
const { cells, ...rest } = m; m = rest; densities.push(cells);
|
|
159
236
|
latest = frame({ ...m, elapsed: (now - t0) / 1000, perStep, left: perStep && (m.steps - m.step) * perStep }); frames.push(latest);
|
|
160
237
|
history.compliance.push(m.compliance); history.change.push(m.change);
|
|
161
238
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/cad",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.8",
|
|
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": {
|