@rulecad/cad 0.7.48 → 0.7.53

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/lib/assembly.mjs CHANGED
@@ -16,6 +16,8 @@
16
16
  // { "holes": "pcb.board", "into": "case.body", "depth": "m2.insert_length", "label": "Screws find their inserts" }
17
17
  // The path must be clear for depth mm (it lands in a hole) and solid within "ring" mm of it (default: the hole's
18
18
  // diameter) half way down, so the screw has something to grip. "direction": "up" for screws from below.
19
+ // A screwed joint is a fasten (lib/fasten.mjs): { "screw": "M3 cap", "through": ["bracket"], "into": "base", "at": ["bracket.h1"] }.
20
+ // Its holes are read from the parts as drawn, its screws placed as reference parts, and it holds as a fit that fastens does.
19
21
  import { host, readJson } from './host.mjs';
20
22
  import fs from 'node:fs';
21
23
  import crypto from 'node:crypto';
@@ -44,6 +46,7 @@ import { gripChecks } from './grip.mjs';
44
46
  import { gaitOf, gaitChecks, gaitSequence } from './gait.mjs';
45
47
  import { boughtBuilt, boughtFindings, boughtSets } from './bought.mjs';
46
48
  import { orderChecks } from './order.mjs';
49
+ let fastening = null; // lib/fasten.mjs, loaded with the first assembly that has a fasten: the rest start as fast as before
47
50
 
48
51
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
49
52
  export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
@@ -217,7 +220,9 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
217
220
  items.push({ ...it, id, objName: src.objName, built: src.b, version: src.version, role: src.role });
218
221
  }
219
222
  }
220
- // Every part, with its item where the joints put it at these values (jointValues)
223
+ // Every part, with its item where the joints put it at these values (jointValues); then the hardware of its fasten
224
+ // relations (lib/fasten.mjs), each piece with the item it sits in
225
+ let hardware = [];
221
226
  const partsAt = (worlds) => {
222
227
  const out = [];
223
228
  placed.forEach(([, c], k) => {
@@ -229,7 +234,8 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
229
234
  for (const p of src.sub.parts) {
230
235
  if (p.role === 'support' && a.kind !== 'plate') continue;
231
236
  out.push({ ...p, name: `${id}.${p.name}`, item: id, leaf: `${id}.${p.leaf}`, label: `${id} ${p.label}`,
232
- 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) });
237
+ 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),
238
+ ...(p.hardware ? { moves: id, allow: p.allow.map((l) => `${id}.${l}`), lift: jscad.maths.vec3.transform([0, 0, 0], p.lift, [...m.slice(0, 12), 0, 0, 0, 1]) } : {}) }); // (a component's screws move with it)
233
239
  }
234
240
  } else {
235
241
  for (const p of src.b.parts) {
@@ -241,12 +247,24 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
241
247
  }
242
248
  }
243
249
  });
250
+ for (const h of hardware) out.push(fastening.hardwarePart(h, toMat4(worlds[h.host])));
244
251
  return out;
245
252
  };
246
253
  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'})`);
247
254
  const pose = opts.pose ?? motion.pose;
248
255
  const jv = jointValues(motion, pose);
249
- parts.push(...partsAt(placeItems(motion, jv)));
256
+ const worlds0 = placeItems(motion, jv);
257
+ parts.push(...partsAt(worlds0));
258
+ // Screwed joints: each screw followed through the parts as they stand, its hardware placed, and the joint counted as a
259
+ // fit that fastens (what holds a part, what the order of assembly and the list read)
260
+ let fastened = null;
261
+ if (a.fasten?.length && a.kind !== 'plate') {
262
+ fastening ||= await import('./fasten.mjs');
263
+ fastened = fastening.fastenOf({ a, project, parts, objects, motion, num }, worlds0, { access: pose === motion.pose });
264
+ hardware = fastened.hardware;
265
+ parts.push(...hardware.map((h) => fastening.hardwarePart(h, toMat4(worlds0[h.host]))));
266
+ fits.push(...fastened.fits.map((x) => ({ ...x, num })));
267
+ }
250
268
  // A fit with * applies to every copy: "key-*.switch.bottom" becomes one fit for key-0-0, key-0-1, …
251
269
  // With * on both sides, each copy is checked against all the others: { "a": "key-*.cap", "b": "key-*.cap" }
252
270
  for (let x of a.fits || []) {
@@ -271,9 +289,9 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
271
289
  const at = (p) => {
272
290
  if (typeof p === 'string' && others[p]) return others[p];
273
291
  const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
274
- return { ...s, parts: moved, pose: typeof p === 'string' ? p : null, jointValues: v, polygons: moved.flatMap((x) => x.polygons), triangles: moved.flatMap((x) => x.triangles) };
292
+ return { ...s, parts: moved, fastened: null, pose: typeof p === 'string' ? p : null, jointValues: v, polygons: moved.flatMap((x) => x.polygons), triangles: moved.flatMap((x) => x.triangles) };
275
293
  };
276
- const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, wires, task, gait, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
294
+ const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, wires, task, gait, fastened, hardware, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
277
295
  polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
278
296
  return s;
279
297
  }
@@ -385,7 +403,9 @@ function motionOf(a, placed, num, ref) {
385
403
  const marks = placed.flatMap(([, c], k) => Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
386
404
  try { return { item: k, id: c.id, name, frame: frameOf(spec, evalIn(c.src.b.values, `${c.src.objName} anchor ${name}`)) }; } catch { return null; }
387
405
  })).filter(Boolean);
388
- return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes, drives, loads, gravity: (a.gravity || [0, 0, -1]).map(num) };
406
+ // Where each screw of a fasten goes, where it says so with anchors: a point on its axis, the anchor's z along it
407
+ const fasten = (a.fasten || []).map((x, i) => (Array.isArray(x.at) ? x.at : []).map((n) => ({ ...anchor(n, `fasten ${i + 1}`), name: typeof n === 'string' ? n : null })));
408
+ return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes, drives, loads, fasten, gravity: (a.gravity || [0, 0, -1]).map(num) };
389
409
  }
390
410
 
391
411
  // A pair measured from its drawn teeth (@rulecad/gears contact: backlash, transmission error, interference), kept in
@@ -695,6 +715,9 @@ function saveOverlaps() {
695
715
  try { host.writeText(OVERLAPS, JSON.stringify(remembered)); fresh = 0; } catch {} // only slower without it
696
716
  }
697
717
 
718
+ // A screw and what it is threaded into (its part, its nut, its insert) share space by design: fasten's hardware says which
719
+ const threaded = (a, b) => !!(a.allow?.includes(b.leaf) || b.allow?.includes(a.leaf));
720
+
698
721
  // checkAssembly(built) -> findings, as @rulecad/printcheck: { level, text, card? } (card: a short line for the mirror)
699
722
  // What a project prints in, for the motors' heat and press-fit checks
700
723
  const materialOf = (project) => { try { return readJson(path.join(paths.project(project), 'project.json')).material; } catch { return null; } };
@@ -721,7 +744,7 @@ export function checkAssembly(s) {
721
744
  }
722
745
  // Overlaps between object instances, inside components too. Bounding boxes first: most pairs can't touch.
723
746
  const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`);
724
- 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))));
747
+ const allowed = (a, b) => threaded(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))));
725
748
  const box = new Map(), bx = (p) => box.get(p) || (box.set(p, bounds(p.triangles)), box.get(p));
726
749
  const touch = (a, b) => [0, 1, 2].every((k) => bx(a).lo[k] <= bx(b).hi[k] + 1e-6 && bx(b).lo[k] <= bx(a).hi[k] + 1e-6);
727
750
  const clashes = [];
@@ -864,6 +887,7 @@ export function checkAssembly(s) {
864
887
  }
865
888
  }
866
889
  }
890
+ if (s.a.fasten?.length && fastening) fastening.fastenChecks(s, f, { placeItems });
867
891
  boughtFindings(s, f);
868
892
  massFinding(s, f);
869
893
  runningChecks(s, f, { axisOf, placeItems, jointValues, mul });
@@ -902,7 +926,7 @@ export function loopGaps(s) {
902
926
 
903
927
  // Pairs of parts that overlap, as checkAssembly finds them (fits with a negative min allowed): [[a, b, mm³]]
904
928
  function clashesOf(s, named) {
905
- 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))));
929
+ const allowed = (a, b) => threaded(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))));
906
930
  const boxes = s.parts.map((p) => bounds(p.triangles)), out = [];
907
931
  for (let i = 0; i < s.parts.length; i++) for (let j = i + 1; j < s.parts.length; j++) {
908
932
  const pa = s.parts[i], pb = s.parts[j], A = boxes[i], B = boxes[j];
@@ -963,14 +987,14 @@ export function motionData(s) {
963
987
  const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`), allow = [];
964
988
  const loose = s.fits.filter((x) => x.min != null && x.num(x.min) < 0);
965
989
  s.parts.forEach((pa, i) => s.parts.forEach((pb, j) => {
966
- 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]);
990
+ if (j > i && pa.item !== pb.item && (threaded(pa, pb) || loose.some((x) => (named(pa, x.a) && named(pb, x.b)) || (named(pa, x.b) && named(pb, x.a))))) allow.push([i, j]);
967
991
  }));
968
992
  return { motion: {
969
993
  items: mo.items.map(([n, ...m]) => [n, ...m.map(r)]),
970
994
  joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone, step }) => ({ id, type, parent, child, a: a.map(r), b: b.map(r), dofs: dofs.map((d) => d.map(r)),
971
995
  ...(label ? { label } : {}), ...(follow ? { follow } : {}), ...(path ? { path: path.map((p) => p.map(r)) } : {}), ...(cone != null ? { cone } : {}), ...(step ? { step } : {}) })),
972
996
  poses: mo.poses, ...(s.pose ? { pose: s.pose } : {}),
973
- part: s.parts.map((p) => names.indexOf(p.item)),
997
+ part: s.parts.map((p) => names.indexOf(p.moves ?? p.item)), // (a screw moves with the item it sits in)
974
998
  ...(allow.length ? { allow } : {}),
975
999
  ...(s.gait ? { sequence: gaitSequence(s) ?? undefined } : {}),
976
1000
  } };
package/lib/design.mjs CHANGED
@@ -27,13 +27,14 @@ import { pathToFileURL, fileURLToPath } from 'node:url';
27
27
  import { createRequire } from 'node:module';
28
28
  import crypto from 'node:crypto';
29
29
  import { resolve, loadRuleSet } from './rules.mjs';
30
- import { WS, paths, printerOf } from './workspace.mjs';
30
+ import { WS, paths, printerOf, RULE_DIRS } from './workspace.mjs';
31
31
  import { readLayout, hasLayout, keys, width, depth } from './layout.mjs';
32
32
  import { optimised, forDesign } from './optimise.mjs';
33
33
  import * as shapes from '@rulecad/shapes';
34
34
  import * as flexures from '@rulecad/flexures';
35
35
  import * as gears from '@rulecad/gears';
36
36
  import * as motors from '@rulecad/motors';
37
+ import { resolve as resolveWith } from '@rulecad/variables';
37
38
  import { engineId, packageVersion, materialise } from './versions.mjs';
38
39
  import { satisfies } from '@rulecad/versions';
39
40
 
@@ -127,11 +128,12 @@ const CACHE = paths.cache('builds'), CACHE_VERSION = 3;
127
128
  const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
128
129
  // What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
129
130
  // boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
130
- const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))), motorsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/motors')));
131
+ const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))), motorsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/motors'))), fixingsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/fixings')));
131
132
  // (every module of a helper package but its tests: they change nothing a design builds)
132
133
  const helperSources = (dir) => fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs').sort().map((f) => source(pathToFileURL(path.join(dir, f)).href)).join('');
133
134
  const feaDir = path.dirname(createRequire(pathToFileURL(path.join(flexuresDir, 'package.json')).href).resolve('@rulecad/fea')); // (flexures' own, wherever npm put it)
134
- const own = source(import.meta.url) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(motorsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling'); // every shapes module, not just its entry
135
+ // (as one digest, so each build's key hashes a line and not a megabyte of source)
136
+ const own = crypto.createHash('sha256').update(source(import.meta.url) + source('./fixings.mjs') + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(motorsDir) + helperSources(fixingsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling')).digest('hex'); // every shapes module, not just its entry
135
137
  // A lamina's slow stages (the physics, the flood's probe) are kept apart from the builds, keyed by the library's code
136
138
  // and their own inputs, so a build that changes only what comes after them (a strap, a check, a rule's words) has them
137
139
  // at once: .cache/stages/. A design in the sandbox can't write them, so the sandbox hands them back and the tool writes them
@@ -147,6 +149,29 @@ export const pcbEngine = () => import('@rulecad/pcb').catch((e) => {
147
149
  throw e;
148
150
  });
149
151
 
152
+ // What v.fixings is bound to (lib/fixings.mjs): the workspace's own rule sets by name (a release's own, where it is one:
153
+ // its threads and materials are used before the kit's), the project's printer as a rule set with its values worked
154
+ // out, and the project's material. With a hash of all of it and of the kit's sets: a build that called v.fixings is
155
+ // made from these too, so its cache holds only while they stand.
156
+ let kitRules = null;
157
+ export function fixingsContext(d) {
158
+ const dir = d.rulesDir || RULE_DIRS[0], sets = {}, text = [];
159
+ for (const f of host.list(dir).filter((x) => x.endsWith('.json')).sort()) {
160
+ try { const raw = host.readText(path.join(dir, f)), s = JSON.parse(raw); if (s && s.rules && typeof s.rules === 'object') { sets[s.name ?? f.slice(0, -5)] = s; text.push(raw); } } catch {} // (a broken set is cad check's to name, where a design uses it)
161
+ }
162
+ const name = printerOf(d.project), peek = (n) => { const f = [dir, ...RULE_DIRS].map((x) => path.join(x, `${n}.json`)).find((x) => host.exists(x)); if (!f) throw new Error(`no rule set "${n}" (rules/${n}.json)`); return readJson(f); };
163
+ let printer = null;
164
+ try { // (a printer with no rule set is said where a print is checked; fixings then draws for the kit's)
165
+ const set = peek(name), values = resolveWith({ uses: [name] }, { load: peek }).values[name];
166
+ printer = { name: set.name ?? name, rules: Object.fromEntries(Object.entries(set.rules).map(([k, r]) => [k, typeof values[k] === 'number' ? { ...r, value: values[k] } : r])) };
167
+ } catch {}
168
+ let material = null;
169
+ try { const f = path.join(d.dir, 'project.json'); if (host.exists(f)) material = String(readJson(f).material || '').trim().toLowerCase().split(/\s/)[0] || null; } catch {}
170
+ kitRules ||= (() => { const k = RULE_DIRS.at(-1); return crypto.createHash('sha256').update(fs.readdirSync(k).filter((f) => f.endsWith('.json')).sort().map((f) => fs.readFileSync(path.join(k, f), 'utf8')).join('')).digest('hex'); })();
171
+ const context = { sets, printer, material };
172
+ return { context, hash: crypto.createHash('sha256').update(JSON.stringify([text, printer, material, kitRules])).digest('hex').slice(0, 24) };
173
+ }
174
+
150
175
  // An object's on-screen settings are "display" ({ "smooth": 24 }), and a part left off screen is "display": false.
151
176
  // Their first name, "mirror", still works: read here, the rest of the tool sees it as mirror either way.
152
177
  // Which engine a design's v.ops booleans use: the object's "engine": "manifold", or CAD_ENGINE=manifold for every design
@@ -169,7 +194,8 @@ function syntaxAt(e, d) {
169
194
  return e;
170
195
  }
171
196
 
172
- // build(design, set, { mirror }) -> { object, values, entries, parts, polygons (for the mirror), triangles (for checks and export) }
197
+ // build(design, set, { mirror }) -> { object, values, entries, parts, polygons (for the mirror), triangles (for checks and export), fixings? }
198
+ // fixings: what the design's calls to v.fixings found (each hole and seat, what it was drawn to and rests on), as findings
173
199
  // parts: [{ name, role, label, geometry, polygons, triangles }]; polygons and triangles: every part together
174
200
  export async function build(d, set = {}, { mirror = false } = {}) {
175
201
  const object = readObject(d);
@@ -196,22 +222,26 @@ export async function build(d, set = {}, { mirror = false } = {}) {
196
222
  const reads = { values, parts: object.parts, engine: object.engine, mirror: object.mirror };
197
223
  const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), reads, ruleText, files, Object.values(problems).map((p) => p.hash), set, display])).digest('hex');
198
224
  const hit = path.join(CACHE, `${key}.json`);
199
- if (!process.env.CAD_NO_CACHE && host.exists(hit)) {
200
- const c = JSON.parse(host.readText(hit));
225
+ // (a build that called v.fixings is also made from the workspace's thread sets, its printer and material: it holds
226
+ // while those stand, and is known by them too, so what is kept by a build's hash, an overlap, follows a changed pilot)
227
+ let fx = null; const fixed = () => (fx ||= fixingsContext(d)), known = (f) => (f ? crypto.createHash('sha256').update(key + f).digest('hex') : key);
228
+ const kept = !process.env.CAD_NO_CACHE && host.exists(hit) ? JSON.parse(host.readText(hit)) : null;
229
+ if (kept && (!kept.fixed || kept.fixed === fixed().hash)) {
230
+ const c = kept;
201
231
  try { host.touch(hit); } catch {} // recently used: kept when the cache is pruned
202
232
  for (const e of entries) if (c.used.includes(e.name)) e.used = true;
203
233
  const parts = c.parts.map(({ solid: f, ...p }) => ({ ...p, geometry: fromFaces(f) }));
204
234
  if (c.circuit) Object.assign(values, (await pcbEngine()).outputs(c.circuit, c.matrix));
205
- return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), cached: true, hash: key, ...(c.mechanism ? { mechanism: c.mechanism } : {}), ...(c.circuit ? { circuit: c.circuit, matrix: c.matrix, ...(c.source ? { source: c.source } : {}) } : {}) };
235
+ return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), cached: true, hash: known(c.fixed), ...(c.fixings ? { fixings: c.fixings } : {}), ...(c.mechanism ? { mechanism: c.mechanism } : {}), ...(c.circuit ? { circuit: c.circuit, matrix: c.matrix, ...(c.source ? { source: c.source } : {}) } : {}) };
206
236
  }
207
237
 
208
238
  // A JSCAD design runs in a sandbox (sandbox.mjs: another process that can't write files, start programs or reach
209
239
  // the network) unless the workspace trusts its designs; a board design runs here, with the board engine
210
240
  const pcb = object.engine === 'pcb' ? await pcbEngine() : null;
211
- let parts, board = null, read, mechanism = null;
241
+ let parts, board = null, read, mechanism = null, fixings = null;
212
242
  const optional = Object.keys(object.mirror || {}); // inputs only the on-screen copy has: main may ask for them when they aren't there
213
243
  const stages = stageStore();
214
- if (!pcb && sandboxed() && host.name === 'node') ({ parts, read, mechanism } = await runSandboxed(d, values, object.parts || {}, booleans(object), optional, stages).catch((e) => { throw syntaxAt(e, d); }));
244
+ if (!pcb && sandboxed() && host.name === 'node') ({ parts, read, mechanism, fixings } = await runSandboxed(d, values, object.parts || {}, booleans(object), optional, stages, fixed().context).catch((e) => { throw syntaxAt(e, d); }));
215
245
  else {
216
246
  flexures.laminaCache(stages);
217
247
  const mod = await host.loadModule(d.js).catch((e) => { // a fresh copy after each edit
@@ -221,7 +251,8 @@ export async function build(d, set = {}, { mirror = false } = {}) {
221
251
  throw syntaxAt(located(e, d.js, 'design.run'), d);
222
252
  });
223
253
  if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
224
- const w = watch(values, { shapes, flexures, gears, motors, ops: await shapes.ops(booleans(object)), ...(pcb ? { pcb } : {}) }, optional);
254
+ const ops = await shapes.ops(booleans(object)), df = (await import('./fixings.mjs')).designFixings({ ...fixed().context, ops }); // (loaded when a design is run here: the sandbox's runner has its own)
255
+ const w = watch(values, { shapes, flexures, gears, motors, fixings: df.fixings, ops, ...(pcb ? { pcb } : {}) }, optional);
225
256
  read = w.read;
226
257
  let made;
227
258
  try { ({ shapes: made, mechanism } = unpack(await mod.main(w.v))); } catch (e) { throw Object.assign(located(e, d.js, 'design.run'), { line: lineOf(e, pathToFileURL(d.js).href) || undefined }); }
@@ -238,13 +269,14 @@ export async function build(d, set = {}, { mirror = false } = {}) {
238
269
  made = pcb.solids(board.circuit, { thickness: values.thickness, smooth: values.smooth, models: meshes });
239
270
  }
240
271
  try { parts = named(made, object.parts || {}); } catch (e) { throw located(e, d.js, 'design.run'); }
272
+ if (df.used()) fixings = df.found();
241
273
  }
242
274
  for (const e of entries) if (read.has(e.name)) e.used = true;
243
275
  try {
244
276
  prune();
245
- host.writeText(hit, JSON.stringify({ used: entries.filter((e) => e.used).map((e) => e.name), parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...(board || {}), ...(mechanism ? { mechanism } : {}) }));
277
+ host.writeText(hit, JSON.stringify({ used: entries.filter((e) => e.used).map((e) => e.name), parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...(board || {}), ...(mechanism ? { mechanism } : {}), ...(fixings ? { fixed: fixed().hash, fixings } : {}) }));
246
278
  } catch {} // a cache that can't be written is only slower
247
- return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: key, ...(board || {}), ...(mechanism ? { mechanism } : {}) };
279
+ return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: known(fixings ? fixed().hash : null), ...(fixings ? { fixings } : {}), ...(board || {}), ...(mechanism ? { mechanism } : {}) };
248
280
  }
249
281
 
250
282
  // A cache keeps its most recently used files, about `keep` of them (an old version's builds go first)
package/lib/edit.mjs CHANGED
@@ -58,18 +58,18 @@ const assemblyFile = (ref) => {
58
58
  };
59
59
 
60
60
  /**
61
- * Add to an assembly: a fit, a joint, an item or a loop (appended to its list), or a pose (by name).
62
- * @param {string} ref project/assembly @param {'fit' | 'joint' | 'item' | 'loop' | 'pose'} what @param {any} entry (a pose: { name, values })
61
+ * Add to an assembly: a fit, a joint, an item, a loop or a fasten (appended to its list), or a pose (by name).
62
+ * @param {string} ref project/assembly @param {'fit' | 'joint' | 'item' | 'loop' | 'fasten' | 'pose'} what @param {any} entry (a pose: { name, values })
63
63
  * @returns {{ file: string }}
64
64
  */
65
65
  export function addToAssembly(ref, what, entry) {
66
- const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), list = { fit: 'fits', joint: 'joints', item: 'items', loop: 'loops' }[what];
66
+ const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), list = { fit: 'fits', joint: 'joints', item: 'items', loop: 'loops', fasten: 'fasten' }[what];
67
67
  let text = before;
68
68
  if (what === 'pose') {
69
69
  if (getAt(text, ['poses']) === undefined) text = setAt(text, ['poses'], {});
70
70
  text = setAt(text, ['poses', entry.name], entry.values);
71
71
  } else {
72
- if (!list) throw new CadError('edit.what', `can't add a ${what} (fit, joint, item, loop or pose)`);
72
+ if (!list) throw new CadError('edit.what', `can't add a ${what} (fit, joint, item, loop, fasten or pose)`);
73
73
  if (getAt(text, [list]) === undefined) text = setAt(text, [list], []);
74
74
  const ids = (getAt(text, [list]) || []).map((x) => x.id).filter(Boolean);
75
75
  if (entry.id && ids.includes(entry.id)) throw new CadError('edit.duplicate', `${ref} already has a ${what} "${entry.id}"`, { file });
@@ -84,6 +84,14 @@ export function addToAssembly(ref, what, entry) {
84
84
  if (parts && !parts.includes(part)) throw new CadError('edit.part', `fit ${side}: ${it.object} has no part "${part}" (parts: ${parts.join(', ')})`, { file });
85
85
  }
86
86
  }
87
+ // a fasten names the parts its screw passes and ends in, and where the screws go: each must be an item of the assembly
88
+ if (what === 'fasten') {
89
+ const items = (getAt(text, ['items']) || []).map((x) => x.id), has = (n) => items.includes(String(n).split(/[.@]/)[0]);
90
+ if (!entry.screw) throw new CadError('edit.incomplete', 'a fasten needs its screw, by thread and head: --screw "M3 cap"', { file });
91
+ if (!entry.into || !Array.isArray(entry.through)) throw new CadError('edit.incomplete', 'a fasten needs the parts the screw passes and the one it ends in: --through bracket --into base', { file });
92
+ if ((entry.at == null) === (entry.holes == null)) throw new CadError('edit.incomplete', 'a fasten needs where its screws go: --at bracket.h1,bracket.h2 (an anchor each) or --holes bracket.body (a part whose holes they use), one of the two', { file });
93
+ for (const n of [...entry.through, entry.into, ...(entry.holes ? [entry.holes] : []), ...(entry.at || []).filter((x) => typeof x === 'string')]) if (!has(n)) throw new CadError('edit.part', `fasten: no item "${String(n).split(/[.@]/)[0]}" in ${ref} (items: ${items.join(', ') || 'none'})`, { file });
94
+ }
87
95
  text = appendAt(text, [list], entry);
88
96
  }
89
97
  write(file, text, 'assembly');