@rulecad/cad 0.3.3 → 0.4.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 +12 -0
- package/README.md +83 -0
- package/bin/cad.mjs +62 -5
- package/lib/assembly.mjs +211 -24
- package/lib/mesh.mjs +427 -0
- package/lib/meshcmd.mjs +204 -0
- package/lib/preview.mjs +11 -1
- package/package.json +2 -2
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).
|
|
@@ -47,6 +56,9 @@ variable says which rule it comes from. Follow these steps; they're what makes a
|
|
|
47
56
|
with ranges from rules. An overlap or gap outside its range is a finding: report it with the numbers, and never
|
|
48
57
|
widen a range to make it pass without saying why.
|
|
49
58
|
- Build bigger things from checked assemblies used as items, rather than placing their objects again.
|
|
59
|
+
- Things that move are one assembly with joints and poses, not a copy per position: give the objects anchors, join
|
|
60
|
+
them with joints, name the positions in `poses`, and run `cad check --sweep` to find where parts collide on the way.
|
|
61
|
+
See "Joints and poses" in the cad README.
|
|
50
62
|
- A part is named in fits as `<item>.<part>`; an object that returns one unnamed shape has one part, `body`.
|
|
51
63
|
- A gap fit can't tell whether holes line up. Where a board screws into a part, add a holes fit
|
|
52
64
|
(`{ "holes": "pcb.board", "into": "case.body", "depth": "m2.insert_length" }`).
|
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
|
|
@@ -181,6 +183,31 @@ out. `--part cap` works on one part; `cad preview --explode` moves the parts apa
|
|
|
181
183
|
- The print check treats parts that print together as one print: an underside resting on another part (a legend on its
|
|
182
184
|
cap) isn't an overhang, and each part must be a closed solid on its own.
|
|
183
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
|
+
|
|
184
211
|
## Assemblies
|
|
185
212
|
|
|
186
213
|
`projects/<project>/assemblies/<name>.json` places objects together. Positions are expressions over rules and the
|
|
@@ -227,6 +254,62 @@ other items' variables, so a keycap can sit exactly where its slot meets the swi
|
|
|
227
254
|
- `check`, `preview` (`--explode` lifts each kind of object above the last: plate, switches, keycaps), `show`, `link` and, for plates, `export` all take
|
|
228
255
|
`<project>/<assembly>`.
|
|
229
256
|
|
|
257
|
+
### Joints and poses
|
|
258
|
+
|
|
259
|
+
Things that move (a lid, a hinged screen, a drawer, a ball head) are one assembly with joints, not one assembly per
|
|
260
|
+
position. An object names its **anchors** in its .json, as expressions over its own variables: a point, with an axis.
|
|
261
|
+
|
|
262
|
+
```json
|
|
263
|
+
"anchors": { "pivot": { "at": ["width / 2", 0, "height"], "axis": [1, 0, 0] } }
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
A **joint** ties an anchor on its child item to one on its parent item. At value 0 the two anchors lie together, and
|
|
267
|
+
the joint's value moves the child from there. A joint's child has no `at` or `rotate`: the joint places it.
|
|
268
|
+
|
|
269
|
+
```json
|
|
270
|
+
"joints": [
|
|
271
|
+
{ "id": "lid", "type": "revolute", "parent": "case.pivot", "child": "lid.pivot", "min": -180, "max": 0, "label": "Lid" },
|
|
272
|
+
{ "id": "lid_r", "type": "revolute", "parent": "case.pivot_r", "child": "stay.pivot", "follow": "lid" }
|
|
273
|
+
],
|
|
274
|
+
"poses": { "shut": { "lid": 0 }, "open": { "lid": -110 } }
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
| Type | Values | For |
|
|
278
|
+
|---|---|---|
|
|
279
|
+
| `fixed` | none | a part bolted on in a set place |
|
|
280
|
+
| `revolute` | angle | hinges, pivots |
|
|
281
|
+
| `prismatic` | distance | straight rails, drawers |
|
|
282
|
+
| `cylindrical` | `[angle, distance]` | a pin that turns and slides in a slot |
|
|
283
|
+
| `ball` | `[x, y, z]` angles | ball joints; `"cone": 30` limits how far the child's axis may tip |
|
|
284
|
+
| `path` | distance | curved rails: `"path": [[x, y, z], …]`, a polyline in the parent anchor's frame, the child's axis along it |
|
|
285
|
+
|
|
286
|
+
Angles are in degrees about the anchor's z axis (its `axis`); distances are in mm along it. A `ball` turns about x,
|
|
287
|
+
then y, then z, as `rotate` does.
|
|
288
|
+
|
|
289
|
+
- **Anchors:** `<item>.<anchor>`, or `<item>.<component item>.<anchor>` inside a component. An anchor can also be
|
|
290
|
+
written in place, in the assembly's names: `{ "item": "case", "at": ["case.width", 0, 0], "axis": [0, 1, 0] }`.
|
|
291
|
+
Without an `item` it is in the world. `ref` sets which way the anchor's x axis points (what angle 0 means), or
|
|
292
|
+
`rotate` turns the anchor as `rotate` turns an item.
|
|
293
|
+
- **Limits:** `min`, `max` and `value` (the default) are numbers or expressions, one per value (`[…]` for two or
|
|
294
|
+
three). An angle with no limits goes from -180 to 180. A distance needs both limits, except on a path, which runs
|
|
295
|
+
from 0 to its length.
|
|
296
|
+
- **Followers:** `"follow": "lid"` gives a joint another joint's values, times `ratio` (default 1), plus `offset`. Use
|
|
297
|
+
it for the second hinge of a pair, or for gears.
|
|
298
|
+
- **Loops:** each item has one joint to its parent. Where parts join in a ring (two links between the same two
|
|
299
|
+
parts), let joints place every part, then name the meeting that closes the ring in `loops`. The check measures it
|
|
300
|
+
in every pose: `"loops": [{ "a": "link_l.top", "b": "mount_l.axis", "label": "Left pivot lines up" }]`. Its anchors
|
|
301
|
+
must meet within 0.01 mm (or `tolerance`), with their axes lined up.
|
|
302
|
+
- **Poses:** `"poses"` names sets of values. `"pose"` names the one that previews, links and the display show (by
|
|
303
|
+
default, the first). `cad check` checks every pose. What is the same in every pose is reported once; the rest is
|
|
304
|
+
reported under the pose's name. `--pose open` checks, previews, shows or links one pose. A fit that only makes
|
|
305
|
+
sense in some poses names them: `"poses": ["folded"]`.
|
|
306
|
+
- **Sweeps:** `cad check <project>/<assembly> --sweep` moves each joint that doesn't follow another through its
|
|
307
|
+
range (`--steps 24`, from the pose, the other joints held still). It names where parts collide or a loop comes
|
|
308
|
+
apart: "sweep lid, -180 to 0° in 24 steps: -180 to -165°: lid.body hits hinge.pin". `--sweep lid` sweeps one joint.
|
|
309
|
+
- **Links:** an assembly's link carries its joints. The page shows a slider for each joint, a button for each pose,
|
|
310
|
+
and a quick look for parts pushed into each other when you let a slider go. The quick look can miss parts that cross
|
|
311
|
+
without a corner going in, so `--sweep` is the real check.
|
|
312
|
+
|
|
230
313
|
## Boards
|
|
231
314
|
|
|
232
315
|
A circuit board is an object whose .json says `"engine": "pcb"`. Its `main(v)` returns a
|
package/bin/cad.mjs
CHANGED
|
@@ -11,7 +11,8 @@ 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 {
|
|
14
|
+
import { measure, match } from '../lib/meshcmd.mjs';
|
|
15
|
+
import { isAssembly, buildAssembly, checkAssembly, shapes, sweep } 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';
|
|
17
18
|
|
|
@@ -52,6 +53,9 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
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]
|
|
54
55
|
[--no-rules: leave out the Rules panel's list of values and their sources]
|
|
56
|
+
Assemblies with joints: check checks every pose; --pose <name> picks one (check, preview, show, link)
|
|
57
|
+
[--sweep [joint]: move each joint (or one) through its range, looking for collisions]
|
|
58
|
+
[--steps 24: how many steps a sweep takes]
|
|
55
59
|
|
|
56
60
|
cad status [project] each object's version, and whether it has changes since its last release
|
|
57
61
|
cad release <project>/<object> -m "what changed" [--bump major|minor|patch] [--dry-run] [--push]
|
|
@@ -62,6 +66,16 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
62
66
|
cad printed <project>/<object> --result ok|failed [--note "…"] [--material PETG] [--version 0.1.0]
|
|
63
67
|
cad release <project> --all -m "…" release every object that changed (each with this message), then the project
|
|
64
68
|
|
|
69
|
+
cad measure <model.stl|3mf> a model from elsewhere, measured: size, the stretches along its length with the same
|
|
70
|
+
cross-section, and each section's shape, with a drawing in .preview/measure/
|
|
71
|
+
[--along x|y|z] [--at 10,50: sections there too] [--line 0.6,2.5;4.6,2.5: where lines
|
|
72
|
+
along it are inside] [--rules <name> --source <url> --licence "…": draft rules]
|
|
73
|
+
cad match <project>/<object> <model.stl|3mf> how closely the design matches a model: both ways, signed, with the
|
|
74
|
+
worst places and sections through them [--tol 0.2 (default: the printer's fit)]
|
|
75
|
+
[--place "rz90 t1,2,3": how to lay the model over the design, else it is fitted]
|
|
76
|
+
[--at 10,50: sections there too] [--samples 20000]
|
|
77
|
+
--no-pictures measure, match: the report only, no drawings (no Chrome needed)
|
|
78
|
+
|
|
65
79
|
cad variants <project>/<object> the object's variants: named sets of inputs, built as <project>/<object>:<variant>
|
|
66
80
|
cad compare <project>/<object> <a> <b> two variants (or releases, 1.2.0) side by side in one preview
|
|
67
81
|
|
|
@@ -127,6 +141,11 @@ async function main() {
|
|
|
127
141
|
return;
|
|
128
142
|
}
|
|
129
143
|
if (cmd === 'status') return status(ref);
|
|
144
|
+
if (cmd === 'measure') {
|
|
145
|
+
if (!ref) throw new Error('usage: cad measure <model.stl|model.3mf> [--along x] [--at 10,50] [--line 0.6,2.5] [--rules <name>]');
|
|
146
|
+
const list = (k) => (opt(k) && opt(k) !== true ? String(opt(k)).split(k === 'line' ? ';' : ',').filter(Boolean) : []);
|
|
147
|
+
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') });
|
|
148
|
+
}
|
|
130
149
|
if (!ref) throw new Error(`usage: cad ${cmd} <project>/<object>`);
|
|
131
150
|
if (cmd === 'release') return ref.includes('/') ? releaseObject(locate(ref)) : opt('all') ? releaseAll(ref) : releaseProject(ref);
|
|
132
151
|
if (cmd === 'variants') return variants(locate(ref));
|
|
@@ -143,6 +162,15 @@ async function main() {
|
|
|
143
162
|
|
|
144
163
|
if (b.circuit && ['check', 'preview', 'export'].includes(cmd)) return board(cmd, d, b, { title, version, tag });
|
|
145
164
|
|
|
165
|
+
if (cmd === 'match') {
|
|
166
|
+
const file = args[2];
|
|
167
|
+
if (!file || file.startsWith('--')) throw new Error(`usage: cad match ${ref} <model.stl|model.3mf> [--tol 0.2] [--place "rz90 t1,2,3"]`);
|
|
168
|
+
const tol = opt('tol') ? Number(opt('tol')) : printer(b, d).fit ?? 0.2;
|
|
169
|
+
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') });
|
|
170
|
+
process.exitCode = ok ? 0 : 1;
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
|
|
146
174
|
if (cmd === 'rules') {
|
|
147
175
|
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)' : ''}`);
|
|
148
176
|
return;
|
|
@@ -235,20 +263,28 @@ async function board(cmd, d, b, { title, version, tag }) {
|
|
|
235
263
|
|
|
236
264
|
// ---------- assemblies ----------
|
|
237
265
|
async function assembly(cmd, ref) {
|
|
238
|
-
const
|
|
266
|
+
const pose = typeof opt('pose') === 'string' ? opt('pose') : undefined;
|
|
267
|
+
const s = await buildAssembly(ref, [], {}, { pose }), a = s.a, title = `${a.title || s.name}${pose ? ` (${pose})` : ''}`;
|
|
239
268
|
const versions = [...new Map(s.objects.map((o) => [o.objName, `${o.objName} ${o.version}`])).values()].join(', ');
|
|
240
269
|
const rules = (ns) => Object.fromEntries(Object.keys(loadRuleSet(ns).rules).map((k) => [k, s.num(`${ns}.${k}`)]));
|
|
241
270
|
const printed = s.parts.filter((p) => p.role !== 'reference');
|
|
242
271
|
|
|
243
272
|
if (cmd === 'check') {
|
|
244
273
|
console.log(`${title} (${a.kind || 'fit'}: ${versions})`);
|
|
245
|
-
|
|
274
|
+
// Each pose (or the one asked for): what's the same in every pose is said once, the rest under the pose's name
|
|
275
|
+
const poses = pose ? [pose] : Object.keys(s.motion.poses);
|
|
276
|
+
let findings = checkAssembly(s);
|
|
277
|
+
if (poses.length > 1) {
|
|
278
|
+
const each = poses.map((p) => [p, checkAssembly(s.at(p))]), same = (x) => each.every(([, list]) => list.some((y) => y.text === x.text && y.level === x.level));
|
|
279
|
+
findings = [{ level: 'pass', text: `${poses.length} poses checked: ${poses.join(', ')}` }, ...each[0][1].filter(same), ...each.flatMap(([p, list]) => list.filter((x) => !same(x)).map((x) => ({ ...x, text: `${p}: ${x.text}`, ...(x.card ? { card: `${p}: ${x.card}` } : {}) })))];
|
|
280
|
+
}
|
|
281
|
+
if (opt('sweep')) findings.push(...sweep(s, { joint: typeof opt('sweep') === 'string' ? opt('sweep') : undefined, steps: Number(opt('steps')) || 24 }));
|
|
246
282
|
if (a.kind === 'plate') findings.push(...check(printed.flatMap((p) => p.triangles), rules(printerOf(s.project)), { parts: printed }));
|
|
247
283
|
process.exitCode = report(findings) ? 1 : 0;
|
|
248
284
|
return;
|
|
249
285
|
}
|
|
250
286
|
if (cmd === 'preview') {
|
|
251
|
-
const out = paths.preview(s.project, `${s.name}${opt('explode') ? '-exploded' : ''}.png`);
|
|
287
|
+
const out = paths.preview(s.project, `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}.png`);
|
|
252
288
|
const size = (await import('@rulecad/printcheck')).bounds(s.triangles).size.map((n) => fmt(n)).join(' × ');
|
|
253
289
|
const faint = [...new Set(s.parts.filter((p) => p.role !== 'part').map((p) => `${p.object || p.item}${p.role === 'support' ? ' supports' : ''}`))]; // each kind once
|
|
254
290
|
await preview(s.parts, { title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode') });
|
|
@@ -286,6 +322,7 @@ async function assembly(cmd, ref) {
|
|
|
286
322
|
return placed.place.map(([i, ...m], n) => { const p = placed.shapes[i].part; return { shape: i, role: p.role, label: p.object || p.label, slot: slotOf(fil, p.filament), triangles: tri(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; });
|
|
287
323
|
})() : []),
|
|
288
324
|
};
|
|
325
|
+
Object.assign(model, motionLink(s));
|
|
289
326
|
const url = await linkTo(model);
|
|
290
327
|
return { view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, src: model.src, size: url.length, title, version: '' };
|
|
291
328
|
};
|
|
@@ -293,7 +330,7 @@ async function assembly(cmd, ref) {
|
|
|
293
330
|
if (cmd === 'show') {
|
|
294
331
|
// Each shape once, placed for every copy: nine keys cost one keycap in the mirror's link. Built with each object's
|
|
295
332
|
// mirror settings (fewer segments), so the display gets a lighter mesh; checks and links use the real one
|
|
296
|
-
const m = await buildAssembly(ref, [], {}, { mirror: true });
|
|
333
|
+
const m = await buildAssembly(ref, [], {}, { mirror: true, pose });
|
|
297
334
|
const placed = shapes(m.parts.filter((p) => p.role !== 'support' && p.mirror !== false));
|
|
298
335
|
// The card: what the checks found, one short line each
|
|
299
336
|
const items = checkAssembly(s).filter((x) => x.card).slice(0, 6).map((x) => x.card);
|
|
@@ -304,6 +341,26 @@ async function assembly(cmd, ref) {
|
|
|
304
341
|
throw new Error(`cad ${cmd} doesn't work on an assembly (check, preview, export, show, link do)`);
|
|
305
342
|
}
|
|
306
343
|
|
|
344
|
+
// An assembly's joints, for the page's sliders: each part moves with its item (motion in @rulecad/model-link)
|
|
345
|
+
function motionLink(s) {
|
|
346
|
+
const mo = s.motion;
|
|
347
|
+
if (!mo.joints.length) return {};
|
|
348
|
+
const r = (x) => Number(x.toFixed(6)), names = mo.items.map((x) => x[0]);
|
|
349
|
+
const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`), allow = [];
|
|
350
|
+
const loose = s.fits.filter((x) => x.min != null && x.num(x.min) < 0);
|
|
351
|
+
s.parts.forEach((pa, i) => s.parts.forEach((pb, j) => {
|
|
352
|
+
if (j > i && pa.item !== pb.item && loose.some((x) => (named(pa, x.a) && named(pb, x.b)) || (named(pa, x.b) && named(pb, x.a)))) allow.push([i, j]);
|
|
353
|
+
}));
|
|
354
|
+
return { motion: {
|
|
355
|
+
items: mo.items.map(([n, ...m]) => [n, ...m.map(r)]),
|
|
356
|
+
joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone }) => ({ id, type, parent, child, a: a.map(r), b: b.map(r), dofs: dofs.map((d) => d.map(r)),
|
|
357
|
+
...(label ? { label } : {}), ...(follow ? { follow } : {}), ...(path ? { path: path.map((p) => p.map(r)) } : {}), ...(cone != null ? { cone } : {}) })),
|
|
358
|
+
poses: mo.poses, ...(s.pose ? { pose: s.pose } : {}),
|
|
359
|
+
part: s.parts.map((p) => names.indexOf(p.item)),
|
|
360
|
+
...(allow.length ? { allow } : {}),
|
|
361
|
+
} };
|
|
362
|
+
}
|
|
363
|
+
|
|
307
364
|
// ---------- links ----------
|
|
308
365
|
// 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
|
|
309
366
|
// they use, as [group, name, value, unit, rule, expr, kind, source, checked] (group: the object, or the rule's set).
|
package/lib/assembly.mjs
CHANGED
|
@@ -27,6 +27,7 @@ import { satisfies } from '@rulecad/versions';
|
|
|
27
27
|
import { bounds } from '@rulecad/printcheck';
|
|
28
28
|
import { closest, inside } from '@rulecad/fit';
|
|
29
29
|
import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
|
|
30
|
+
import { DOFS, frame, turn, mul, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
|
|
30
31
|
|
|
31
32
|
export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
|
|
32
33
|
export const isAssembly = (ref) => String(ref).includes('/') && fs.existsSync(assemblyPath(ref.split('@')[0]));
|
|
@@ -143,46 +144,61 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
143
144
|
placing.push([it, copies]);
|
|
144
145
|
}
|
|
145
146
|
// Then place them: every item is built by now, so a position can refer to any item, before or after it (a board
|
|
146
|
-
// placed under the case's top, the case built with the board's Pico position)
|
|
147
|
+
// placed under the case's top, the case built with the board's Pico position). Each copy is an item of the motion:
|
|
148
|
+
// placed by at and rotate, or by the joint whose child it is.
|
|
149
|
+
const placed = []; // [it, copy], each a motion item, in order
|
|
147
150
|
for (const [it, copies] of placing) {
|
|
148
151
|
if (it.place === false) { // built only for its values ("place": false): a board a print plate's case is sized from
|
|
149
152
|
for (const c of copies) if (!c.src.sub) objects.push({ id: c.id, objName: c.src.objName, version: c.src.version, built: c.src.b, role: c.src.role, unplaced: true });
|
|
150
153
|
continue;
|
|
151
154
|
}
|
|
152
|
-
for (const c of copies) {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
155
|
+
for (const c of copies) { placed.push([it, c]); ids.push(c.id); }
|
|
156
|
+
}
|
|
157
|
+
const motion = motionOf(a, placed, num, ref);
|
|
158
|
+
for (const [it, c] of placed) {
|
|
159
|
+
const src = c.src, id = c.id;
|
|
160
|
+
if (src.sub) {
|
|
161
|
+
const sub = src.sub;
|
|
162
|
+
for (const o of sub.objects) objects.push({ ...o, id: `${id}.${o.id}` });
|
|
163
|
+
for (const x of sub.fits) fits.push({ ...x, a: `${id}.${x.a}`, b: `${id}.${x.b}`, label: x.label && `${x.label} (${id})` });
|
|
164
|
+
requires.push(...sub.requires);
|
|
165
|
+
for (const n of sub.seen) seen.add(n);
|
|
166
|
+
items.push({ ...it, id, sub, role: 'part' });
|
|
167
|
+
} else {
|
|
168
|
+
objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role });
|
|
169
|
+
items.push({ ...it, id, objName: src.objName, built: src.b, version: src.version, role: src.role });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
// Every part, with its item where the joints put it at these values (jointValues)
|
|
173
|
+
const partsAt = (worlds) => {
|
|
174
|
+
const out = [];
|
|
175
|
+
placed.forEach(([, c], k) => {
|
|
176
|
+
const src = c.src, id = c.id, key = src.key, m = toMat4(worlds[k]);
|
|
177
|
+
items[k].m = m;
|
|
156
178
|
// Faces are moved as they are, not re-triangulated in place: triangulating again after a move rounds differently
|
|
157
|
-
const m = translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms;
|
|
158
179
|
const move = (polys) => polys.map((poly) => poly.map((v) => jscad.maths.vec3.transform([0, 0, 0], v, m)));
|
|
159
|
-
ids.push(id);
|
|
160
180
|
if (src.sub) {
|
|
161
|
-
const
|
|
162
|
-
for (const p of sub.parts) {
|
|
181
|
+
for (const p of src.sub.parts) {
|
|
163
182
|
if (p.role === 'support' && a.kind !== 'plate') continue;
|
|
164
|
-
|
|
183
|
+
out.push({ ...p, name: `${id}.${p.name}`, item: id, leaf: `${id}.${p.leaf}`, label: `${id} ${p.label}`,
|
|
165
184
|
geometry: transform(m, p.geometry), polygons: move(p.polygons), triangles: move(p.triangles), m: jscad.maths.mat4.multiply(jscad.maths.mat4.create(), m, p.m) });
|
|
166
185
|
}
|
|
167
|
-
for (const o of sub.objects) objects.push({ ...o, id: `${id}.${o.id}` });
|
|
168
|
-
for (const x of sub.fits) fits.push({ ...x, a: `${id}.${x.a}`, b: `${id}.${x.b}`, label: x.label && `${x.label} (${id})` });
|
|
169
|
-
requires.push(...sub.requires);
|
|
170
|
-
for (const n of sub.seen) seen.add(n);
|
|
171
|
-
items.push({ ...it, id, sub, role: 'part' });
|
|
172
186
|
} else {
|
|
173
|
-
const
|
|
174
|
-
for (const p of b.parts) {
|
|
187
|
+
for (const p of src.b.parts) {
|
|
175
188
|
if (p.role === 'support' && a.kind !== 'plate') continue; // supports are snipped off before parts go together
|
|
176
|
-
|
|
189
|
+
out.push({ name: `${id}.${p.name}`, item: id, leaf: id, object: src.objName, role: src.role === 'reference' ? 'reference' : p.role, label: `${id}: ${p.label}`,
|
|
177
190
|
...(p.filament ? { filament: p.filament } : {}), ...(p.mirror === false ? { mirror: false } : {}), part: p.name,
|
|
178
191
|
geometry: transform(m, p.geometry), polygons: move(p.polygons), triangles: move(p.triangles),
|
|
179
|
-
shape: `${key}:${p.name}`, hash: `${b.hash}:${p.name}`, local: p.polygons, localTriangles: p.triangles, m });
|
|
192
|
+
shape: `${key}:${p.name}`, hash: `${src.b.hash}:${p.name}`, local: p.polygons, localTriangles: p.triangles, m });
|
|
180
193
|
}
|
|
181
|
-
objects.push({ id, objName: src.objName, version: src.version, built: b, role: src.role });
|
|
182
|
-
items.push({ ...it, id, objName: src.objName, built: b, version: src.version, role: src.role });
|
|
183
194
|
}
|
|
184
|
-
}
|
|
185
|
-
|
|
195
|
+
});
|
|
196
|
+
return out;
|
|
197
|
+
};
|
|
198
|
+
for (const x of a.fits || []) for (const p of x.poses || []) if (!motion.poses[p]) throw new Error(`fit ${x.note || x.label || `${x.a} / ${x.b}`}: no pose "${p}" (poses: ${Object.keys(motion.poses).join(', ') || 'none'})`);
|
|
199
|
+
const pose = opts.pose ?? motion.pose;
|
|
200
|
+
const jv = jointValues(motion, pose);
|
|
201
|
+
parts.push(...partsAt(placeItems(motion, jv)));
|
|
186
202
|
// A fit with * applies to every copy: "key-*.switch.bottom" becomes one fit for key-0-0, key-0-1, …
|
|
187
203
|
// With * on both sides, each copy is checked against all the others: { "a": "key-*.cap", "b": "key-*.cap" }
|
|
188
204
|
for (let x of a.fits || []) {
|
|
@@ -199,8 +215,115 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
199
215
|
}
|
|
200
216
|
for (const id of copies) { const swap = (n) => (n === star ? at(id, n) : n); fits.push({ ...x, a: swap(x.a), b: swap(x.b), num }); }
|
|
201
217
|
}
|
|
202
|
-
|
|
218
|
+
// at(pose): the same assembly in another pose (a name, or { joint: values }), nothing built again
|
|
219
|
+
const at = (p) => {
|
|
220
|
+
const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
|
|
221
|
+
return { ...s, parts: moved, pose: typeof p === 'string' ? p : null, jointValues: v, polygons: moved.flatMap((x) => x.polygons), triangles: moved.flatMap((x) => x.triangles) };
|
|
222
|
+
};
|
|
223
|
+
const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
|
|
203
224
|
polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
|
|
225
|
+
return s;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// ---------- joints ----------
|
|
229
|
+
// "joints" move items against each other: a joint ties an anchor on its child item to one on its parent, and its
|
|
230
|
+
// values (an angle, a distance) move the child from there. A joint's child has no at or rotate: the joint places it.
|
|
231
|
+
// "joints": [{ "id": "hinge", "type": "revolute", "parent": "case.pivot", "child": "lid.pivot", "min": 0, "max": 180,
|
|
232
|
+
// "value": 90, "label": "Lid" }]
|
|
233
|
+
// Anchors are named in the object's .json ("anchors": { "pivot": { "at": ["width / 2", 0, "h"], "axis": [1, 0, 0] } },
|
|
234
|
+
// expressions over its own variables) and found as <item>.<anchor>, or <item>.<component item>.<anchor> into a
|
|
235
|
+
// component. Or written in place, in the assembly's names: { "item": "case", "at": […], "axis": […] } (no item: the
|
|
236
|
+
// world). An anchor is a point with axes: z along axis, x towards ref (optional), or turned by rotate as items are.
|
|
237
|
+
// At value 0 the two anchors lie together. Types, and what they take (angles in degrees, distances in mm, on z):
|
|
238
|
+
// fixed; revolute (angle); prismatic (distance: a straight rail); cylindrical ([angle, distance]: a pin in a slot);
|
|
239
|
+
// ball ([x, y, z] turns; "cone": how far z may tip); path (distance along "path": [[x, y, z], …], a polyline in the
|
|
240
|
+
// parent anchor's frame: a curved rail, the child's z along it).
|
|
241
|
+
// min, max and value are numbers or expressions, one per value ([…] for two or three). "follow": "hinge" gives a joint
|
|
242
|
+
// another's values (times "ratio", plus "offset"): the second hinge of a pair, gears. Items joined in a ring (two links
|
|
243
|
+
// between the same two parts) can't all be joints: join the ring's last pair with "loops" instead, which the check
|
|
244
|
+
// measures in every pose: [{ "a": "link_l.top", "b": "mount_l.axis", "label": "Left pivot lines up" }].
|
|
245
|
+
// "poses": { "open": { "hinge": 90 } } names sets of values, "pose" the one shown (default: the first); check checks
|
|
246
|
+
// every pose, and --sweep moves each joint through its range, looking for parts that collide.
|
|
247
|
+
const rows = (m) => [m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14]]; // JSCAD's mat4 is column-major
|
|
248
|
+
const toMat4 = (r) => [r[0], r[4], r[8], 0, r[1], r[5], r[9], 0, r[2], r[6], r[10], 0, r[3], r[7], r[11], 1];
|
|
249
|
+
export const LIMITS = { angle: [-180, 180] };
|
|
250
|
+
function motionOf(a, placed, num, ref) {
|
|
251
|
+
const { translate, rotate } = jscad.transforms, deg = Math.PI / 180;
|
|
252
|
+
const index = new Map(placed.map(([, c], k) => [c.id, k]));
|
|
253
|
+
const where = (n, what) => { if (!index.has(n)) throw new Error(`${what}: no item "${n}" (items: ${[...index.keys()].join(', ')})`); return index.get(n); };
|
|
254
|
+
const evalIn = (values, label) => (x) => evaluate(x, (n) => {
|
|
255
|
+
let v = values;
|
|
256
|
+
for (const k of n.split('.')) v = v?.[k];
|
|
257
|
+
if (typeof v !== 'number') throw new Error(`${label}: "${n}" isn't one of its numbers`);
|
|
258
|
+
return v;
|
|
259
|
+
});
|
|
260
|
+
const frameOf = (spec, ev) => {
|
|
261
|
+
const at = (spec.at || [0, 0, 0]).map(ev);
|
|
262
|
+
if (spec.rotate) { const m = turn(spec.rotate.map(ev)); m[3] = at[0]; m[7] = at[1]; m[11] = at[2]; return m; }
|
|
263
|
+
return frame(at, (spec.axis || [0, 0, 1]).map(ev), spec.ref && spec.ref.map(ev));
|
|
264
|
+
};
|
|
265
|
+
// An anchor: { item (index, -1 the world), frame (12 numbers, in the item's own frame) }
|
|
266
|
+
const anchor = (spec, what) => {
|
|
267
|
+
if (spec && typeof spec === 'object') return { item: spec.item ? where(spec.item, what) : -1, frame: frameOf(spec, num) };
|
|
268
|
+
const bits = String(spec).split('.'), name = bits.pop(), [id, ...inside] = bits;
|
|
269
|
+
if (!id || !name) throw new Error(`${what}: name an anchor as <item>.<anchor> (got "${spec}")`);
|
|
270
|
+
const k = where(id, what);
|
|
271
|
+
let src = placed[k][1].src, pre = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
|
|
272
|
+
for (const n of inside) { // into a component: its item's place there
|
|
273
|
+
const sub = src.sub?.items.find((x) => x.id === n);
|
|
274
|
+
if (!sub) throw new Error(`${what}: ${id} has no item "${n}"`);
|
|
275
|
+
pre = mul(pre, rows(sub.m));
|
|
276
|
+
src = sub.sub ? { sub: sub.sub } : { b: sub.built, objName: sub.objName };
|
|
277
|
+
}
|
|
278
|
+
const anchors = src.b?.object.anchors || {};
|
|
279
|
+
if (!anchors[name]) throw new Error(`${what}: ${src.objName || id} has no anchor "${name}" (anchors: ${Object.keys(anchors).join(', ') || 'none'})`);
|
|
280
|
+
return { item: k, frame: mul(pre, frameOf(anchors[name], evalIn(src.b.values, `${src.objName} anchor ${name}`))) };
|
|
281
|
+
};
|
|
282
|
+
const joints = [], children = new Set();
|
|
283
|
+
for (const j of a.joints || []) {
|
|
284
|
+
const what = `joint ${j.id}`;
|
|
285
|
+
if (!/^[a-z][\w-]*$/.test(j.id || '')) throw new Error(`each joint needs an id (letters, digits, - or _): got ${JSON.stringify(j.id)}`);
|
|
286
|
+
if (!Object.hasOwn(DOFS, j.type)) throw new Error(`${what}: type is one of ${Object.keys(DOFS).join(', ')} (got ${JSON.stringify(j.type)})`);
|
|
287
|
+
const p = j.parent == null ? { item: -1, frame: frame([0, 0, 0]) } : anchor(j.parent, what), c = anchor(j.child, what);
|
|
288
|
+
if (c.item < 0) throw new Error(`${what}: its child must be an item`);
|
|
289
|
+
if (children.has(c.item)) throw new Error(`${what}: ${placed[c.item][1].id} is already placed by another joint (two joints to one item make a ring: use loops)`);
|
|
290
|
+
const [it] = placed[c.item];
|
|
291
|
+
if (it.at || it.rotate || it.repeat) throw new Error(`${what}: ${it.id} is placed by the joint, so it can't have at, rotate or repeat`);
|
|
292
|
+
children.add(c.item);
|
|
293
|
+
const path = j.type === 'path' ? (j.path || []).map((pt) => pt.map(num)) : undefined;
|
|
294
|
+
if (path && path.length < 2) throw new Error(`${what}: a path joint needs "path": two points or more`);
|
|
295
|
+
const kinds = DOFS[j.type], list = (x) => (x == null ? [] : [].concat(x));
|
|
296
|
+
const lo = list(j.min), hi = list(j.max), val = list(j.value);
|
|
297
|
+
const dofs = kinds.map((kind, i) => {
|
|
298
|
+
const range = j.type === 'path' ? [0, pathLength(path)] : kind === 'angle' ? LIMITS.angle : null;
|
|
299
|
+
const mn = lo[i] != null ? num(lo[i]) : range?.[0], mx = hi[i] != null ? num(hi[i]) : range?.[1];
|
|
300
|
+
if (mn == null || mx == null) throw new Error(`${what}: give its ${kind} a min and max`);
|
|
301
|
+
if (mn > mx) throw new Error(`${what}: min ${mn} is above max ${mx}`);
|
|
302
|
+
return [mn, mx, val[i] != null ? num(val[i]) : Math.min(mx, Math.max(mn, 0))];
|
|
303
|
+
});
|
|
304
|
+
joints.push({ id: j.id, type: j.type, parent: p.item, child: c.item, a: p.frame, b: c.frame, dofs,
|
|
305
|
+
...(j.label ? { label: j.label } : {}), ...(path ? { path } : {}), ...(j.cone != null ? { cone: num(j.cone) } : {}),
|
|
306
|
+
...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}) });
|
|
307
|
+
}
|
|
308
|
+
for (const j of joints) if (j.follow) {
|
|
309
|
+
const l = joints.find((x) => x.id === j.follow[0]);
|
|
310
|
+
if (!l) throw new Error(`joint ${j.id}: follows "${j.follow[0]}", which isn't a joint (${joints.map((x) => x.id).join(', ')})`);
|
|
311
|
+
if (l.dofs.length !== j.dofs.length) throw new Error(`joint ${j.id} (${j.type}) takes ${j.dofs.length} values, but follows ${l.id} (${l.type}), which takes ${l.dofs.length}`);
|
|
312
|
+
}
|
|
313
|
+
const items = placed.map(([it, c], k) => {
|
|
314
|
+
if (children.has(k)) return [c.id];
|
|
315
|
+
const base = (it.at || [0, 0, 0]).map(num), rot = (it.rotate || [0, 0, 0]).map((r) => num(r) * deg);
|
|
316
|
+
// A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
|
|
317
|
+
return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
|
|
318
|
+
});
|
|
319
|
+
const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).map(([id, v]) => {
|
|
320
|
+
if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
|
|
321
|
+
return [id, Array.isArray(v) ? v.map(num) : num(v)];
|
|
322
|
+
}))]));
|
|
323
|
+
if (a.pose && !poses[a.pose]) throw new Error(`pose "${a.pose}" isn't one of the poses (${Object.keys(poses).join(', ') || 'none'})`);
|
|
324
|
+
const loops = (a.loops || []).map((l, i) => ({ label: l.label || `${typeof l.a === 'string' ? l.a : 'anchor'} meets ${typeof l.b === 'string' ? l.b : 'anchor'}`,
|
|
325
|
+
a: anchor(l.a, `loop ${i + 1}`), b: anchor(l.b, `loop ${i + 1}`), tolerance: l.tolerance != null ? num(l.tolerance) : 0.01 }));
|
|
326
|
+
return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref };
|
|
204
327
|
}
|
|
205
328
|
|
|
206
329
|
// keyCentres(layout): each key's centre, from lib/layout.mjs (kept under this name for older callers)
|
|
@@ -263,6 +386,7 @@ export function checkAssembly(s) {
|
|
|
263
386
|
const pick = (n) => (Array.isArray(n) ? n.flatMap(pick) : s.parts.filter((p) => named(p, n)));
|
|
264
387
|
const groups = new Map();
|
|
265
388
|
for (const x of s.fits) {
|
|
389
|
+
if (x.poses && !x.poses.includes(s.pose)) continue; // a fit for some poses only: the folded screen over the keys
|
|
266
390
|
if (x.holes) { holesFit(x); continue; }
|
|
267
391
|
const A = pick(x.a), key = x.note || `${x.a} / ${x.b}`;
|
|
268
392
|
const lo = x.min != null ? x.num(x.min) : -Infinity, hi = x.max != null ? x.num(x.max) : Infinity;
|
|
@@ -308,6 +432,17 @@ export function checkAssembly(s) {
|
|
|
308
432
|
f(misses.length ? 'fail' : 'pass', misses.length ? `${label}: ${misses.join('; ')}` : `${label}: ${holes.length} of ${holes.length} holes clear for ${mm(depth)} mm, with material around each`,
|
|
309
433
|
`${label}: ${misses.length ? `${misses.length} of ${holes.length} miss` : `${holes.length} of ${holes.length} line up`}`);
|
|
310
434
|
}
|
|
435
|
+
// Joints: every value in its range (a ball's tip within its cone), and every loop closed
|
|
436
|
+
if (s.motion?.joints.length) {
|
|
437
|
+
const outside = [];
|
|
438
|
+
for (const j of s.motion.joints) {
|
|
439
|
+
const v = s.jointValues[j.id];
|
|
440
|
+
j.dofs.forEach(([lo, hi], i) => { if (v[i] < lo - 1e-9 || v[i] > hi + 1e-9) outside.push(`${j.id} ${mm(v[i])} (${mm(lo)} to ${mm(hi)})`); });
|
|
441
|
+
if (j.cone != null) { const tip = Math.acos(Math.min(1, jointMatrix(j, v)[10])) / (Math.PI / 180); if (tip > j.cone + 1e-9) outside.push(`${j.id} tips ${mm(tip)}° (cone ${mm(j.cone)}°)`); }
|
|
442
|
+
}
|
|
443
|
+
if (outside.length) f('fail', `joints out of range: ${outside.join(', ')}`, `${outside.length} joints out of range`);
|
|
444
|
+
for (const l of loopGaps(s)) f(l.ok ? 'pass' : 'fail', `${l.label}: ${l.ok ? 'closed' : 'apart'} (${mm(l.gap)} mm, axes ${mm(l.angle)}° apart)`, `${l.label}: ${l.ok ? 'closed' : 'apart'}`);
|
|
445
|
+
}
|
|
311
446
|
// Plates print everything: no references
|
|
312
447
|
if (s.a.kind === 'plate') {
|
|
313
448
|
const refs = s.objects.filter((o) => o.role === 'reference' && !o.unplaced); // an unplaced item only lends its numbers
|
|
@@ -322,6 +457,58 @@ export function checkAssembly(s) {
|
|
|
322
457
|
return out;
|
|
323
458
|
}
|
|
324
459
|
|
|
460
|
+
// Each loop at the assembly's pose: how far apart its two anchors are (mm), and their axes (degrees, either way round)
|
|
461
|
+
export function loopGaps(s) {
|
|
462
|
+
const worlds = placeItems(s.motion, s.jointValues), I = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
|
|
463
|
+
return s.motion.loops.map((l) => {
|
|
464
|
+
const A = mul(l.a.item < 0 ? I : worlds[l.a.item], l.a.frame), B = mul(l.b.item < 0 ? I : worlds[l.b.item], l.b.frame);
|
|
465
|
+
const gap = Math.hypot(A[3] - B[3], A[7] - B[7], A[11] - B[11]), dot = Math.abs(A[2] * B[2] + A[6] * B[6] + A[10] * B[10]);
|
|
466
|
+
const angle = Math.acos(Math.min(1, dot)) / (Math.PI / 180);
|
|
467
|
+
return { label: l.label, gap, angle, ok: gap <= l.tolerance && angle <= 0.05 };
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// Pairs of parts that overlap, as checkAssembly finds them (fits with a negative min allowed): [[a, b, mm³]]
|
|
472
|
+
function clashesOf(s, named) {
|
|
473
|
+
const allowed = (a, b) => s.fits.some((x) => x.min != null && x.num(x.min) < 0 && ((named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a))));
|
|
474
|
+
const boxes = s.parts.map((p) => bounds(p.triangles)), out = [];
|
|
475
|
+
for (let i = 0; i < s.parts.length; i++) for (let j = i + 1; j < s.parts.length; j++) {
|
|
476
|
+
const pa = s.parts[i], pb = s.parts[j], A = boxes[i], B = boxes[j];
|
|
477
|
+
if (pa.leaf === pb.leaf || ![0, 1, 2].every((k) => A.lo[k] <= B.hi[k] + 1e-6 && B.lo[k] <= A.hi[k] + 1e-6) || allowed(pa, pb)) continue;
|
|
478
|
+
const v = pairOverlap(pa, pb);
|
|
479
|
+
if (v > 0.01) out.push([pa.name, pb.name, v]);
|
|
480
|
+
}
|
|
481
|
+
return out;
|
|
482
|
+
}
|
|
483
|
+
const isNamed = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`);
|
|
484
|
+
|
|
485
|
+
// sweep(s, { joint, steps }) -> findings: each free joint (or the one named) moved through its range, the others held
|
|
486
|
+
// at the assembly's pose, looking for parts that collide and loops that come apart on the way
|
|
487
|
+
export function sweep(s, { joint, steps = 24 } = {}) {
|
|
488
|
+
const out = [], f = (level, text, card) => out.push({ level, text, ...(card && { card }) }), mm = (n) => `${Number(n.toFixed(2))}`;
|
|
489
|
+
const free = s.motion.joints.filter((j) => !j.follow && j.dofs.length && (!joint || j.id === joint));
|
|
490
|
+
if (joint && !free.length) throw new Error(`no joint "${joint}" to sweep (${s.motion.joints.filter((j) => !j.follow && j.dofs.length).map((j) => j.id).join(', ') || 'none'})`);
|
|
491
|
+
const base = s.jointValues;
|
|
492
|
+
for (const j of free) j.dofs.forEach(([lo, hi], d) => {
|
|
493
|
+
const unit = DOFS[j.type][d] === 'angle' ? '°' : ' mm', name = `${j.id}${j.dofs.length > 1 ? ` ${'xyz'[d] && j.type === 'ball' ? 'xyz'[d] : DOFS[j.type][d]}` : ''}`;
|
|
494
|
+
const bad = []; // [value, what]
|
|
495
|
+
for (let i = 0; i <= steps; i++) {
|
|
496
|
+
const v = lo + ((hi - lo) * i) / steps, set = { ...base, [j.id]: base[j.id].map((x, k) => (k === d ? v : x)) };
|
|
497
|
+
const t = s.at(Object.fromEntries(Object.entries(set).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow)));
|
|
498
|
+
const what = [...clashesOf(t, isNamed).map(([a, b]) => `${a} hits ${b}`), ...loopGaps(t).filter((l) => !l.ok).map((l) => `${l.label} apart by ${mm(l.gap)} mm`)];
|
|
499
|
+
if (what.length) bad.push([v, what]);
|
|
500
|
+
}
|
|
501
|
+
const ranges = []; // runs of steps in a row that collide
|
|
502
|
+
for (const [v, what] of bad) { const r = ranges[ranges.length - 1]; if (r && Math.abs(v - r.to - (hi - lo) / steps) < 1e-9) { r.to = v; r.what = [...new Set([...r.what, ...what])]; } else ranges.push({ from: v, to: v, what }); }
|
|
503
|
+
const span = `${mm(lo)} to ${mm(hi)}${unit}`;
|
|
504
|
+
if (!ranges.length) f('pass', `sweep ${name}, ${span} in ${steps} steps: nothing collides`, `${name}: clear ${span}`);
|
|
505
|
+
else f('fail', `sweep ${name}, ${span} in ${steps} steps: ${ranges.map((r) => `${r.from === r.to ? `at ${mm(r.from)}` : `${mm(r.from)} to ${mm(r.to)}`}${unit.trim()}: ${r.what.slice(0, 3).join('; ')}${r.what.length > 3 ? `; and ${r.what.length - 3} more` : ''}`).join(' | ')}`,
|
|
506
|
+
`${name}: collides ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`);
|
|
507
|
+
});
|
|
508
|
+
saveOverlaps();
|
|
509
|
+
return out;
|
|
510
|
+
}
|
|
511
|
+
|
|
325
512
|
// shapes(parts) -> { shapes: [{ part, polygons, triangles }], place: [[shape index, 12 numbers], …] }
|
|
326
513
|
// Each distinct shape once, then where each copy goes: a 3 × 4 transform by rows (x' = a·x + b·y + c·z + d, …).
|
|
327
514
|
export function shapes(parts) {
|
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 || ''));
|
package/lib/meshcmd.mjs
ADDED
|
@@ -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) => ({ '&': '&', '<': '<', '>': '>' })[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
|
-
|
|
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
|
+
"version": "0.4.0",
|
|
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": {
|
|
@@ -47,7 +47,7 @@
|
|
|
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.
|
|
50
|
+
"@rulecad/model-link": "^0.2.0",
|
|
51
51
|
"@rulecad/versions": "^0.1.0",
|
|
52
52
|
"@rulecad/shapes": "^0.2.0",
|
|
53
53
|
"@rulecad/rules": "^0.2.0",
|