@rulecad/cad 0.3.2 → 0.3.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/AGENTS.md CHANGED
@@ -17,6 +17,15 @@ variable says which rule it comes from. Follow these steps; they're what makes a
17
17
  on `interface` (versions follow them). Give sensible `tweak` ranges to the ones they may want to change.
18
18
  5. `npx cad export` for printing; `npx cad link --md` for a link to share.
19
19
 
20
+ ## Fitting something from elsewhere
21
+ - When a part must fit something whose model exists (a maker's CAD, a model site), measure that model:
22
+ `npx cad measure <file> --rules <name> --source <url> --licence "…"`. Look at the drawing in `.preview/measure/`,
23
+ then rename the draft rules for what they are and say in each `rule` what the feature does.
24
+ - Model it from those rules, then `npx cad match <project>/<object> <file>`: report the worst places with their numbers,
25
+ and look at the sections picture. A deliberate clearance shows as an even offset; anything else is a finding.
26
+ - Don't copy the shape of a model whose licence is non-commercial, no-derivatives or share-alike into a design under
27
+ another licence: take measurements only, and say so.
28
+
20
29
  ## Changing a design
21
30
  1. `npx cad history <project>/<object>` first: read the print log. A failed print is the reason for most changes:
22
31
  fix the rule or variable it points at (a measured fit beats a community rule).
package/README.md CHANGED
@@ -36,6 +36,8 @@ npx cad check bathroom/soap-tray --set width=60 # change variables that have a
36
36
  npx cad variants keyboard/keycap # named sets of inputs: keyboard/keycap:legend-f
37
37
  npx cad compare keyboard/keycap dsa legend-f # two variants (or releases) side by side
38
38
  npx cad import-kle layout.json keyboard/mine # a layout from keyboard-layout-editor.com, into layouts/
39
+ npx cad measure cover.3mf --rules cover # a model from elsewhere, measured into draft rules
40
+ npx cad match legion-go/rail cover.3mf # how closely a design matches that model, both ways
39
41
  ```
40
42
 
41
43
  The keyboard examples below come from the project rulecad grew out of: a keycap, a switch plate, a case and their
@@ -69,6 +71,9 @@ fragment, which never reaches the web host, so the public page can open private
69
71
  which version it holds (`keyboard/keycap@0.1.0`, or `+changes` if it isn't a release). The page is to become `@rulecad/viewer`;
70
72
  `scripts/publish-view.sh "message"` publishes it (only that folder) to the public repo.
71
73
 
74
+ - **Rules:** a link carries the model's values and the rules they use (value, source, kind, date checked) for the
75
+ page's Rules panel; estimates are marked there. A rule set with `"private": true` stays out of links, and
76
+ `--no-rules` leaves the list out altogether. Anyone with a link can read what it carries.
72
77
  - **Short links** (`--short`, and the default for `--md`, once `"shorten": "gist"` is in `cad.config.json`'s
73
78
  `targets`): the link's data goes in a secret GitHub Gist (unlisted, but anyone with the link can open it) and the
74
79
  link carries only its ID: `…/#s=<id>`. The page fetches it from GitHub's API. The same model reuses its Gist
@@ -178,6 +183,31 @@ out. `--part cap` works on one part; `cad preview --explode` moves the parts apa
178
183
  - The print check treats parts that print together as one print: an underside resting on another part (a legend on its
179
184
  cap) isn't an overhang, and each part must be a closed solid on its own.
180
185
 
186
+ ## Models from elsewhere
187
+
188
+ To fit something someone else made (a maker's connector, a part from a model site), measure their model rather than
189
+ guessing, then check your design against it.
190
+
191
+ `cad measure <model.stl|model.3mf>` finds the stretches along the model's longest axis (or `--along y`) where its
192
+ cross-section stays the same, numbers the distinct sections (a section seen again gets the same letter), and describes
193
+ each one: its extent and its height bands, the heights over which it has the same pieces across, split again at steps.
194
+ It draws every distinct section in `.preview/measure/`. `--line 0.6,2.5` reports where a line along the axis is inside
195
+ the model (where notches start and stop); `--at 10,50` adds sections there. `--rules <name>` writes the numbers as a
196
+ draft rule set, every value `kind: derived` with the file, `--source` and `--licence` it came from: rename the
197
+ placeholder names (`stretch3_from`, `sectionB_w`) for what they are before a design uses them. Sections are compared by
198
+ shape, within 0.05 mm, so a curve faceted differently along its length is still one section.
199
+
200
+ `cad match <project>/<object> <model>` lays the model over the design (trying every quarter turn whose size fits, then
201
+ shifting it onto the design's surface; `--place "rz90 t1,2,3"` pins it) and samples both surfaces: how far the design is
202
+ from the model, and the model from the design, signed (outside: extra material; inside: missing material, or a
203
+ clearance you meant). It passes when everything is within `--tol` (the printer's sliding fit by default), warns when
204
+ only the worst 5% is past it, and fails otherwise, listing the worst places. The pictures show the model over the
205
+ design, and sections through the worst places with the model dashed. Deliberate differences (a clearance on sliding
206
+ faces) show up as an even offset: set `--tol` above them.
207
+
208
+ A model's licence limits what you make from it, not what you learn: measurements are facts, but a non-commercial or
209
+ share-alike model's shape shouldn't be copied into a design under another licence. `measure` warns about those.
210
+
181
211
  ## Assemblies
182
212
 
183
213
  `projects/<project>/assemblies/<name>.json` places objects together. Positions are expressions over rules and the
package/bin/cad.mjs CHANGED
@@ -11,6 +11,7 @@ import { locate, build, pick, lint, readObject, printer, pcbEngine, objectSets }
11
11
  import { git, tags, bump, bigger, newer, compare, snapshot, materialise, files, prints, printsFile, engineId } from '../lib/versions.mjs';
12
12
  import { check } from '@rulecad/printcheck';
13
13
  import { preview } from '../lib/preview.mjs';
14
+ import { measure, match } from '../lib/meshcmd.mjs';
14
15
  import { isAssembly, buildAssembly, checkAssembly, shapes } from '../lib/assembly.mjs';
15
16
  import { fromParts, fromShapes, encode, check as checkLink, expand } from '@rulecad/model-link';
16
17
  import { threemf, slotOf } from '../lib/threemf.mjs';
@@ -51,6 +52,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
51
52
  cad link <project>/<object> links to open the model in a browser, and to download its STL or 3MF
52
53
  [--md: one labelled Markdown link, for chat (the page downloads any parts): short unless --long]
53
54
  [--short: the model's data in a secret GitHub Gist, so links are ~80 characters]
55
+ [--no-rules: leave out the Rules panel's list of values and their sources]
54
56
 
55
57
  cad status [project] each object's version, and whether it has changes since its last release
56
58
  cad release <project>/<object> -m "what changed" [--bump major|minor|patch] [--dry-run] [--push]
@@ -61,6 +63,16 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
61
63
  cad printed <project>/<object> --result ok|failed [--note "…"] [--material PETG] [--version 0.1.0]
62
64
  cad release <project> --all -m "…" release every object that changed (each with this message), then the project
63
65
 
66
+ cad measure <model.stl|3mf> a model from elsewhere, measured: size, the stretches along its length with the same
67
+ cross-section, and each section's shape, with a drawing in .preview/measure/
68
+ [--along x|y|z] [--at 10,50: sections there too] [--line 0.6,2.5;4.6,2.5: where lines
69
+ along it are inside] [--rules <name> --source <url> --licence "…": draft rules]
70
+ cad match <project>/<object> <model.stl|3mf> how closely the design matches a model: both ways, signed, with the
71
+ worst places and sections through them [--tol 0.2 (default: the printer's fit)]
72
+ [--place "rz90 t1,2,3": how to lay the model over the design, else it is fitted]
73
+ [--at 10,50: sections there too] [--samples 20000]
74
+ --no-pictures measure, match: the report only, no drawings (no Chrome needed)
75
+
64
76
  cad variants <project>/<object> the object's variants: named sets of inputs, built as <project>/<object>:<variant>
65
77
  cad compare <project>/<object> <a> <b> two variants (or releases, 1.2.0) side by side in one preview
66
78
 
@@ -126,6 +138,11 @@ async function main() {
126
138
  return;
127
139
  }
128
140
  if (cmd === 'status') return status(ref);
141
+ if (cmd === 'measure') {
142
+ if (!ref) throw new Error('usage: cad measure <model.stl|model.3mf> [--along x] [--at 10,50] [--line 0.6,2.5] [--rules <name>]');
143
+ const list = (k) => (opt(k) && opt(k) !== true ? String(opt(k)).split(k === 'line' ? ';' : ',').filter(Boolean) : []);
144
+ return measure(ref, { along: opt('along'), at: list('at'), line: list('line'), rules: opt('rules'), source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), pictures: !opt('no-pictures') });
145
+ }
129
146
  if (!ref) throw new Error(`usage: cad ${cmd} <project>/<object>`);
130
147
  if (cmd === 'release') return ref.includes('/') ? releaseObject(locate(ref)) : opt('all') ? releaseAll(ref) : releaseProject(ref);
131
148
  if (cmd === 'variants') return variants(locate(ref));
@@ -142,6 +159,15 @@ async function main() {
142
159
 
143
160
  if (b.circuit && ['check', 'preview', 'export'].includes(cmd)) return board(cmd, d, b, { title, version, tag });
144
161
 
162
+ if (cmd === 'match') {
163
+ const file = args[2];
164
+ if (!file || file.startsWith('--')) throw new Error(`usage: cad match ${ref} <model.stl|model.3mf> [--tol 0.2] [--place "rz90 t1,2,3"]`);
165
+ const tol = opt('tol') ? Number(opt('tol')) : printer(b, d).fit ?? 0.2;
166
+ const ok = await match(b, d, file, { place: opt('place'), tol, samples: Number(opt('samples')) || 20000, at: opt('at') ? String(opt('at')).split(',') : [], title: `${title} ${version}`, tag, pictures: !opt('no-pictures') });
167
+ process.exitCode = ok ? 0 : 1;
168
+ return;
169
+ }
170
+
145
171
  if (cmd === 'rules') {
146
172
  for (const e of b.entries) console.log(`${e.name.padEnd(18)} ${`${fmt(e.value)} ${e.unit || ''}`.padEnd(14)} ${e.expr ? `= ${e.expr} ` : ''}${e.rule || ''}${e.source ? ` [${e.kind ? `${e.kind}: ` : ''}${e.source}]` : ''}${e.set ? ' (set)' : ''}`);
147
173
  return;
@@ -270,6 +296,7 @@ async function assembly(cmd, ref) {
270
296
  const model = {
271
297
  title, version: versions, src: `${s.project}/${s.name}`, // object versions are in version: the file name stays short orientation: a.note || (a.kind === 'plate' ? 'A print plate: print everything together.' : 'A fit check: references are faint.'),
272
298
  rules: [],
299
+ ...sheet([...new Map(s.objects.filter((o) => o.built?.entries).map((o) => [o.objName, o.built.entries])).entries()]),
273
300
  // Its boards' 2D views (copper, schematic), so one link holds the whole build: tabs over the 3D model
274
301
  ...(await (async () => {
275
302
  const boards = [...new Map(s.objects.filter((o) => o.built?.circuit).map((o) => [o.objName, o])).values()];
@@ -303,6 +330,23 @@ async function assembly(cmd, ref) {
303
330
  }
304
331
 
305
332
  // ---------- links ----------
333
+ // The rules sheet a link carries, for the page's Rules panel: a row for each of an object's own values, then each rule
334
+ // they use, as [group, name, value, unit, rule, expr, kind, source, checked] (group: the object, or the rule's set).
335
+ // A rule set marked "private" stays out, and --no-rules leaves the sheet out altogether.
336
+ function sheet(objects) {
337
+ if (opt('no-rules')) return {};
338
+ const rows = [], seen = new Set(), trim = (r) => { while (r.length && (r[r.length - 1] === '' || r[r.length - 1] == null)) r.pop(); return r; };
339
+ for (const [obj, entries] of objects) for (const e of entries) {
340
+ if (!e.name.includes('.')) rows.push(trim([obj, e.label || e.name, fmt(e.value), e.unit || '', e.rule || '', e.expr || '']));
341
+ }
342
+ for (const [, entries] of objects) for (const e of entries) {
343
+ if (!e.name.includes('.') || !e.used || e.private || seen.has(e.name)) continue;
344
+ seen.add(e.name);
345
+ const [set, name] = e.name.split('.');
346
+ rows.push(trim([set, name, fmt(e.value), e.unit || '', e.rule || '', e.expr || '', e.kind || '', e.source || '', e.checked || '']));
347
+ }
348
+ return rows.length ? { sheet: rows } : {};
349
+ }
306
350
  // The model as a link: full print precision (triangles), the rules card, and exactly which version it is.
307
351
  async function links(d, b, set) {
308
352
  const s = d.tag ? { kind: null } : await since(d), fil = filaments(d.project);
@@ -312,6 +356,7 @@ async function links(d, b, set) {
312
356
  title: `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`, version, src, ...(Object.keys(set).length ? { set: suffix(set).slice(1).replace(/-(?=\w+=)/g, ',') } : {}),
313
357
  material: b.object.material, orientation: b.object.orientation,
314
358
  rules: b.entries.filter((e) => e.show).map((e) => [e.label || e.name, fmt(e.value), e.unit || '']),
359
+ ...sheet([[b.object.name, b.entries]]),
315
360
  ...(b.circuit ? { views: await (await pcbEngine()).views(b.circuit) } : {}), // boards: the 2D board and schematic
316
361
  ...fromParts(b.parts.map((p) => ({ name: p.name, role: p.role, label: p.label, slot: slotOf(fil, p.filament), triangles: p.triangles.flatMap((t) => t.slice(1, -1).map((_, i) => [t[0], t[i + 1], t[i + 2]])) }))),
317
362
  };
package/lib/mesh.mjs ADDED
@@ -0,0 +1,427 @@
1
+ // Meshes from elsewhere (an STL or 3MF from the internet, a maker's CAD export): read them, measure them, and compare a
2
+ // design with them. Everything works on triangles, [[x, y, z] × 3], in millimetres. No dependencies but node's zlib.
3
+ // readMesh(file) -> triangles
4
+ // profiles(tris, axis) -> the stretches along an axis where the cross-section stays the same, each with its outline
5
+ // spans(tris, axis, at) -> where a line along an axis is inside the solid
6
+ // align(moving, fixed) -> the turn and shift that best lays moving over fixed
7
+ // deviation(from, to) -> how far points on one surface are from the other, signed (+ outside, - inside)
8
+ import fs from 'node:fs';
9
+ import zlib from 'node:zlib';
10
+
11
+ export const AXES = ['x', 'y', 'z'];
12
+ export const axisOf = (a) => { const i = AXES.indexOf(String(a).toLowerCase()); if (i < 0) throw new Error(`axis is x, y or z, not "${a}"`); return i; };
13
+ // The two other axes of a cross-section, in order: across, then up (z when it can be)
14
+ export const planeAxes = (axis) => (axis === 2 ? [0, 1] : axis === 1 ? [0, 2] : [1, 2]);
15
+ const r2 = (n) => Math.round(n * 100) / 100;
16
+
17
+ // ---- reading ----
18
+
19
+ export function readMesh(file) {
20
+ const buf = fs.readFileSync(file);
21
+ if (/\.3mf$/i.test(file)) return read3mf(buf);
22
+ if (/\.stl$/i.test(file)) return readStl(buf);
23
+ throw new Error(`${file}: an STL or 3MF, please (export STEP files from a CAD program as STL first)`);
24
+ }
25
+
26
+ export function readStl(buf) {
27
+ const n = buf.length >= 84 ? buf.readUInt32LE(80) : -1;
28
+ if (n >= 0 && 84 + n * 50 === buf.length) { // binary
29
+ const tris = [];
30
+ for (let i = 0; i < n; i++) {
31
+ const o = 84 + i * 50 + 12, v = (k) => [buf.readFloatLE(o + k * 12), buf.readFloatLE(o + k * 12 + 4), buf.readFloatLE(o + k * 12 + 8)];
32
+ tris.push([v(0), v(1), v(2)]);
33
+ }
34
+ return tris;
35
+ }
36
+ const pts = [...buf.toString('utf8').matchAll(/vertex\s+(\S+)\s+(\S+)\s+(\S+)/g)].map((m) => [+m[1], +m[2], +m[3]]);
37
+ if (!pts.length || pts.length % 3) throw new Error('not an STL: no triangles found');
38
+ const tris = [];
39
+ for (let i = 0; i < pts.length; i += 3) tris.push([pts[i], pts[i + 1], pts[i + 2]]);
40
+ return tris;
41
+ }
42
+
43
+ // A zip's files by name (stored or deflated), from its central directory
44
+ export function unzip(buf) {
45
+ let e = buf.length - 22;
46
+ while (e >= 0 && buf.readUInt32LE(e) !== 0x06054b50) e--;
47
+ if (e < 0) throw new Error('not a zip file');
48
+ let count = buf.readUInt16LE(e + 10), p = buf.readUInt32LE(e + 16);
49
+ if (p === 0xffffffff && e >= 20 && buf.readUInt32LE(e - 20) === 0x07064b50) { // Zip64: the real numbers are in its own record
50
+ const z = Number(buf.readBigUInt64LE(e - 12));
51
+ count = Number(buf.readBigUInt64LE(z + 32));
52
+ p = Number(buf.readBigUInt64LE(z + 48));
53
+ }
54
+ const files = {};
55
+ for (let i = 0; i < count; i++) {
56
+ if (buf.readUInt32LE(p) !== 0x02014b50) throw new Error('a damaged zip file');
57
+ const method = buf.readUInt16LE(p + 10), nameLen = buf.readUInt16LE(p + 28);
58
+ const extraLen = buf.readUInt16LE(p + 30), noteLen = buf.readUInt16LE(p + 32);
59
+ let local = buf.readUInt32LE(p + 42), csize = buf.readUInt32LE(p + 20);
60
+ const name = buf.toString('utf8', p + 46, p + 46 + nameLen);
61
+ // Zip64: sizes and offset in the extra field when the 32-bit ones are 0xffffffff
62
+ const ext = buf.subarray(p + 46 + nameLen, p + 46 + nameLen + extraLen);
63
+ for (let q = 0; q + 4 <= ext.length;) {
64
+ const id = ext.readUInt16LE(q), len = ext.readUInt16LE(q + 2);
65
+ if (id === 1) {
66
+ let r = q + 4;
67
+ if (buf.readUInt32LE(p + 24) === 0xffffffff) r += 8; // uncompressed size
68
+ if (buf.readUInt32LE(p + 20) === 0xffffffff) { csize = Number(ext.readBigUInt64LE(r)); r += 8; }
69
+ if (local === 0xffffffff) local = Number(ext.readBigUInt64LE(r));
70
+ }
71
+ q += 4 + len;
72
+ }
73
+ const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
74
+ const data = buf.subarray(start, start + csize);
75
+ files[name] = method === 8 ? zlib.inflateRawSync(data) : method === 0 ? data : null;
76
+ p += 46 + nameLen + extraLen + noteLen;
77
+ }
78
+ return files;
79
+ }
80
+
81
+ // A 3MF: every build item, with its transform, and the components it is made of (in this model file or another)
82
+ export function read3mf(buf) {
83
+ const files = unzip(buf);
84
+ const models = Object.fromEntries(Object.entries(files).filter(([n, d]) => d && /\.model$/i.test(n)).map(([n, d]) => ['/' + n.replace(/^\//, ''), d.toString('utf8')]));
85
+ const root = Object.keys(models).find((n) => /^\/3D\/3dmodel\.model$/i.test(n)) || Object.keys(models)[0];
86
+ if (!root) throw new Error('no 3D model in the 3MF');
87
+ const attr = (s, k) => { const m = s.match(new RegExp(`(?:^|\\s)${k}="([^"]*)"`)); return m ? m[1] : undefined; };
88
+ const objects = {}; // "<file>#<id>" -> { tris, components }
89
+ for (const [file, xml] of Object.entries(models)) {
90
+ for (const m of xml.matchAll(/<object\b([^>]*)>([\s\S]*?)<\/object>/g)) {
91
+ const id = attr(m[1], 'id'), body = m[2];
92
+ const verts = [...body.matchAll(/<vertex\b([^>]*)\/>/g)].map((v) => ['x', 'y', 'z'].map((k) => +attr(v[1], k)));
93
+ const tris = [...body.matchAll(/<triangle\b([^>]*)\/>/g)].map((t) => ['v1', 'v2', 'v3'].map((k) => verts[+attr(t[1], k)]));
94
+ const components = [...body.matchAll(/<component\b([^>]*)\/>/g)].map((c) => ({ ref: `${attr(c[1], 'p:path') || file}#${attr(c[1], 'objectid')}`, transform: attr(c[1], 'transform') }));
95
+ objects[`${file}#${id}`] = { tris, components };
96
+ }
97
+ }
98
+ const out = [];
99
+ const place = (key, M, depth = 0) => {
100
+ const o = objects[key];
101
+ if (!o || depth > 16) return;
102
+ for (const t of o.tris) out.push(t.map((v) => apply3mf(M, v)));
103
+ for (const c of o.components) place(c.ref, mul3mf(parse3mf(c.transform), M), depth + 1);
104
+ };
105
+ const items = [...models[root].matchAll(/<item\b([^>]*)\/>/g)];
106
+ if (items.length) for (const it of items) place(`${attr(it[1], 'p:path') || root}#${attr(it[1], 'objectid')}`, parse3mf(attr(it[1], 'transform')));
107
+ else for (const k of Object.keys(objects)) if (k.startsWith(root)) place(k, parse3mf());
108
+ if (!out.length) throw new Error('the 3MF has no triangles');
109
+ return out;
110
+ }
111
+ // 3MF transforms are 3 × 4, row vectors: p' = p · M (m00 m01 m02 m10 m11 m12 m20 m21 m22 m30 m31 m32)
112
+ const parse3mf = (s) => (s ? s.trim().split(/\s+/).map(Number) : [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]);
113
+ const apply3mf = (m, [x, y, z]) => [x * m[0] + y * m[3] + z * m[6] + m[9], x * m[1] + y * m[4] + z * m[7] + m[10], x * m[2] + y * m[5] + z * m[8] + m[11]];
114
+ const mul3mf = (a, b) => { // a then b
115
+ const r = [];
116
+ for (let i = 0; i < 4; i++) for (let j = 0; j < 3; j++) r.push((i < 3 ? 0 : b[9 + j]) + a[i * 3] * b[j] + a[i * 3 + 1] * b[3 + j] + a[i * 3 + 2] * b[6 + j]);
117
+ return r;
118
+ };
119
+
120
+ // ---- measuring ----
121
+
122
+ export function bounds(tris) {
123
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
124
+ for (const t of tris) for (const v of t) for (let a = 0; a < 3; a++) { if (v[a] < min[a]) min[a] = v[a]; if (v[a] > max[a]) max[a] = v[a]; }
125
+ return { min, max, size: max.map((m, a) => m - min[a]) };
126
+ }
127
+ export const volume = (tris) => Math.abs(tris.reduce((s, [a, b, c]) => s + (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6, 0));
128
+
129
+ // The cross-section at axis = v: segments in the plane's (across, up) coordinates
130
+ export function section(tris, axis, v) {
131
+ const [u, w] = planeAxes(axis), segs = [];
132
+ for (const t of tris) {
133
+ const pts = [];
134
+ for (let i = 0; i < 3; i++) {
135
+ const a = t[i], b = t[(i + 1) % 3], da = a[axis] - v, db = b[axis] - v;
136
+ if ((da < 0 && db >= 0) || (da >= 0 && db < 0)) { const f = da / (da - db); pts.push([a[u] + f * (b[u] - a[u]), a[w] + f * (b[w] - a[w])]); }
137
+ }
138
+ if (pts.length === 2) segs.push(pts);
139
+ }
140
+ return segs;
141
+ }
142
+
143
+ // Where a line through a section, at height h, is inside: [[from, to], …] across
144
+ export function crossings(segs, h) {
145
+ const xs = [];
146
+ for (const [a, b] of segs) if ((a[1] < h && b[1] >= h) || (a[1] >= h && b[1] < h)) xs.push(a[0] + ((h - a[1]) / (b[1] - a[1])) * (b[0] - a[0]));
147
+ xs.sort((p, q) => p - q);
148
+ const out = [];
149
+ for (let i = 0; i + 1 < xs.length; i += 2) out.push([xs[i], xs[i + 1]]);
150
+ return out;
151
+ }
152
+
153
+ // Where a line along an axis, through the point `at` (the other two coordinates), is inside the solid
154
+ export function spans(tris, axis, at) {
155
+ const [u, w] = planeAxes(axis), pu = at[0] + 1e-5, pw = at[1] + 1.3e-5; // off any edge
156
+ const hits = [];
157
+ for (const t of tris) {
158
+ const [a, b, c] = t;
159
+ const d = (b[u] - a[u]) * (c[w] - a[w]) - (c[u] - a[u]) * (b[w] - a[w]);
160
+ if (!d) continue;
161
+ const l1 = ((b[u] - pu) * (c[w] - pw) - (c[u] - pu) * (b[w] - pw)) / d, l2 = ((c[u] - pu) * (a[w] - pw) - (a[u] - pu) * (c[w] - pw)) / d, l3 = 1 - l1 - l2;
162
+ if (l1 >= 0 && l2 >= 0 && l3 >= 0) hits.push(l1 * a[axis] + l2 * b[axis] + l3 * c[axis]);
163
+ }
164
+ hits.sort((p, q) => p - q);
165
+ const out = [];
166
+ for (let i = 0; i + 1 < hits.length; i += 2) out.push([hits[i], hits[i + 1]]);
167
+ return out;
168
+ }
169
+
170
+ // Join a section's segments into outlines (closed where they meet up)
171
+ export function loops(segs, eps = 1e-4) {
172
+ const key = (p) => `${Math.round(p[0] / eps)},${Math.round(p[1] / eps)}`;
173
+ const from = new Map();
174
+ segs.forEach((s, i) => { for (const p of s) { const k = key(p); if (!from.has(k)) from.set(k, []); from.get(k).push(i); } });
175
+ const used = new Set(), out = [];
176
+ for (let i = 0; i < segs.length; i++) {
177
+ if (used.has(i)) continue;
178
+ used.add(i);
179
+ const line = [segs[i][0], segs[i][1]];
180
+ for (;;) {
181
+ const end = line[line.length - 1], next = (from.get(key(end)) || []).find((j) => !used.has(j));
182
+ if (next === undefined) break;
183
+ used.add(next);
184
+ const [p, q] = segs[next];
185
+ line.push(key(p) === key(end) ? q : p);
186
+ }
187
+ out.push(line);
188
+ }
189
+ return out;
190
+ }
191
+
192
+ // The stretches along an axis where the cross-section stays the same. The section can only change at a vertex, so it
193
+ // is taken once between each pair of neighbouring vertex positions, and equal neighbours are merged. Stretches that
194
+ // change all along (a taper, a curve) come out as one stretch marked `varies`. Sections are compared by shape (where a
195
+ // grid of lines through them is inside, within tol), so a curve triangulated differently along its length still counts
196
+ // as the same. A mesh with more distinct positions than `max` is sampled evenly instead.
197
+ export function profiles(tris, axis, { max = 4000, tol = 0.05 } = {}) {
198
+ const { min, max: hi } = bounds(tris);
199
+ let cuts = [...new Set(tris.flatMap((t) => t.map((v) => Math.round(v[axis] * 1000) / 1000)))].sort((a, b) => a - b);
200
+ if (cuts.length > max) cuts = Array.from({ length: max + 1 }, (_, i) => min[axis] + ((hi[axis] - min[axis]) * i) / max);
201
+ // A section's signature is its shape, not its triangulation: where lines across it, and up it, are inside
202
+ const [u, w] = planeAxes(axis), grid = 48;
203
+ const lines = (a) => Array.from({ length: grid }, (_, i) => min[a] + ((hi[a] - min[a]) * (i + 0.5)) / grid);
204
+ const swap = (segs) => segs.map((sg) => sg.map(([x, y]) => [y, x]));
205
+ const sig = (segs) => [...lines(w).map((h) => crossings(segs, h).flat()), ...lines(u).map((h) => crossings(swap(segs), h).flat())];
206
+ // The same shape: every line crosses it as often, at places within tol (a curve's facets move a crossing a little)
207
+ const same = (a, b) => a.every((l, i) => l.length === b[i].length && l.every((x, j) => Math.abs(x - b[i][j]) <= tol));
208
+ const runs = [];
209
+ for (let i = 0; i + 1 < cuts.length; i++) {
210
+ const at = (cuts[i] + cuts[i + 1]) / 2, segs = section(tris, axis, at), s = sig(segs);
211
+ const last = runs[runs.length - 1];
212
+ if (last && same(last.sig, s)) last.to = cuts[i + 1];
213
+ else runs.push({ from: cuts[i], to: cuts[i + 1], sig: s, at, segs });
214
+ }
215
+ // Short runs that differ from each neighbour are a changing stretch (a taper or curve): merge them
216
+ const out = [];
217
+ for (const r of runs) {
218
+ const last = out[out.length - 1], short = (x) => x.to - x.from < (hi[axis] - min[axis]) / 200;
219
+ if (last && short(r) && (last.varies || short(last))) { last.to = r.to; last.varies = true; } else out.push({ ...r, varies: false });
220
+ }
221
+ // Number the distinct shapes: a stretch with the same section as an earlier one gets its number
222
+ const distinct = [];
223
+ for (const r of out) {
224
+ if (!r.varies) { r.at = (r.from + r.to) / 2; r.segs = section(tris, axis, r.at); } // the middle: clear of any lead-in at its ends
225
+ Object.assign(r, profileOf(r.segs));
226
+ if (r.varies || r.empty) continue;
227
+ r.shape = distinct.findIndex((x) => same(x, r.sig));
228
+ if (r.shape < 0) { distinct.push(r.sig); r.shape = distinct.length - 1; }
229
+ }
230
+ for (const r of out) delete r.sig;
231
+ return out;
232
+ }
233
+
234
+ // A cross-section described: its extent, and its height bands: the heights over which it has the same number of separate
235
+ // pieces across (one for a plate; three where a key stands up between two lips), split again at steps in the outline. Each band gives the pieces at its
236
+ // bottom and top and at their widest; `straight` when the sides don't move within the band (no slope or curve).
237
+ export function profileOf(segs) {
238
+ if (!segs.length) return { empty: true, bands: [] };
239
+ const pts = segs.flat(), us = pts.map((p) => p[0]), ws = pts.map((p) => p[1]);
240
+ const extent = { across: [Math.min(...us), Math.max(...us)], up: [Math.min(...ws), Math.max(...ws)] };
241
+ const levels = [...new Set(ws.map((w) => Math.round(w * 1000) / 1000))].sort((a, b) => a - b);
242
+ const raw = [];
243
+ for (let i = 0; i + 1 < levels.length; i++) {
244
+ const r = { from: levels[i], to: levels[i + 1], inside: crossings(segs, (levels[i] + levels[i + 1]) / 2) };
245
+ if (r.to - r.from < 0.02 && raw.length) raw[raw.length - 1].to = r.to; else raw.push(r); // slivers between facets
246
+ }
247
+ // Steps: flat stretches of outline (a ledge, a shoulder) start a new band even when the piece count doesn't change
248
+ const steps = new Set(segs.filter(([a, b]) => Math.abs(a[1] - b[1]) < 1e-6 && Math.abs(a[0] - b[0]) > 0.05).map(([a]) => Math.round(a[1] * 1000) / 1000));
249
+ const bands = [];
250
+ for (const r of raw) {
251
+ const last = bands[bands.length - 1];
252
+ if (last && last.pieces === r.inside.length && ![...steps].some((h) => Math.abs(h - r.from) < 0.02)) { last.to = r.to; last.top = r.inside; last.n++; last.widest = last.widest.map(([a, b], j) => [Math.min(a, r.inside[j][0]), Math.max(b, r.inside[j][1])]); }
253
+ else bands.push({ from: r.from, to: r.to, pieces: r.inside.length, bottom: r.inside, top: r.inside, widest: r.inside, n: 1 });
254
+ }
255
+ const near = (x, y) => x.every(([a, b], j) => Math.abs(a - y[j][0]) < 0.01 && Math.abs(b - y[j][1]) < 0.01);
256
+ for (const g of bands) { g.straight = near(g.bottom, g.top) && near(g.bottom, g.widest); g.inside = g.widest; delete g.n; }
257
+ return { extent, bands, curved: bands.some((g) => !g.straight), loops: loops(segs) };
258
+ }
259
+
260
+ // ---- comparing ----
261
+
262
+ // The 24 ways to turn a part a quarter turn at a time, as 3 × 3 matrices (rows), with names like "rx90 rz180"
263
+ export const turns = (() => {
264
+ const rot = (a, q) => { const c = [1, 0, -1, 0][q], s = [0, 1, 0, -1][q], m = { 0: [[1, 0, 0], [0, c, -s], [0, s, c]], 1: [[c, 0, s], [0, 1, 0], [-s, 0, c]], 2: [[c, -s, 0], [s, c, 0], [0, 0, 1]] }; return m[a]; };
265
+ const mul = (A, B) => A.map((r) => B[0].map((_, j) => r.reduce((s, x, k) => s + x * B[k][j], 0)));
266
+ const seen = new Map();
267
+ for (const [a0, q0] of [[0, 0], [0, 1], [0, 2], [0, 3], [1, 1], [1, 3]]) for (let q1 = 0; q1 < 4; q1++) {
268
+ const M = mul(rot(2, q1), rot(a0, q0)), k = JSON.stringify(M);
269
+ const name = [q0 ? `r${AXES[a0]}${q0 * 90}` : '', q1 ? `rz${q1 * 90}` : ''].filter(Boolean).join(' ') || 'none';
270
+ if (!seen.has(k)) seen.set(k, { name, M });
271
+ }
272
+ return [...seen.values()];
273
+ })();
274
+ export const turn = (tris, M, shift = [0, 0, 0]) => tris.map((t) => t.map((v) => M.map((r, i) => r[0] * v[0] + r[1] * v[1] + r[2] * v[2] + shift[i])));
275
+
276
+ // "rz90 rx180 t1,2,3" -> { M, shift }: turns applied in order, then the shift
277
+ export function parsePlacement(s) {
278
+ let M = [[1, 0, 0], [0, 1, 0], [0, 0, 1]], shift = [0, 0, 0];
279
+ for (const w of String(s).trim().split(/\s+/).filter(Boolean)) {
280
+ const r = w.match(/^r([xyz])(-?\d+)$/), t = w.match(/^t(-?[\d.]+),(-?[\d.]+),(-?[\d.]+)$/);
281
+ if (r) {
282
+ const q = ((+r[2] / 90) % 4 + 4) % 4;
283
+ if (!Number.isInteger(q)) throw new Error(`${w}: quarter turns only (90, 180, 270)`);
284
+ const one = turns.find((x) => x.name === (q ? `r${r[1]}${q * 90}` : 'none'))?.M || rotOne(axisOf(r[1]), q);
285
+ M = one.map((row) => M[0].map((_, j) => row.reduce((s2, x, k) => s2 + x * M[k][j], 0)));
286
+ } else if (t) shift = shift.map((v, i) => v + +t[i + 1]);
287
+ else throw new Error(`placement "${w}": use rx90, ry180, rz270 and t<x>,<y>,<z>`);
288
+ }
289
+ return { M, shift };
290
+ }
291
+ const rotOne = (a, q) => { const c = [1, 0, -1, 0][q], s = [0, 1, 0, -1][q]; return { 0: [[1, 0, 0], [0, c, -s], [0, s, c]], 1: [[c, 0, s], [0, 1, 0], [-s, 0, c]], 2: [[c, -s, 0], [s, c, 0], [0, 0, 1]] }[a]; };
292
+
293
+ // Nearest-point queries on a mesh, through a grid of its triangles
294
+ export function surface(tris) {
295
+ const { min, size } = bounds(tris);
296
+ const h = Math.max(Math.cbrt((size[0] + 1) * (size[1] + 1) * (size[2] + 1) / Math.max(tris.length, 1)) * 1.5, 0.2);
297
+ const dims = size.map((s) => Math.max(1, Math.ceil((s + 1e-9) / h)));
298
+ const cell = (v, a) => Math.min(dims[a] - 1, Math.max(0, Math.floor((v - min[a]) / h)));
299
+ const grid = new Map(), id = (i, j, k) => (i * dims[1] + j) * dims[2] + k;
300
+ const normals = tris.map(([a, b, c]) => { const u = sub(b, a), v = sub(c, a), n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]], l = Math.hypot(...n) || 1; return n.map((x) => x / l); });
301
+ tris.forEach((t, n) => {
302
+ const lo = [0, 1, 2].map((a) => cell(Math.min(t[0][a], t[1][a], t[2][a]), a)), hi = [0, 1, 2].map((a) => cell(Math.max(t[0][a], t[1][a], t[2][a]), a));
303
+ for (let i = lo[0]; i <= hi[0]; i++) for (let j = lo[1]; j <= hi[1]; j++) for (let k = lo[2]; k <= hi[2]; k++) { const c = id(i, j, k); if (!grid.has(c)) grid.set(c, []); grid.get(c).push(n); }
304
+ });
305
+ const far = Math.max(...dims);
306
+ // nearest(p) -> { d (signed: + outside, - inside), q (the nearest point), n (its triangle) }
307
+ const nearest = (p) => {
308
+ const c = [0, 1, 2].map((a) => Math.floor((p[a] - min[a]) / h));
309
+ let best = null;
310
+ for (let r = 0; r <= far + Math.ceil(Math.max(...[0, 1, 2].map((a) => Math.max(-c[a], c[a] - dims[a] + 1, 0)))); r++) {
311
+ for (let i = c[0] - r; i <= c[0] + r; i++) for (let j = c[1] - r; j <= c[1] + r; j++) for (let k = c[2] - r; k <= c[2] + r; k++) {
312
+ if (Math.max(Math.abs(i - c[0]), Math.abs(j - c[1]), Math.abs(k - c[2])) !== r) continue; // this ring only
313
+ if (i < 0 || j < 0 || k < 0 || i >= dims[0] || j >= dims[1] || k >= dims[2]) continue;
314
+ for (const n of grid.get(id(i, j, k)) || []) {
315
+ const q = closest(p, tris[n]), d = Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]);
316
+ if (!best || d < best.dist - 1e-12) best = { dist: d, q, n };
317
+ }
318
+ }
319
+ // Anything in a farther ring is at least r × h away (less the distance from p to its cell's edge)
320
+ if (best && best.dist <= r * h) break;
321
+ }
322
+ if (!best) return null;
323
+ const v = sub(p, best.q), nn = normals[best.n];
324
+ let sign = Math.sign(v[0] * nn[0] + v[1] * nn[1] + v[2] * nn[2]);
325
+ if (best.dist > 1e-9 && Math.abs(v[0] * nn[0] + v[1] * nn[1] + v[2] * nn[2]) < best.dist * 0.5) sign = pseudoSign(p, best, (grid.get(id(...[0, 1, 2].map((a) => cell(best.q[a], a)))) || []).map((n) => tris[n]), (grid.get(id(...[0, 1, 2].map((a) => cell(best.q[a], a)))) || []).map((n) => normals[n])); // near an edge: ask the neighbours
326
+ return { d: (sign || 1) * best.dist, q: best.q, n: best.n };
327
+ };
328
+ return { nearest, normals };
329
+ }
330
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
331
+ // At an edge or corner the nearest face's normal can point either way: average the normals of the faces that share the
332
+ // nearest point
333
+ function pseudoSign(p, best, tris, normals) { // tris and normals: the faces near the nearest point
334
+ const q = best.q, v = sub(p, q), acc = [0, 0, 0];
335
+ tris.forEach((t, n) => { if (Math.hypot(...sub(closest(q, t), q)) < 1e-6) for (let a = 0; a < 3; a++) acc[a] += normals[n][a]; });
336
+ return Math.sign(v[0] * acc[0] + v[1] * acc[1] + v[2] * acc[2]);
337
+ }
338
+
339
+ // The point of triangle t nearest p (Ericson, Real-Time Collision Detection, 5.1.5)
340
+ export function closest(p, [a, b, c]) {
341
+ const ab = sub(b, a), ac = sub(c, a), ap = sub(p, a), dot = (x, y) => x[0] * y[0] + x[1] * y[1] + x[2] * y[2];
342
+ const at = (s, t) => [a[0] + ab[0] * s + ac[0] * t, a[1] + ab[1] * s + ac[1] * t, a[2] + ab[2] * s + ac[2] * t];
343
+ const d1 = dot(ab, ap), d2 = dot(ac, ap);
344
+ if (d1 <= 0 && d2 <= 0) return a;
345
+ const bp = sub(p, b), d3 = dot(ab, bp), d4 = dot(ac, bp);
346
+ if (d3 >= 0 && d4 <= d3) return b;
347
+ const vc = d1 * d4 - d3 * d2;
348
+ if (vc <= 0 && d1 >= 0 && d3 <= 0) return at(d1 / (d1 - d3), 0);
349
+ const cp = sub(p, c), d5 = dot(ab, cp), d6 = dot(ac, cp);
350
+ if (d6 >= 0 && d5 <= d6) return c;
351
+ const vb = d5 * d2 - d1 * d6;
352
+ if (vb <= 0 && d2 >= 0 && d6 <= 0) return at(0, d2 / (d2 - d6));
353
+ const va = d3 * d6 - d5 * d4;
354
+ if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { const w = (d4 - d3) / (d4 - d3 + (d5 - d6)); return [b[0] + (c[0] - b[0]) * w, b[1] + (c[1] - b[1]) * w, b[2] + (c[2] - b[2]) * w]; }
355
+ const den = 1 / (va + vb + vc);
356
+ return at(vb * den, vc * den);
357
+ }
358
+
359
+ // Points spread evenly over a surface, by area; the same points every run (a fixed seed)
360
+ export function sample(tris, n) {
361
+ const areas = tris.map(([a, b, c]) => { const u = sub(b, a), v = sub(c, a); return Math.hypot(u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) / 2; });
362
+ const total = areas.reduce((s, x) => s + x, 0), cum = [];
363
+ areas.reduce((s, x, i) => (cum[i] = s + x), 0);
364
+ let seed = 12345;
365
+ const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648);
366
+ const out = [];
367
+ for (let i = 0; i < n; i++) {
368
+ const r = rnd() * total;
369
+ let lo = 0, hi = cum.length - 1;
370
+ while (lo < hi) { const m = (lo + hi) >> 1; if (cum[m] < r) lo = m + 1; else hi = m; }
371
+ const [a, b, c] = tris[lo];
372
+ let s = rnd(), t = rnd();
373
+ if (s + t > 1) { s = 1 - s; t = 1 - t; }
374
+ out.push([0, 1, 2].map((k) => a[k] + (b[k] - a[k]) * s + (c[k] - a[k]) * t));
375
+ }
376
+ return out;
377
+ }
378
+
379
+ // Lay `moving` over `fixed`: try the quarter turns whose bounding box matches best, centre them, then shift by the mean
380
+ // offset to the nearest points a few times. Returns { name, M, shift, score (mean distance) }.
381
+ export function align(moving, fixed, { samples = 1500 } = {}) {
382
+ const F = bounds(fixed), S = surface(fixed), centre = (b) => b.min.map((m, a) => (m + b.max[a]) / 2);
383
+ const tried = turns.map((t) => { const b = bounds(turn(moving, t.M)); return { ...t, b, fit: b.size.reduce((s, x, a) => s + Math.abs(x - F.size[a]), 0) }; });
384
+ const bestFit = Math.min(...tried.map((t) => t.fit));
385
+ const results = [];
386
+ for (const t of tried.filter((x) => x.fit <= bestFit + 0.5)) {
387
+ let shift = sub(centre(F), centre(t.b));
388
+ const pts = sample(turn(moving, t.M), samples);
389
+ let score = Infinity;
390
+ for (let it = 0; it < 10; it++) {
391
+ const off = [0, 0, 0];
392
+ let sum = 0;
393
+ for (const p of pts) { const q = [p[0] + shift[0], p[1] + shift[1], p[2] + shift[2]], n = S.nearest(q); sum += Math.abs(n.d); for (let a = 0; a < 3; a++) off[a] += n.q[a] - q[a]; }
394
+ score = sum / pts.length;
395
+ const step = off.map((x) => x / pts.length);
396
+ shift = shift.map((x, a) => x + step[a]);
397
+ if (Math.hypot(...step) < 1e-4) break;
398
+ }
399
+ results.push({ name: t.name, M: t.M, shift, score });
400
+ }
401
+ return results.sort((a, b) => a.score - b.score)[0];
402
+ }
403
+
404
+ // How far each sampled point of `from` is from the surface of `to`, signed (+: outside `to`, -: inside it)
405
+ export function deviation(from, to, { samples = 20000 } = {}) {
406
+ const S = surface(to);
407
+ return sample(from, samples).map((p) => ({ p, d: S.nearest(p).d }));
408
+ }
409
+
410
+ // The worst places: the largest deviations, at least `apart` mm from each other
411
+ export function worst(points, { count = 5, apart = 3 } = {}) {
412
+ const out = [];
413
+ for (const x of [...points].sort((a, b) => Math.abs(b.d) - Math.abs(a.d))) {
414
+ if (out.length >= count) break;
415
+ if (out.every((o) => Math.hypot(...sub(o.p, x.p)) >= apart)) out.push(x);
416
+ }
417
+ return out;
418
+ }
419
+
420
+ export function stats(points) {
421
+ const a = points.map((x) => Math.abs(x.d)).sort((p, q) => p - q), n = a.length;
422
+ const pct = (f) => a[Math.min(n - 1, Math.floor(f * n))];
423
+ return { max: a[n - 1], mean: a.reduce((s, x) => s + x, 0) / n, p95: pct(0.95), signed: points.reduce((s, x) => s + x.d, 0) / n };
424
+ }
425
+
426
+ // Licences that limit what can be made from a model (non-commercial, no derivatives, share-alike)
427
+ export const limitingLicence = (s) => /\b(NC|ND|SA)\b|non-?commercial|no-?deriv|share-?alike|share alike/i.test(String(s || ''));
@@ -0,0 +1,204 @@
1
+ // cad measure and cad match: a mesh from elsewhere, measured into draft rules, and a design checked against it.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fmt } from './rules.mjs';
5
+ import { WS, paths } from './workspace.mjs';
6
+ import { picture, preview } from './preview.mjs';
7
+ import {
8
+ AXES, axisOf, planeAxes, readMesh, bounds, volume, section, profiles, spans, loops, parsePlacement, turn, align, deviation, worst, stats, limitingLicence,
9
+ } from './mesh.mjs';
10
+
11
+ const f2 = (n) => fmt(Math.round(n * 100) / 100);
12
+ const range = ([a, b]) => `${f2(a)}..${f2(b)}`;
13
+ const letter = (i) => String.fromCharCode(65 + (i % 26)) + (i >= 26 ? Math.floor(i / 26) : '');
14
+ const today = () => new Date().toISOString().slice(0, 10);
15
+
16
+ // Edges used by one face only: holes in the surface, which make inside and outside meaningless
17
+ function openEdges(tris) {
18
+ const k = (v) => v.map((x) => Math.round(x * 1e4)).join(','), count = new Map();
19
+ for (const t of tris) for (let i = 0; i < 3; i++) { const a = k(t[i]), b = k(t[(i + 1) % 3]), e = a < b ? `${a}|${b}` : `${b}|${a}`; count.set(e, (count.get(e) || 0) + 1); }
20
+ return [...count.values()].filter((n) => n === 1).length;
21
+ }
22
+
23
+ // ---- drawing sections ----
24
+
25
+ // panels: [{ title, layers: [{ segs, style: 'design' | 'reference' }], marks: [[u, w]] }], all in one scale
26
+ function sectionsSvg(panels, { title, note, axis }) {
27
+ const [u, w] = planeAxes(axis), W = 1800, H = 1200, head = 110, cols = Math.min(panels.length, 3), rows = Math.ceil(panels.length / cols);
28
+ const pw = W / cols, ph = (H - head) / rows, pad = 70;
29
+ const all = panels.flatMap((p) => p.layers.flatMap((l) => l.segs.flat()));
30
+ if (!all.length) return '';
31
+ const lo = [Math.min(...all.map((p) => p[0])), Math.min(...all.map((p) => p[1]))], hi = [Math.max(...all.map((p) => p[0])), Math.max(...all.map((p) => p[1]))];
32
+ const s = Math.min((pw - pad * 2) / (hi[0] - lo[0] || 1), (ph - pad * 2) / (hi[1] - lo[1] || 1));
33
+ const esc = (t) => String(t).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
34
+ let body = '';
35
+ panels.forEach((p, i) => {
36
+ const ox = (i % cols) * pw, oy = head + Math.floor(i / cols) * ph;
37
+ const X = (x) => ox + pw / 2 + (x - (lo[0] + hi[0]) / 2) * s, Y = (y) => oy + ph / 2 - (y - (lo[1] + hi[1]) / 2) * s;
38
+ body += `<text x="${ox + 32}" y="${oy + 36}" class="h">${esc(p.title)}</text>`;
39
+ // a 1 mm scale bar
40
+ body += `<line x1="${ox + 32}" y1="${oy + ph - 30}" x2="${ox + 32 + s}" y2="${oy + ph - 30}" stroke="#8a8a8a" stroke-width="2"/><text x="${ox + 40 + s}" y="${oy + ph - 24}" class="m">1 mm</text>`;
41
+ for (const l of p.layers) {
42
+ const d = loops(l.segs).map((line) => `M${line.map(([a, b]) => `${X(a).toFixed(1)},${Y(b).toFixed(1)}`).join('L')}`).join('');
43
+ body += l.style === 'reference'
44
+ ? `<path d="${d}" fill="none" stroke="#b4b4b4" stroke-width="2" stroke-dasharray="7 5"/>`
45
+ : `<path d="${d}" fill="#3a3a3a" fill-rule="evenodd" stroke="#ffffff" stroke-width="1.6"/>`;
46
+ }
47
+ for (const [a, b] of p.marks || []) body += `<circle cx="${X(a)}" cy="${Y(b)}" r="9" fill="none" stroke="#ffffff" stroke-width="2"/>`;
48
+ body += `<text x="${ox + 32}" y="${oy + 62}" class="m">${AXES[u]} across, ${AXES[w]} up</text>`;
49
+ });
50
+ const legend = panels.some((p) => p.layers.some((l) => l.style === 'reference'))
51
+ ? `<rect x="1180" y="40" width="34" height="18" fill="#3a3a3a" stroke="#fff"/><text x="1226" y="55" class="m">design</text><line x1="1340" y1="49" x2="1380" y2="49" stroke="#b4b4b4" stroke-width="2" stroke-dasharray="7 5"/><text x="1392" y="55" class="m">reference</text><circle cx="1530" cy="49" r="9" fill="none" stroke="#fff" stroke-width="2"/><text x="1548" y="55" class="m">worst places</text>` : '';
52
+ return `<!doctype html><html><head><meta charset="utf-8"></head><body style="margin:0;background:#000"><svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
53
+ <style>text{font-family:-apple-system,Helvetica,Arial,sans-serif;fill:#fff}.t{font-size:30px}.n{font-size:21px;fill:#9a9a9a}.h{font-size:19px;letter-spacing:2px;fill:#9a9a9a}.m{font-size:17px;fill:#8a8a8a}</style>
54
+ <rect width="${W}" height="${H}" fill="#000"/><text x="32" y="52" class="t">${esc(title)}</text><text x="32" y="86" class="n">${esc(note)}</text>${legend}${body}</svg></body></html>`;
55
+ }
56
+
57
+ // ---- cad measure ----
58
+
59
+ // measure(file, { along, at: ['10', '50'], line: ['0.6,2.5'], rules, source, licence, force, pictures }) -> prints the report;
60
+ // writes the profiles' drawing, and draft rules when asked
61
+ export async function measure(file, o = {}) {
62
+ if (!fs.existsSync(file)) throw new Error(`no file ${file}`);
63
+ const tris = readMesh(file), B = bounds(tris);
64
+ const axis = o.along ? axisOf(o.along) : B.size.indexOf(Math.max(...B.size)), [u, w] = planeAxes(axis), A = AXES[axis];
65
+ const name = path.basename(file).replace(/\.[^.]+$/, '');
66
+ const open = openEdges(tris);
67
+ console.log(`${path.basename(file)}: ${tris.length} triangles${open ? `, ${open} open edges (not a closed solid: inside and outside are guesses)` : ', a closed solid'}`);
68
+ console.log(` size ${B.size.map(f2).join(' × ')} mm: ${AXES.map((a, i) => `${a} ${range([B.min[i], B.max[i]])}`).join(', ')}; volume ${fmt(Math.round(volume(tris) / 10) / 100)} cm³`);
69
+ if (o.licence && limitingLicence(o.licence)) console.log(` ! licence "${o.licence}" limits reuse: measurements are facts, but don't copy the model's shape into a design under another licence`);
70
+
71
+ // Stretches along the axis with the same cross-section, and the distinct shapes among them
72
+ const runs = profiles(tris, axis), shapes = [];
73
+ for (const r of runs) {
74
+ if (r.shape === undefined) continue;
75
+ if (!shapes[r.shape]) shapes[r.shape] = { ...r, first: r };
76
+ r.shape = letter(r.shape);
77
+ }
78
+ console.log(`\n along ${A}: ${runs.length} stretches, ${shapes.length} distinct cross-sections (positions from ${A} = ${f2(B.min[axis])})`);
79
+ for (const r of runs) {
80
+ const len = r.to - r.from, at = `${f2(r.from)}..${f2(r.to)}`.padEnd(16);
81
+ console.log(` ${at} ${`(${f2(len)})`.padEnd(9)} ${r.varies ? 'changing: a taper, slope or curve' : r.empty ? 'empty' : `section ${r.shape}`}`);
82
+ }
83
+ for (const [i, s] of shapes.entries()) {
84
+ console.log(`\n section ${letter(i)}: ${AXES[u]} ${range(s.extent.across)} (${f2(s.extent.across[1] - s.extent.across[0])} wide), ${AXES[w]} ${range(s.extent.up)} (${f2(s.extent.up[1] - s.extent.up[0])} high)${s.curved ? ', with sloped or curved sides' : ''}`);
85
+ for (const b of s.bands) {
86
+ const pieces = (x) => x.map(range).join(' + ');
87
+ const how = b.straight ? pieces(b.widest) : `${pieces(b.bottom)} at the bottom, ${pieces(b.top)} at the top, widest ${pieces(b.widest)}`;
88
+ console.log(` ${AXES[w]} ${range([b.from, b.to])}`.padEnd(24) + (b.pieces ? `${b.pieces} piece${b.pieces === 1 ? '' : 's'} at ${AXES[u]} ${how}` : 'nothing (a gap under material above)'));
89
+ }
90
+ }
91
+
92
+ // Lines along the axis: where they are inside
93
+ const lines = (o.line || []).map((t) => { const p = String(t).split(',').map(Number); if (p.length !== 2 || p.some(Number.isNaN)) throw new Error(`--line ${t}: two numbers, ${AXES[u]},${AXES[w]}`); return p; });
94
+ const found = lines.map((p) => ({ p, inside: spans(tris, axis, p) }));
95
+ for (const l of found) console.log(`\n along ${A} at ${AXES[u]} ${f2(l.p[0])}, ${AXES[w]} ${f2(l.p[1])}: inside ${l.inside.map(range).join(', ') || 'nowhere'}`);
96
+
97
+ // The drawing: each distinct section, and any asked for
98
+ const panels = shapes.map((s, i) => ({ title: `SECTION ${letter(i)} · ${A} ${f2(s.first.from)}..${f2(s.first.to)}`, layers: [{ segs: s.first.segs, style: 'design' }] }));
99
+ for (const at of (o.at || []).map(Number)) panels.push({ title: `${A} = ${f2(at)}`, layers: [{ segs: section(tris, axis, at), style: 'design' }] });
100
+ if (panels.length && o.pictures !== false) {
101
+ const out = paths.preview('measure', `${name}.png`);
102
+ await picture(sectionsSvg(panels.slice(0, 9), { title: `${path.basename(file)}: sections across ${A}`, note: `${B.size.map(f2).join(' × ')} mm · ${runs.length} stretches along ${A}`, axis }), out);
103
+ console.log(`\n drawing: ${out}`);
104
+ }
105
+
106
+ if (o.rules) writeDraft({ o, name, file, B, axis, runs, shapes, found });
107
+ }
108
+
109
+ // Draft rules from a measurement: kind derived, every value traced to the file (and its source and licence). Names are
110
+ // placeholders (stretch2_from, sectionB_w): rename them for what they are before a design uses them.
111
+ function writeDraft({ o, name, file, B, axis, runs, shapes, found }) {
112
+ const set = String(o.rules);
113
+ if (!/^[a-z][a-z0-9_]*$/.test(set)) throw new Error('--rules <name>: lower case, digits and _ (a rule set name)');
114
+ const to = path.join(WS, 'rules', `${set}.json`);
115
+ if (fs.existsSync(to) && !o.force) throw new Error(`rules/${set}.json already exists (--force to replace it)`);
116
+ const [u, w] = planeAxes(axis), A = AXES[axis], base = B.min[axis];
117
+ const src = o.source || path.basename(file), extra = { kind: 'derived', source: src, ...(o.licence ? { licence: o.licence } : {}), checked: today() };
118
+ const rules = {};
119
+ const add = (k, v, rule) => { rules[k] = { value: Math.round(v * 100) / 100, unit: 'mm', rule, ...extra }; };
120
+ AXES.forEach((a, i) => add(`size_${a}`, B.size[i], `Overall size in ${a}`));
121
+ runs.forEach((r, i) => {
122
+ add(`stretch${i + 1}_from`, r.from - base, `Stretch ${i + 1} (${r.varies ? 'changing' : `section ${r.shape}`}) starts, from the model's lowest ${A}`);
123
+ add(`stretch${i + 1}_len`, r.to - r.from, `Stretch ${i + 1} length along ${A}`);
124
+ });
125
+ shapes.forEach((s, i) => {
126
+ const L = letter(i);
127
+ add(`section${L}_w`, s.extent.across[1] - s.extent.across[0], `Section ${L}: width in ${AXES[u]}`);
128
+ add(`section${L}_h`, s.extent.up[1] - s.extent.up[0], `Section ${L}: height in ${AXES[w]}`);
129
+ s.bands.forEach((b, j) => {
130
+ const at = `section${L}_band${j + 1}`;
131
+ add(`${at}_at`, b.from - s.extent.up[0], `Section ${L}, band ${j + 1} (${b.pieces} piece${b.pieces === 1 ? '' : 's'}): its bottom, from the section's lowest ${AXES[w]}`);
132
+ add(`${at}_h`, b.to - b.from, `Section ${L}, band ${j + 1}: its height`);
133
+ b.widest.forEach(([p, q], k) => add(`${at}_piece${k + 1}_w`, q - p, `Section ${L}, band ${j + 1}, piece ${k + 1}: widest, from ${AXES[u]} ${f2(p)}`));
134
+ });
135
+ });
136
+ found.forEach((l, i) => l.inside.forEach(([a, b], j) => {
137
+ add(`line${i + 1}_${j + 1}_from`, a - base, `Along ${A} at ${AXES[u]} ${f2(l.p[0])}, ${AXES[w]} ${f2(l.p[1])}: inside from (from the lowest ${A})`);
138
+ add(`line${i + 1}_${j + 1}_to`, b - base, 'Inside to');
139
+ }));
140
+ const doc = `Measured from ${path.basename(file)} by cad measure (along ${A}). kind derived: read off someone else's model, so check it against the real thing; rename the placeholder names before a design uses them.${o.licence ? ` The model's licence: ${o.licence}.` : ''}`;
141
+ fs.mkdirSync(path.dirname(to), { recursive: true });
142
+ fs.writeFileSync(to, `${JSON.stringify({ _doc: doc, name: set, rules }, null, 2)}\n`);
143
+ console.log(`\n draft rules: ${path.relative(process.cwd(), to)} (${Object.keys(rules).length} values, kind derived: rename them for what they are)`);
144
+ }
145
+
146
+ // ---- cad match ----
147
+
148
+ // match(b, d, file, { place, tol, samples, at, pictures }) -> report; exit code 1 when the design is outside the tolerance
149
+ export async function match(b, d, file, { place, tol, samples = 20000, at = [], title, tag = '', pictures = true }) {
150
+ if (!fs.existsSync(file)) throw new Error(`no file ${file}`);
151
+ const fan = (polys) => polys.flatMap((p) => p.slice(1, -1).map((_, i) => [p[0], p[i + 1], p[i + 2]]));
152
+ const parts = b.parts.filter((p) => p.role !== 'support'), design = fan(parts.flatMap((p) => p.triangles));
153
+ const ref = readMesh(file);
154
+ const placed = place ? { ...parsePlacement(place), name: place, score: null } : align(ref, design);
155
+ const R = turn(ref, placed.M, placed.shift);
156
+ const words = (p) => `${p.name === 'none' ? '' : `${p.name} `}t${p.shift.map(f2).join(',')}`.trim();
157
+ console.log(`${title} against ${path.basename(file)}`);
158
+ console.log(` placed ${place ? 'as asked' : 'by fitting it to the design'}: ${words(placed)}${place ? '' : ` (pin it with --place "${words(placed)}")`}`);
159
+ if (openEdges(ref)) console.log(` ! the reference has ${openEdges(ref)} open edges: inside and outside are guesses near them`);
160
+
161
+ const D = deviation(design, R, { samples }), Rv = deviation(R, design, { samples });
162
+ const sd = stats(D), sr = stats(Rv);
163
+ const level = (s) => (s.max <= tol ? 'pass' : s.p95 <= tol ? 'warn' : 'fail');
164
+ const mark = { pass: '✓', warn: '!', fail: '✗' };
165
+ const side = (x) => (x < 0 ? 'inside' : 'outside');
166
+ console.log(` ${mark[level(sd)]} the design's surface: 95% within ${f2(sd.p95)} mm of the reference, ${f2(sd.max)} at most (mean ${f2(sd.mean)}; on average ${f2(Math.abs(sd.signed))} mm ${side(sd.signed)} it)`);
167
+ console.log(` ${mark[level(sr)]} the reference's surface: 95% within ${f2(sr.p95)} mm of the design, ${f2(sr.max)} at most (mean ${f2(sr.mean)})`);
168
+ console.log(` tolerance ${f2(tol)} mm${place ? '' : ''}: ✓ everything within it, ! only the worst 5% past it, ✗ more than that`);
169
+
170
+ const wd = worst(D.filter((x) => Math.abs(x.d) > tol)), wr = worst(Rv.filter((x) => Math.abs(x.d) > tol));
171
+ const where = (p) => AXES.map((a, i) => `${a} ${f2(p[i])}`).join(' ');
172
+ if (wd.length) { console.log(' where the design is off:'); for (const x of wd) console.log(` ${where(x.p)}: ${f2(Math.abs(x.d))} mm ${x.d > 0 ? 'outside the reference (extra material)' : 'inside the reference (material missing, or clearance)'}`); }
173
+ if (wr.length) { console.log(' where the reference has what the design lacks, or lacks what it has:'); for (const x of wr) console.log(` ${where(x.p)}: the reference is ${f2(Math.abs(x.d))} mm ${x.d > 0 ? 'outside the design (material the design lacks)' : 'inside the design (the design has extra here)'}`); }
174
+
175
+ // Along the longest axis: the worst deviation in each eighth, to see where it goes wrong
176
+ const DB = bounds(design), axis = DB.size.indexOf(Math.max(...DB.size)), lo = DB.min[axis], len = DB.size[axis] || 1;
177
+ const bins = Array(8).fill(0);
178
+ for (const x of [...D, ...Rv]) { const i = Math.min(7, Math.max(0, Math.floor(((x.p[axis] - lo) / len) * 8))); bins[i] = Math.max(bins[i], Math.abs(x.d)); }
179
+ console.log(` worst in each eighth along ${AXES[axis]}: ${bins.map(f2).join(' · ')} mm`);
180
+
181
+ const ok = level(sd) !== 'fail' && level(sr) !== 'fail';
182
+ if (!pictures) return ok;
183
+ // Pictures: the reference over the design, and sections through the worst places (and any asked for)
184
+ const out = paths.preview(d.project, `${d.name}${tag}-match.png`);
185
+ await preview([...parts, { name: 'reference', role: 'reference', label: 'reference', triangles: R }], { title: `${title}: match`, meta: `reference ${path.basename(file)} · faint lines`, out });
186
+ // Sections at the places asked for, then through the worst places: just inside the ends (a cut on an end face is
187
+ // empty), and at least 1 mm apart
188
+ const cuts = [];
189
+ for (const c of [...at.map(Number), ...[...wd, ...wr].map((x) => x.p[axis])]) {
190
+ const k = Math.round(Math.min(lo + len - 0.05, Math.max(lo + 0.05, c)) * 100) / 100;
191
+ if (cuts.length < 6 && cuts.every((x) => Math.abs(x - k) >= 1)) cuts.push(k);
192
+ }
193
+ if (!cuts.length) cuts.push(lo + len / 2);
194
+ const [u, w] = planeAxes(axis);
195
+ const panels = cuts.map((c) => ({
196
+ title: `${AXES[axis].toUpperCase()} = ${f2(c)}`,
197
+ layers: [{ segs: section(design, axis, c), style: 'design' }, { segs: section(R, axis, c), style: 'reference' }],
198
+ marks: [...wd, ...wr].filter((x) => Math.abs(x.p[axis] - c) < 0.5).map((x) => [x.p[u], x.p[w]]),
199
+ }));
200
+ const sOut = paths.preview(d.project, `${d.name}${tag}-match-sections.png`);
201
+ await picture(sectionsSvg(panels, { title: `${title} against ${path.basename(file)}`, note: `sections across ${AXES[axis]} · tolerance ${f2(tol)} mm · 95% within ${f2(Math.max(sd.p95, sr.p95))}, worst ${f2(Math.max(sd.max, sr.max))}`, axis }), sOut);
202
+ console.log(` pictures: ${out}\n ${sOut}`);
203
+ return ok;
204
+ }
package/lib/preview.mjs CHANGED
@@ -30,6 +30,16 @@ export async function preview(parts, { title = '', meta = '', out, explode = fal
30
30
  if (u.startsWith('/three/') && fs.existsSync(f)) return send('text/javascript', fs.readFileSync(f));
31
31
  res.writeHead(404); res.end();
32
32
  });
33
+ return shoot(server, out);
34
+ }
35
+
36
+ // Any page as an image: html served on this Mac for the few seconds Chrome takes (an SVG drawing, a report)
37
+ export async function picture(html, out, { width = 1800, height = 1200 } = {}) {
38
+ const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(html); });
39
+ return shoot(server, out, { width, height });
40
+ }
41
+
42
+ async function shoot(server, out, { width = 1800, height = 1200 } = {}) {
33
43
  await new Promise((r) => server.listen(0, '127.0.0.1', r));
34
44
  const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'cad-preview-'));
35
45
  fs.mkdirSync(path.dirname(out), { recursive: true });
@@ -37,7 +47,7 @@ export async function preview(parts, { title = '', meta = '', out, explode = fal
37
47
  await new Promise((resolve, reject) => {
38
48
  if (!CHROME) return reject(new Error('no Chrome or Chromium found for previews: set CAD_CHROME to one'));
39
49
  const p = spawn(CHROME, ['--headless=new', `--user-data-dir=${profile}`, '--no-first-run', '--hide-scrollbars', '--force-device-scale-factor=1',
40
- '--window-size=1800,1200', '--virtual-time-budget=8000', `--screenshot=${out}`, `http://127.0.0.1:${server.address().port}/`], { stdio: 'ignore' });
50
+ `--window-size=${width},${height}`, '--virtual-time-budget=8000', `--screenshot=${out}`, `http://127.0.0.1:${server.address().port}/`], { stdio: 'ignore' });
41
51
  const t = setTimeout(() => { p.kill(); reject(new Error('Chrome took too long to render the preview')); }, 60000);
42
52
  p.on('exit', () => { clearTimeout(t); fs.existsSync(out) ? resolve() : reject(new Error('Chrome made no screenshot')); });
43
53
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.3.2",
3
+ "version": "0.3.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": {
@@ -43,11 +43,11 @@
43
43
  "directory": "packages/cad"
44
44
  },
45
45
  "dependencies": {
46
- "@rulecad/variables": "^0.1.4",
46
+ "@rulecad/variables": "^0.1.6",
47
47
  "@rulecad/keyboard-layout": "^0.1.2",
48
48
  "@rulecad/printcheck": "^0.1.0",
49
49
  "@rulecad/fit": "^0.2.0",
50
- "@rulecad/model-link": "^0.1.4",
50
+ "@rulecad/model-link": "^0.1.5",
51
51
  "@rulecad/versions": "^0.1.0",
52
52
  "@rulecad/shapes": "^0.2.0",
53
53
  "@rulecad/rules": "^0.2.0",