@rulecad/cad 0.8.0 → 0.9.0
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 +24 -10
- package/CHANGELOG.md +404 -0
- package/EXAMPLES.md +40 -38
- package/README.md +193 -67
- package/TUTORIAL.md +2 -2
- package/bin/cad.mjs +2250 -512
- package/lib/animate.mjs +173 -49
- package/lib/assembly.mjs +1847 -434
- package/lib/beams.mjs +256 -52
- package/lib/belts.mjs +66 -15
- package/lib/board-work.mjs +12 -0
- package/lib/bought.mjs +309 -53
- package/lib/buildpage.mjs +179 -29
- package/lib/carried.mjs +201 -0
- package/lib/clone.mjs +194 -42
- package/lib/design.mjs +649 -121
- package/lib/drive.mjs +187 -63
- package/lib/edit.mjs +899 -191
- package/lib/errors.mjs +16 -3
- package/lib/explain.mjs +62 -13
- package/lib/fasten.mjs +2702 -507
- package/lib/fittings.mjs +715 -121
- package/lib/fixings.mjs +21 -9
- package/lib/framebuild.mjs +790 -175
- package/lib/framecheck.mjs +1901 -368
- package/lib/framegen.mjs +100 -22
- package/lib/frameheat.mjs +225 -42
- package/lib/frameprint.mjs +513 -108
- package/lib/frames.mjs +81 -17
- package/lib/framesize.mjs +792 -120
- package/lib/frametip.mjs +235 -0
- package/lib/gait.mjs +135 -23
- package/lib/grip.mjs +62 -13
- package/lib/guides.mjs +1403 -230
- package/lib/host.mjs +123 -21
- package/lib/inplace.mjs +171 -36
- package/lib/jigs.mjs +360 -78
- package/lib/joins.mjs +697 -118
- package/lib/jsonedit.mjs +88 -26
- package/lib/kept.mjs +84 -0
- package/lib/kit.mjs +438 -68
- package/lib/layout.mjs +2 -1
- package/lib/links.mjs +149 -42
- package/lib/list.mjs +326 -64
- package/lib/live-guard.mjs +68 -0
- package/lib/live-shape.mjs +96 -24
- package/lib/live.mjs +189 -59
- package/lib/loads.mjs +579 -130
- package/lib/machine.mjs +372 -74
- package/lib/magnets.mjs +162 -44
- package/lib/measured.mjs +417 -94
- package/lib/mesh.mjs +526 -119
- package/lib/meshcmd.mjs +215 -60
- package/lib/motors.mjs +1021 -213
- package/lib/motorsvg.mjs +114 -32
- package/lib/names.mjs +3 -1
- package/lib/optimise.mjs +978 -283
- package/lib/order.mjs +519 -112
- package/lib/panels.mjs +482 -94
- package/lib/parts.mjs +78 -23
- package/lib/pins.mjs +163 -44
- package/lib/plates.mjs +223 -35
- package/lib/player.mjs +37 -9
- package/lib/power.mjs +64 -13
- package/lib/preview.mjs +83 -16
- package/lib/profilemeasure.mjs +572 -129
- package/lib/rules.mjs +15 -5
- package/lib/sandbox-hooks.mjs +77 -19
- package/lib/sandbox-run.mjs +117 -18
- package/lib/sandbox.mjs +509 -60
- package/lib/schema.mjs +42 -11
- package/lib/seats.mjs +227 -49
- package/lib/services.mjs +261 -52
- package/lib/sheet.mjs +851 -178
- package/lib/slotnuts.mjs +213 -34
- package/lib/targets/gist.mjs +4 -1
- package/lib/targets.mjs +22 -4
- package/lib/task.mjs +376 -79
- package/lib/versions.mjs +111 -28
- package/lib/wires.mjs +228 -45
- package/lib/workspace.mjs +197 -12
- package/package.json +19 -19
- package/schemas/assembly.schema.json +2 -2
package/lib/live-shape.mjs
CHANGED
|
@@ -5,37 +5,70 @@
|
|
|
5
5
|
// thread posts each round, and the page's stop button sets a shared flag it reads between rounds.
|
|
6
6
|
import http from 'node:http';
|
|
7
7
|
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
8
|
+
import { liveGuard } from './live-guard.mjs';
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
11
|
* 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
|
+
* @param {{ port?: number, host?: string, title: string, allowHosts?: string[], job: { region: { lo: number[], hi: number[] }, root: number[], tip: number[], mirror?: number, travel?: number, moves?: string } }} o
|
|
13
|
+
* allowHosts: names the page may be opened by beside this computer's own names and addresses, such as a Tailscale
|
|
14
|
+
* name (live-guard.mjs)
|
|
12
15
|
* @returns {Promise<{ url: string, round: (r: object) => void, stopped: () => boolean, close: (summary?: string, o?: { hold?: number }) => Promise<void> }>}
|
|
13
16
|
*/
|
|
14
|
-
export function liveShape({ port = 8090, host = '127.0.0.1', title, job }) {
|
|
17
|
+
export function liveShape({ port = 8090, host = '127.0.0.1', title, job, allowHosts = [] }) {
|
|
15
18
|
const flag = new Int32Array(new SharedArrayBuffer(4));
|
|
16
|
-
const setup = {
|
|
17
|
-
|
|
19
|
+
const setup = {
|
|
20
|
+
room: job.region,
|
|
21
|
+
root: job.root,
|
|
22
|
+
tip: job.tip,
|
|
23
|
+
mirror: job.mirror ?? null,
|
|
24
|
+
travel: job.travel ?? 0,
|
|
25
|
+
moves: job.moves ?? 'y',
|
|
26
|
+
};
|
|
27
|
+
const worker = new Worker(new URL(import.meta.url), { workerData: { port, host, title, flag, setup, allowHosts } });
|
|
18
28
|
return new Promise((resolve, reject) => {
|
|
19
29
|
worker.once('error', reject);
|
|
20
30
|
worker.once('message', (m) => {
|
|
21
|
-
if (m.error) {
|
|
31
|
+
if (m.error) {
|
|
32
|
+
worker.terminate();
|
|
33
|
+
reject(new Error(`the live view can't listen on ${host}:${port}: ${m.error}`));
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
22
36
|
worker.off('error', reject).on('error', (e) => console.error(`the live view stopped: ${e.message}`));
|
|
23
37
|
resolve({
|
|
24
38
|
url: `http://${host === '0.0.0.0' ? 'localhost' : host}:${m.listening}/`,
|
|
25
39
|
// A round: the paths thinned to every other point (plenty to see by), numbers to three figures
|
|
26
40
|
round: (r) => {
|
|
27
|
-
const thin = (p) =>
|
|
28
|
-
|
|
29
|
-
|
|
41
|
+
const thin = (p) =>
|
|
42
|
+
p?.filter((_, i, a) => i % 2 === 0 || i === a.length - 1).map(([x, y]) => [+x.toFixed(2), +y.toFixed(2)]);
|
|
43
|
+
worker.postMessage({
|
|
44
|
+
phase: r.phase,
|
|
45
|
+
round: r.round,
|
|
46
|
+
evaluations: r.evaluations,
|
|
47
|
+
limit: r.limit,
|
|
48
|
+
want: r.want,
|
|
49
|
+
tried: r.tried.map(thin),
|
|
50
|
+
best: r.best && {
|
|
51
|
+
...r.best,
|
|
52
|
+
path: r.best.path.map(([x, y]) => [+x.toFixed(2), +y.toFixed(2)]),
|
|
53
|
+
at: r.best.at?.map((t) => +t.toFixed(3)),
|
|
54
|
+
drawn: thin(r.best.drawn),
|
|
55
|
+
},
|
|
56
|
+
});
|
|
30
57
|
},
|
|
31
58
|
stopped: () => Atomics.load(flag, 0) === 1,
|
|
32
|
-
close: (summary, { hold = 0 } = {}) =>
|
|
59
|
+
close: (summary, { hold = 0 } = {}) =>
|
|
60
|
+
new Promise((done) => {
|
|
61
|
+
worker.once('exit', () => done());
|
|
62
|
+
worker.postMessage({ done: summary ?? 'finished', hold });
|
|
63
|
+
}),
|
|
33
64
|
});
|
|
34
65
|
});
|
|
35
66
|
});
|
|
36
67
|
}
|
|
37
68
|
|
|
38
|
-
const page = (
|
|
69
|
+
const page = (
|
|
70
|
+
title,
|
|
71
|
+
) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
39
72
|
<title>${title}</title>
|
|
40
73
|
<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
74
|
#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}
|
|
@@ -100,31 +133,70 @@ stop.onclick = async () => { stop.disabled = true; await fetch('stop', { method:
|
|
|
100
133
|
</script>`;
|
|
101
134
|
|
|
102
135
|
if (!isMainThread && workerData?.flag && workerData?.setup) {
|
|
103
|
-
const { port, host, title, flag, setup } = workerData,
|
|
104
|
-
|
|
136
|
+
const { port, host, title, flag, setup, allowHosts } = workerData,
|
|
137
|
+
allowed = liveGuard({ host, allowHosts }),
|
|
138
|
+
clients = new Set(),
|
|
139
|
+
frames = [],
|
|
140
|
+
history = [],
|
|
141
|
+
t0 = Date.now();
|
|
142
|
+
let latest = null,
|
|
143
|
+
sent = null,
|
|
144
|
+
done = null;
|
|
105
145
|
const send = (res, m) => res.write(`data: ${JSON.stringify(m)}\n\n`);
|
|
106
146
|
const server = http.createServer((req, res) => {
|
|
147
|
+
// Only this computer's own names, and only the view's own page may stop the run (live-guard.mjs)
|
|
148
|
+
if (!allowed(req, res)) return;
|
|
107
149
|
if (req.url === '/events') {
|
|
108
150
|
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
|
|
109
151
|
send(res, { setup, t0, history, ...(latest ? { frame: latest } : {}), ...(done ? { done } : {}) });
|
|
110
|
-
clients.add(res);
|
|
111
|
-
|
|
112
|
-
} else if (req.url
|
|
113
|
-
|
|
114
|
-
|
|
152
|
+
clients.add(res);
|
|
153
|
+
req.on('close', () => clients.delete(res));
|
|
154
|
+
} else if (req.url.startsWith('/round/') && frames[Number(req.url.slice(7))]) {
|
|
155
|
+
res.writeHead(200, { 'content-type': 'application/json' });
|
|
156
|
+
res.end(JSON.stringify(frames[Number(req.url.slice(7))]));
|
|
157
|
+
} else if (req.url === '/stop' && req.method === 'POST') {
|
|
158
|
+
Atomics.store(flag, 0, 1);
|
|
159
|
+
res.end('stopping');
|
|
160
|
+
} else if (req.url === '/') {
|
|
161
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
|
|
162
|
+
res.end(page(title));
|
|
163
|
+
} else {
|
|
164
|
+
res.writeHead(404);
|
|
165
|
+
res.end();
|
|
166
|
+
}
|
|
115
167
|
});
|
|
116
168
|
// At most four updates a second, whatever the search's pace
|
|
117
|
-
const tick = setInterval(() => {
|
|
169
|
+
const tick = setInterval(() => {
|
|
170
|
+
if (latest && latest !== sent) {
|
|
171
|
+
sent = latest;
|
|
172
|
+
const m = { history, frame: latest };
|
|
173
|
+
for (const c of clients) send(c, m);
|
|
174
|
+
}
|
|
175
|
+
}, 250);
|
|
118
176
|
parentPort.on('message', (m) => {
|
|
119
177
|
if (m.done) {
|
|
120
|
-
done = m.done;
|
|
121
|
-
|
|
122
|
-
const
|
|
123
|
-
|
|
178
|
+
done = m.done;
|
|
179
|
+
clearInterval(tick);
|
|
180
|
+
for (const c of clients) {
|
|
181
|
+
send(c, { history, ...(latest ? { frame: latest } : {}), done });
|
|
182
|
+
c.end();
|
|
183
|
+
}
|
|
184
|
+
const shut = () => {
|
|
185
|
+
server.close();
|
|
186
|
+
server.closeAllConnections();
|
|
187
|
+
parentPort.close();
|
|
188
|
+
};
|
|
189
|
+
if (m.hold) setTimeout(shut, m.hold);
|
|
190
|
+
else shut();
|
|
124
191
|
return;
|
|
125
192
|
}
|
|
126
|
-
m.elapsed = (Date.now() - t0) / 1000;
|
|
127
|
-
|
|
193
|
+
m.elapsed = (Date.now() - t0) / 1000;
|
|
194
|
+
latest = m;
|
|
195
|
+
frames.push(m);
|
|
196
|
+
history.push({
|
|
197
|
+
strain: m.best?.strain != null ? m.best.strain / m.limit : null,
|
|
198
|
+
energy: m.best?.energy != null ? m.best.energy / m.want : null,
|
|
199
|
+
});
|
|
128
200
|
});
|
|
129
201
|
server.once('error', (e) => parentPort.postMessage({ error: e.code || e.message }));
|
|
130
202
|
server.listen(port, host, () => parentPort.postMessage({ listening: server.address().port }));
|
package/lib/live.mjs
CHANGED
|
@@ -9,20 +9,27 @@ import path from 'node:path';
|
|
|
9
9
|
import { createRequire } from 'node:module';
|
|
10
10
|
import { surface } from '@rulecad/topopt';
|
|
11
11
|
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
12
|
+
import { liveGuard } from './live-guard.mjs';
|
|
12
13
|
|
|
13
14
|
/**
|
|
14
15
|
* Starts the server; resolves once it listens.
|
|
15
|
-
* @param {{ port?: number, host?: string, title: string }} o host: 127.0.0.1 unless asked
|
|
16
|
-
* forwards to it; plain 0.0.0.0 would open it to the local network)
|
|
16
|
+
* @param {{ port?: number, host?: string, title: string, allowHosts?: string[] }} o host: 127.0.0.1 unless asked
|
|
17
|
+
* (Tailscale's userspace mode forwards to it; plain 0.0.0.0 would open it to the local network); allowHosts: names
|
|
18
|
+
* the page may be opened by beside this computer's own names and addresses, such as a Tailscale name
|
|
19
|
+
* (live-guard.mjs)
|
|
17
20
|
* @returns {Promise<{ url: string, step: (s: object) => void, stopped: () => boolean, close: (summary?: string) => Promise<void> }>}
|
|
18
21
|
*/
|
|
19
|
-
export function liveView({ port = 8090, host = '127.0.0.1', title }) {
|
|
22
|
+
export function liveView({ port = 8090, host = '127.0.0.1', title, allowHosts = [] }) {
|
|
20
23
|
const flag = new Int32Array(new SharedArrayBuffer(4));
|
|
21
|
-
const worker = new Worker(new URL(import.meta.url), { workerData: { port, host, title, flag } });
|
|
24
|
+
const worker = new Worker(new URL(import.meta.url), { workerData: { port, host, title, flag, allowHosts } });
|
|
22
25
|
return new Promise((resolve, reject) => {
|
|
23
26
|
worker.once('error', reject);
|
|
24
27
|
worker.once('message', (m) => {
|
|
25
|
-
if (m.error) {
|
|
28
|
+
if (m.error) {
|
|
29
|
+
worker.terminate();
|
|
30
|
+
reject(new Error(`the live view can't listen on ${host}:${port}: ${m.error}`));
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
26
33
|
worker.off('error', reject).on('error', (e) => console.error(`the live view stopped: ${e.message}`));
|
|
27
34
|
resolve({
|
|
28
35
|
url: `http://${host === '0.0.0.0' ? 'localhost' : host}:${m.listening}/`,
|
|
@@ -31,12 +38,30 @@ export function liveView({ port = 8090, host = '127.0.0.1', title }) {
|
|
|
31
38
|
const { nx, ny, nz, h } = s.grid;
|
|
32
39
|
// A 3D grid's densities too, a byte a cell, for its surface (drawn when the page asks for it)
|
|
33
40
|
const cells = nz > 1 ? Uint8Array.from(s.density, (d) => Math.round(d * 255)) : null;
|
|
34
|
-
worker.postMessage(
|
|
35
|
-
|
|
41
|
+
worker.postMessage(
|
|
42
|
+
{
|
|
43
|
+
grid: { nx, ny, nz, h },
|
|
44
|
+
step: s.step,
|
|
45
|
+
steps: s.steps,
|
|
46
|
+
compliance: s.compliance,
|
|
47
|
+
change: s.change,
|
|
48
|
+
beta: s.beta,
|
|
49
|
+
volume: s.volume,
|
|
50
|
+
stress: s.stress,
|
|
51
|
+
travel: s.travel,
|
|
52
|
+
views: list,
|
|
53
|
+
cells,
|
|
54
|
+
},
|
|
55
|
+
[...list.map((v) => v.image.buffer), ...(cells ? [cells.buffer] : [])],
|
|
56
|
+
);
|
|
36
57
|
},
|
|
37
58
|
stopped: () => Atomics.load(flag, 0) === 1,
|
|
38
59
|
// hold: keep showing the end for this long (ms), for whoever opens the page late
|
|
39
|
-
close: (summary, { hold = 0 } = {}) =>
|
|
60
|
+
close: (summary, { hold = 0 } = {}) =>
|
|
61
|
+
new Promise((done) => {
|
|
62
|
+
worker.once('exit', () => done());
|
|
63
|
+
worker.postMessage({ done: summary ?? 'finished', hold });
|
|
64
|
+
}),
|
|
40
65
|
});
|
|
41
66
|
});
|
|
42
67
|
});
|
|
@@ -46,17 +71,23 @@ export function liveView({ port = 8090, host = '127.0.0.1', title }) {
|
|
|
46
71
|
// along its line of sight
|
|
47
72
|
function views(d, { nx, ny, nz = 1 }) {
|
|
48
73
|
const view = (name, w, h) => ({ name, w, h, image: new Uint8Array(w * h) });
|
|
49
|
-
const z = view(nz > 1 ? 'along z' : '', nx, ny),
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
74
|
+
const z = view(nz > 1 ? 'along z' : '', nx, ny),
|
|
75
|
+
y = view('along y', nx, nz),
|
|
76
|
+
x = view('along x', ny, nz);
|
|
77
|
+
for (let k = 0; k < nz; k++)
|
|
78
|
+
for (let j = 0; j < ny; j++)
|
|
79
|
+
for (let i = 0; i < nx; i++) {
|
|
80
|
+
const v = Math.round(d[(k * ny + j) * nx + i] * 255);
|
|
81
|
+
if (v > z.image[j * nx + i]) z.image[j * nx + i] = v;
|
|
82
|
+
if (v > y.image[k * nx + i]) y.image[k * nx + i] = v;
|
|
83
|
+
if (v > x.image[k * ny + j]) x.image[k * ny + j] = v;
|
|
84
|
+
}
|
|
56
85
|
return nz > 1 ? [y, x, z] : [z];
|
|
57
86
|
}
|
|
58
87
|
|
|
59
|
-
const page = (
|
|
88
|
+
const page = (
|
|
89
|
+
title,
|
|
90
|
+
) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
60
91
|
<title>${title}</title>
|
|
61
92
|
<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}
|
|
62
93
|
#chart{height:160px;touch-action:none}#scrub{display:flex;gap:8px;align-items:center;position:sticky;bottom:0;z-index:2;background:#111;padding:10px 0;border-top:1px solid #222}#scrub input{flex:1;height:32px}#at-step{color:#aaa;font-size:13px;min-width:5.5em}#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>
|
|
@@ -196,14 +227,34 @@ if (window.wanted3d) window.model3d(...window.wanted3d);
|
|
|
196
227
|
* @returns {{ step: (s: object) => void, steps: () => number, page: (title: string, done: string) => string }}
|
|
197
228
|
*/
|
|
198
229
|
export function recorder() {
|
|
199
|
-
const frames = [],
|
|
230
|
+
const frames = [],
|
|
231
|
+
history = { compliance: [], change: [] },
|
|
232
|
+
t0 = Date.now(),
|
|
233
|
+
times = [];
|
|
200
234
|
return {
|
|
201
235
|
step(s) {
|
|
202
|
-
const now = Date.now();
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
236
|
+
const now = Date.now();
|
|
237
|
+
times.push(now);
|
|
238
|
+
const last = times.slice(-11),
|
|
239
|
+
perStep = last.length > 1 ? (last.at(-1) - last[0]) / (last.length - 1) / 1000 : null,
|
|
240
|
+
{ nx, ny, nz, h } = s.grid;
|
|
241
|
+
frames.push({
|
|
242
|
+
index: frames.length,
|
|
243
|
+
grid: { nx, ny, nz, h },
|
|
244
|
+
step: s.step,
|
|
245
|
+
steps: s.steps,
|
|
246
|
+
compliance: s.compliance,
|
|
247
|
+
change: s.change,
|
|
248
|
+
beta: s.beta,
|
|
249
|
+
volume: s.volume,
|
|
250
|
+
stress: s.stress,
|
|
251
|
+
travel: s.travel,
|
|
252
|
+
elapsed: (now - t0) / 1000,
|
|
253
|
+
perStep,
|
|
254
|
+
views: views(s.density, s.grid).map((v) => ({ ...v, image: Buffer.from(v.image).toString('base64') })),
|
|
255
|
+
});
|
|
256
|
+
history.compliance.push(s.compliance);
|
|
257
|
+
history.change.push(s.change);
|
|
207
258
|
},
|
|
208
259
|
steps: () => frames.length,
|
|
209
260
|
page: (title, done) => replay(title, { history, frames, done }),
|
|
@@ -217,16 +268,31 @@ export function recorder() {
|
|
|
217
268
|
*/
|
|
218
269
|
export function endOnly(title, r, done) {
|
|
219
270
|
const { nx, ny, nz, h } = r.grid;
|
|
220
|
-
const frame = {
|
|
221
|
-
|
|
222
|
-
|
|
271
|
+
const frame = {
|
|
272
|
+
index: Math.max(0, (r.history?.length || 1) - 1),
|
|
273
|
+
grid: { nx, ny, nz, h },
|
|
274
|
+
step: r.steps,
|
|
275
|
+
steps: r.steps,
|
|
276
|
+
compliance: r.compliance,
|
|
277
|
+
change: 0,
|
|
278
|
+
beta: '',
|
|
279
|
+
elapsed: r.seconds ?? null,
|
|
280
|
+
perStep: null,
|
|
281
|
+
views: views(r.density, r.grid).map((v) => ({ ...v, image: Buffer.from(v.image).toString('base64') })),
|
|
282
|
+
};
|
|
283
|
+
return replay(title, {
|
|
284
|
+
history: { compliance: r.history?.length ? r.history : [r.compliance], change: [] },
|
|
285
|
+
frames: [frame],
|
|
286
|
+
done,
|
|
287
|
+
});
|
|
223
288
|
}
|
|
224
289
|
|
|
225
290
|
// The live view's page with its server's two answers read from the run instead: the stream of steps (one message: the
|
|
226
291
|
// whole history, the last step and how it ended) and any step asked for (the nearest one kept at or before it). Long
|
|
227
292
|
// runs keep every few steps, so the page stays under about 8 MB.
|
|
228
293
|
function replay(title, { history, frames, done }) {
|
|
229
|
-
const size = frames.reduce((t, f) => t + f.views.reduce((u, v) => u + v.image.length, 0), 0),
|
|
294
|
+
const size = frames.reduce((t, f) => t + f.views.reduce((u, v) => u + v.image.length, 0), 0),
|
|
295
|
+
every = Math.max(1, Math.ceil(size / 8e6));
|
|
230
296
|
const kept = frames.filter((f, k) => k % every === 0 || k === frames.length - 1);
|
|
231
297
|
const run = JSON.stringify({ history, frames: kept, done }).replace(/</g, '\\u003c');
|
|
232
298
|
const shim = `<script>
|
|
@@ -242,61 +308,125 @@ window.fetch = async (u) => { const k = Number(String(u).replace('frame/', ''));
|
|
|
242
308
|
const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // three's build files, for the 3D view
|
|
243
309
|
|
|
244
310
|
if (!isMainThread && workerData?.flag) {
|
|
245
|
-
const { port, host, title, flag
|
|
311
|
+
const { port, host, title, flag, allowHosts } = workerData,
|
|
312
|
+
allowed = liveGuard({ host, allowHosts }),
|
|
313
|
+
clients = new Set(),
|
|
314
|
+
history = { compliance: [], change: [] },
|
|
315
|
+
frames = [],
|
|
316
|
+
densities = [],
|
|
317
|
+
meshes = new Map(),
|
|
318
|
+
times = [],
|
|
319
|
+
t0 = Date.now();
|
|
246
320
|
// What a reader might want beside the numbers of each step: what ran it, where and when
|
|
247
|
-
const cpus = os.cpus(),
|
|
248
|
-
|
|
249
|
-
|
|
321
|
+
const cpus = os.cpus(),
|
|
322
|
+
about = [
|
|
323
|
+
['Started', new Date(t0).toLocaleString('en-GB')],
|
|
324
|
+
[
|
|
325
|
+
'Machine',
|
|
326
|
+
`${cpus[0]?.model.trim() ?? os.arch()}, ${cpus.length} cores, ${Math.round(os.totalmem() / 2 ** 30)} GB`,
|
|
327
|
+
],
|
|
328
|
+
[
|
|
329
|
+
'Software',
|
|
330
|
+
`@rulecad/cad ${JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version}, Node ${process.versions.node}, ${os.type()}`,
|
|
331
|
+
],
|
|
332
|
+
];
|
|
333
|
+
let latest = null,
|
|
334
|
+
sent = null,
|
|
335
|
+
done = null;
|
|
250
336
|
const send = (res, m) => res.write(`data: ${JSON.stringify(m)}\n\n`);
|
|
251
|
-
const frame = (f) => ({
|
|
337
|
+
const frame = (f) => ({
|
|
338
|
+
...f,
|
|
339
|
+
views: f.views.map((v) => ({ ...v, image: Buffer.from(v.image).toString('base64') })),
|
|
340
|
+
});
|
|
252
341
|
const server = http.createServer((req, res) => {
|
|
342
|
+
// Only this computer's own names, and only the view's own page may stop the run (live-guard.mjs)
|
|
343
|
+
if (!allowed(req, res)) return;
|
|
253
344
|
if (req.url === '/events') {
|
|
254
345
|
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
|
|
255
346
|
send(res, { about, history, ...(latest ? { frame: latest } : {}), ...(done ? { done } : {}) });
|
|
256
|
-
clients.add(res);
|
|
257
|
-
|
|
347
|
+
clients.add(res);
|
|
348
|
+
req.on('close', () => clients.delete(res));
|
|
349
|
+
// Any earlier step, for the scrubber: every one is kept (about a byte a pixel of its views)
|
|
258
350
|
} else if (req.url.startsWith('/mesh/') && densities[Number(req.url.slice(6))]) {
|
|
259
351
|
// A step's surface: vertex and face counts, then the vertices (float32 x, y, z) and the faces (uint32 corners).
|
|
260
352
|
// The last few are kept, as the page asks for the same step again while it turns.
|
|
261
353
|
const n = Number(req.url.slice(6));
|
|
262
354
|
if (!meshes.has(n)) {
|
|
263
|
-
const g = frames[n].grid,
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
355
|
+
const g = frames[n].grid,
|
|
356
|
+
{ vertices, faces } = surface(
|
|
357
|
+
g,
|
|
358
|
+
Float64Array.from(densities[n], (d) => d / 255),
|
|
359
|
+
[0, 0, 0],
|
|
360
|
+
);
|
|
361
|
+
const buf = Buffer.alloc(8 + vertices.length * 12 + faces.length * 12),
|
|
362
|
+
out = new DataView(buf.buffer, buf.byteOffset);
|
|
363
|
+
out.setUint32(0, vertices.length, true);
|
|
364
|
+
out.setUint32(4, faces.length, true);
|
|
365
|
+
vertices.forEach((v, i) => {
|
|
366
|
+
for (let a = 0; a < 3; a++) out.setFloat32(8 + (i * 3 + a) * 4, v[a], true);
|
|
367
|
+
});
|
|
368
|
+
faces.forEach((f, i) => {
|
|
369
|
+
for (let a = 0; a < 3; a++) out.setUint32(8 + vertices.length * 12 + (i * 3 + a) * 4, f[a], true);
|
|
370
|
+
});
|
|
371
|
+
meshes.set(n, buf);
|
|
372
|
+
if (meshes.size > 4) meshes.delete(meshes.keys().next().value);
|
|
269
373
|
}
|
|
270
|
-
res.writeHead(200, { 'content-type': 'application/octet-stream' });
|
|
374
|
+
res.writeHead(200, { 'content-type': 'application/octet-stream' });
|
|
375
|
+
res.end(meshes.get(n));
|
|
271
376
|
} else if (req.url.startsWith('/three/') && fs.existsSync(path.join(THREE, path.basename(req.url)))) {
|
|
272
|
-
res.writeHead(200, { 'content-type': 'text/javascript' });
|
|
273
|
-
|
|
377
|
+
res.writeHead(200, { 'content-type': 'text/javascript' });
|
|
378
|
+
res.end(fs.readFileSync(path.join(THREE, path.basename(req.url))));
|
|
379
|
+
} else if (req.url.startsWith('/frame/') && frames[Number(req.url.slice(7))]) {
|
|
380
|
+
res.writeHead(200, { 'content-type': 'application/json' });
|
|
381
|
+
res.end(JSON.stringify(frames[Number(req.url.slice(7))]));
|
|
274
382
|
} else if (req.url === '/stop' && req.method === 'POST') {
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
383
|
+
Atomics.store(flag, 0, 1);
|
|
384
|
+
res.end('stopping');
|
|
385
|
+
} else if (req.url === '/') {
|
|
386
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
|
|
387
|
+
res.end(page(title));
|
|
388
|
+
} else {
|
|
389
|
+
res.writeHead(404);
|
|
390
|
+
res.end();
|
|
280
391
|
}
|
|
281
|
-
else if (req.url === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(page(title)); }
|
|
282
|
-
else { res.writeHead(404); res.end(); }
|
|
283
392
|
});
|
|
284
393
|
// At most four frames a second, whatever the optimiser's pace
|
|
285
|
-
const tick = setInterval(() => {
|
|
394
|
+
const tick = setInterval(() => {
|
|
395
|
+
if (latest && latest !== sent) {
|
|
396
|
+
sent = latest;
|
|
397
|
+
const m = { history, frame: latest };
|
|
398
|
+
for (const c of clients) send(c, m);
|
|
399
|
+
}
|
|
400
|
+
}, 250);
|
|
286
401
|
parentPort.on('message', (m) => {
|
|
287
402
|
if (m.done) {
|
|
288
|
-
done = m.done;
|
|
289
|
-
|
|
290
|
-
const
|
|
291
|
-
|
|
403
|
+
done = m.done;
|
|
404
|
+
clearInterval(tick);
|
|
405
|
+
for (const c of clients) {
|
|
406
|
+
send(c, { history, ...(latest ? { frame: latest } : {}), done });
|
|
407
|
+
c.end();
|
|
408
|
+
}
|
|
409
|
+
const shut = () => {
|
|
410
|
+
server.close();
|
|
411
|
+
server.closeAllConnections();
|
|
412
|
+
parentPort.close();
|
|
413
|
+
};
|
|
414
|
+
if (m.hold) setTimeout(shut, m.hold);
|
|
415
|
+
else shut();
|
|
292
416
|
return;
|
|
293
417
|
}
|
|
294
418
|
// Timing: the mean of the last ten steps, and what's left at that pace (at most: it may settle sooner)
|
|
295
|
-
const now = Date.now();
|
|
296
|
-
|
|
297
|
-
const
|
|
298
|
-
|
|
299
|
-
|
|
419
|
+
const now = Date.now();
|
|
420
|
+
times.push(now);
|
|
421
|
+
const last = times.slice(-11),
|
|
422
|
+
perStep = last.length > 1 ? (last.at(-1) - last[0]) / (last.length - 1) / 1000 : null;
|
|
423
|
+
const { cells, ...rest } = m;
|
|
424
|
+
m = rest;
|
|
425
|
+
densities.push(cells);
|
|
426
|
+
latest = frame({ ...m, elapsed: (now - t0) / 1000, perStep, left: perStep && (m.steps - m.step) * perStep });
|
|
427
|
+
frames.push(latest);
|
|
428
|
+
history.compliance.push(m.compliance);
|
|
429
|
+
history.change.push(m.change);
|
|
300
430
|
});
|
|
301
431
|
server.once('error', (e) => parentPort.postMessage({ error: e.code || e.message }));
|
|
302
432
|
server.listen(port, host, () => parentPort.postMessage({ listening: server.address().port }));
|