@rulecad/cad 0.7.55 → 0.7.57
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 +73 -7
- package/CHANGELOG.md +149 -0
- package/EXAMPLES.md +942 -268
- package/README.md +366 -16
- package/TUTORIAL.md +27 -15
- package/bin/cad.mjs +54 -14
- package/lib/assembly.mjs +75 -16
- package/lib/beams.mjs +2 -2
- package/lib/bought.mjs +41 -5
- package/lib/buildpage.mjs +8 -3
- package/lib/design.mjs +6 -4
- package/lib/edit.mjs +36 -5
- package/lib/fasten.mjs +322 -55
- package/lib/fittings.mjs +271 -0
- package/lib/framebuild.mjs +407 -0
- package/lib/frames.mjs +4 -3
- package/lib/guides.mjs +354 -0
- package/lib/jigs.mjs +237 -0
- package/lib/joins.mjs +259 -0
- package/lib/jsonedit.mjs +19 -0
- package/lib/list.mjs +24 -8
- package/lib/loads.mjs +9 -2
- package/lib/measured.mjs +64 -17
- package/lib/motors.mjs +28 -13
- package/lib/order.mjs +23 -12
- package/lib/panels.mjs +220 -0
- package/lib/plates.mjs +11 -4
- package/lib/schema.mjs +3 -2
- package/lib/services.mjs +132 -0
- package/lib/sheet.mjs +20 -3
- package/lib/slotnuts.mjs +159 -0
- package/lib/task.mjs +4 -2
- package/lib/wires.mjs +2 -1
- package/package.json +8 -7
- package/schemas/assembly.schema.json +41 -14
- package/schemas/object.schema.json +2 -2
package/lib/bought.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Bought parts in assemblies: a bearing, a switch, a driver, a board or a
|
|
1
|
+
// Bought parts in assemblies: a bearing, a switch, a driver, a board, a supply or a frame's fitting named by its rule set, drawn from the
|
|
2
2
|
// set's figures as a faint reference (never on a plate), with anchors from what it is. A motor is the same thing with a
|
|
3
3
|
// shaft that turns a joint, so its item is built here too (lib/motors.mjs).
|
|
4
4
|
import crypto from 'node:crypto';
|
|
@@ -7,6 +7,7 @@ import jscad from '@jscad/modeling';
|
|
|
7
7
|
import { peekRuleSet as loadRuleSet } from './rules.mjs';
|
|
8
8
|
import { RULE_DIRS } from './workspace.mjs';
|
|
9
9
|
import { named } from './parts.mjs';
|
|
10
|
+
import { boughtFittingModel, boughtFitting } from '@rulecad/frames';
|
|
10
11
|
|
|
11
12
|
const { cuboid, cylinder, polygon } = jscad.primitives, { translate } = jscad.transforms, { union, subtract } = jscad.booleans, { extrudeRotate } = jscad.extrusions;
|
|
12
13
|
const SEG = 48;
|
|
@@ -47,11 +48,14 @@ const SHAPES = {
|
|
|
47
48
|
return { parts: { body, lever: box(w, Math.min(4, d), 0.4, w * 0.1, 0, h + 2) }, anchors: { lever: z([w * 0.6, 0, h + 2]), left: z([-holes, 0, up], [0, 1, 0]), right: z([holes, 0, up], [0, 1, 0]), base: z([0, 0, 0]) } };
|
|
48
49
|
},
|
|
49
50
|
board(v, set) {
|
|
50
|
-
const w = v.body_width, d = v.body_depth, t = 1.6;
|
|
51
|
+
const w = v.body_width, d = v.body_depth, t = v.board_thickness ?? 1.6;
|
|
51
52
|
const axes = [...new Set(Object.keys(set.rules).map((k) => /^step_pin_(\w+)$/.exec(k)?.[1]).filter(Boolean))].map((a) => a.toUpperCase());
|
|
52
53
|
// Where a board's axis connectors are along its edge is for routing a wire, no closer than that
|
|
53
54
|
const sockets = Object.fromEntries(axes.map((a, i) => [a, z([-w / 2 + ((i + 0.5) * w) / axes.length, d / 2, t], [0, 1, 0])]));
|
|
54
|
-
|
|
55
|
+
// its mounting holes, where its set gives them, drawn through it so a screw's clearance is measured in them
|
|
56
|
+
const flat = set.rules.mount_holes?.value, holes = Array.isArray(flat) && v.mount_hole_diameter ? Array.from({ length: Math.floor(flat.length / 2) }, (_, i) => [flat[2 * i], flat[2 * i + 1]]) : [];
|
|
57
|
+
const body = holes.length ? subtract(box(w, d, t), ...holes.map(([x, y]) => translate([x, y, t / 2], cylinder({ radius: v.mount_hole_diameter / 2, height: t + 2, segments: 32 })))) : box(w, d, t);
|
|
58
|
+
return { parts: { body }, anchors: { centre: z([0, 0, t / 2]), top: z([0, 0, t]), bottom: z([0, 0, 0]), ...sockets } };
|
|
55
59
|
},
|
|
56
60
|
driver(v) {
|
|
57
61
|
const w = v.body_width, d = v.body_depth, t = 1.6, row = v.row_spacing / 2, pins = v.pin_count / 2, pitch = v.pin_pitch, run = pitch * (pins - 1), pin = 0.64, drop = 8;
|
|
@@ -64,6 +68,14 @@ const SHAPES = {
|
|
|
64
68
|
return { parts: { body: extrudeRotate({ segments: SEG }, polygon({ points: [[r + c, 0], [R - c, 0], [R, c], [R, L - c], [R - c, L], [r + c, L], [r, L - c], [r, c]] })) }, anchors: { bore: z([0, 0, L / 2]), face: z([0, 0, 0]), top: z([0, 0, L]) } };
|
|
65
69
|
},
|
|
66
70
|
rod(v) { return { parts: { body: translate([0, 0, v.length / 2], cylinder({ radius: v.diameter / 2, height: v.length, segments: SEG })) }, anchors: { bottom: z([0, 0, 0]), top: z([0, 0, v.length]) } }; },
|
|
71
|
+
// a bought fitting for a frame (@rulecad/frames' bought.mjs): drawn in the printed fittings' frames, an anchor on
|
|
72
|
+
// each screw's axis at its head's seat (b1, b2 .. into b; a1 .. into a); one that lies in the slots (an inner or an
|
|
73
|
+
// anchor connector) is inside the beams by design, so the overlap check leaves it out
|
|
74
|
+
fitting(v, set) {
|
|
75
|
+
const m = boughtFittingModel({ name: set.name, part: 'fitting', rules: set.rules }), count = { a: 0, b: 0 };
|
|
76
|
+
const anchors = Object.fromEntries(m.screws.map((q) => [`${q.leg}${++count[q.leg]}`, z(q.at, q.axis.map((c) => (c ? -c : 0)))]));
|
|
77
|
+
return { parts: { body: boughtFitting(m, { pose: 'fit' }) }, anchors: { origin: z([0, 0, 0]), ...anchors }, inside: ['hidden', 'anchor'].includes(m.fitting), model: m };
|
|
78
|
+
},
|
|
67
79
|
supply(v) {
|
|
68
80
|
const w = v.body_width, d = v.body_depth, h = v.body_length;
|
|
69
81
|
return { parts: { body: box(w, d, h) }, anchors: { base: z([0, 0, 0]), top: z([0, 0, h]), terminals: z([0, -d / 2, h / 2], [0, -1, 0]) } };
|
|
@@ -78,7 +90,8 @@ export function boughtModel(name, variant) {
|
|
|
78
90
|
if (variant != null) {
|
|
79
91
|
const vs = set.variants || {};
|
|
80
92
|
if (!vs[variant]) throw new Error(`${name} has no variant "${variant}" (${Object.keys(vs).join(', ') || 'none'})`);
|
|
81
|
-
|
|
93
|
+
// (its values take the variant's kind and source; its rules, where it has them, are whole rules with their own)
|
|
94
|
+
rules = { ...set.rules, ...Object.fromEntries(Object.entries(vs[variant].values ?? {}).map(([k, value]) => [k, { ...set.rules[k], value, kind: vs[variant].kind ?? set.rules[k]?.kind, source: vs[variant].source ?? set.rules[k]?.source }])), ...(vs[variant].rules ?? {}) };
|
|
82
95
|
}
|
|
83
96
|
return { name, part: set.part, variant: variant ?? null, rules };
|
|
84
97
|
}
|
|
@@ -95,11 +108,34 @@ export function boughtBuilt(spec, it, num, id) {
|
|
|
95
108
|
const missing = Object.entries(shape.anchors).filter(([, a]) => a.at.some((c) => !Number.isFinite(c))).map(([k]) => k);
|
|
96
109
|
if (missing.length) throw new Error(`item ${id}: ${spec}: its rules don't place the anchors ${missing.join(', ')}`);
|
|
97
110
|
const parts = named(shape.parts, Object.fromEntries(Object.keys(shape.parts).map((k) => [k, { label: `${m.name} ${k}` }])));
|
|
111
|
+
if (shape.inside) parts[0].collide = jscad.geometries.geom3.create(); // (in the slots, inside the beams by design)
|
|
98
112
|
const entries = Object.entries(m.rules).map(([k, r]) => ({ name: `${m.name}.${k}`, value: r.value, unit: r.unit, rule: r.rule, kind: r.kind, source: r.source, checked: r.checked, set: m.name }));
|
|
99
|
-
return referenceBuilt({ id, key: 'bought', objName: `bought:${m.name}`, name: m.name, parts, anchors: shape.anchors, entries, values, extra: { bought: { set: m.name, variant: m.variant, part: m.part, mass: values.mass ?? null } } });
|
|
113
|
+
return referenceBuilt({ id, key: 'bought', objName: `bought:${m.name}`, name: m.name, parts, anchors: shape.anchors, entries, values, extra: { bought: { set: m.name, variant: m.variant, part: m.part, mass: values.mass ?? null, mount: mountOf(m), ...(m.rules.cost ? { cost: { value: m.rules.cost.value, unit: m.rules.cost.unit } } : {}), ...(shape.model ? { fitting: shape.model } : {}) } } });
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A bought part's mounting holes from its rules (mount_holes: x then y for each), as a printed mount and the fasten checks read them: { holes ([[x, y], ...]), thread,
|
|
118
|
+
* reach, diameter, thickness, face }, or null where its set gives none. A thread means tapped holes (a supply's), a
|
|
119
|
+
* diameter plain ones (a board's). @param {{ name: string, part: string, rules: object }} m boughtModel's
|
|
120
|
+
*/
|
|
121
|
+
export function mountOf(m) {
|
|
122
|
+
const r = m.rules, flat = r.mount_holes?.value; // (x then y for each hole, as the vocabulary keeps a list)
|
|
123
|
+
if (!Array.isArray(flat) || !flat.length || flat.length % 2) return null;
|
|
124
|
+
const holes = Array.from({ length: flat.length / 2 }, (_, i) => [flat[2 * i], flat[2 * i + 1]]);
|
|
125
|
+
return { set: m.name, holes, thread: typeof r.mount_hole_thread?.value === 'string' ? r.mount_hole_thread.value : null, reach: r.mount_hole_reach?.value ?? null, diameter: r.mount_hole_diameter?.value ?? null,
|
|
126
|
+
thickness: m.part === 'board' ? r.board_thickness?.value ?? 1.6 : null, body: [r.body_width?.value, r.body_depth?.value], height: m.part === 'board' ? r.board_thickness?.value ?? 1.6 : r.body_length?.value ?? null, kind: r.mount_holes.kind, source: r.mount_holes.source };
|
|
100
127
|
}
|
|
101
128
|
|
|
102
129
|
// One line in the check for each bought item, so the shopping list and the wiring can read it
|
|
103
130
|
export function boughtFindings(s, f) {
|
|
131
|
+
// a frame's bought fitting placed at a beam's address (an end cap at x1.a, a foot, a hinge on a face): does it fit
|
|
132
|
+
// that beam's profile (its size, its slot family, a foot's stem against the end's bore)
|
|
133
|
+
const items = new Map((s.a?.items ?? []).map((it) => [it.id, it]));
|
|
134
|
+
for (const o of s.objects) if (o.bought?.fitting && !o.unplaced && items.get(o.id)?.join == null) {
|
|
135
|
+
const at = items.get(o.id)?.at, beam = typeof at === 'string' ? s.objects.find((x) => x.id === at.trim().split('.')[0])?.beam : null;
|
|
136
|
+
if (!beam) continue;
|
|
137
|
+
for (const x of boughtFittingModel(o.bought.fitting.set, { profile: beam.profile, ...(s.frames ? { given: s.frames } : {}) }).findings.filter((y) => y.code === 'fitting.fit'))
|
|
138
|
+
f(x.level, `${o.id}: ${x.text}`, x.level === 'fail' ? `${o.id}: fit` : null, { code: x.code, ...(x.values ? { values: x.values } : {}), refs: { item: o.id, beam: beam.name, ...x.refs } });
|
|
139
|
+
}
|
|
104
140
|
for (const o of s.objects) if (o.bought) f('info', `${o.id}: ${o.bought.set}${o.bought.variant ? ` (${o.bought.variant})` : ''}${o.bought.length != null ? ` x ${Number(o.bought.length.toFixed(2))} mm` : ''}, a ${o.bought.part}`, null, { code: 'bought.item', refs: { item: o.id, set: o.bought.set, variant: o.bought.variant, part: o.bought.part, ...(o.bought.length != null ? { length: o.bought.length } : {}) } });
|
|
105
141
|
}
|
package/lib/buildpage.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// What a machine's model link adds to the model, all read from the same assembly the checks read: the task (the pen, the
|
|
2
2
|
// plane, the margins' figures), a step file, the wires' routes, and the build page (shopping list with the beams' cut
|
|
3
|
-
// list, each beam's cut-and-drill sheet, plates, wiring sheet, assembly steps,
|
|
3
|
+
// list, each beam's cut-and-drill sheet, plates, wiring sheet, assembly steps, a frame's build from bars to square,
|
|
4
|
+
// machine settings).
|
|
4
5
|
import fs from 'node:fs';
|
|
5
6
|
import path from 'node:path';
|
|
6
7
|
import { sheetFrame } from '@rulecad/robots';
|
|
@@ -13,6 +14,8 @@ import { shoppingList } from './list.mjs';
|
|
|
13
14
|
import { cutListOf, sheetFile } from './beams.mjs';
|
|
14
15
|
import { wiresFor, wireRoutesOf } from './assembly.mjs';
|
|
15
16
|
import { orderOf, isBuilt } from './order.mjs';
|
|
17
|
+
import { withPreload } from './slotnuts.mjs';
|
|
18
|
+
import { frameBuild } from './framebuild.mjs';
|
|
16
19
|
import { platesOf } from './plates.mjs';
|
|
17
20
|
import { wiringSheet } from './wires.mjs';
|
|
18
21
|
import { readLedger } from './measured.mjs';
|
|
@@ -60,11 +63,13 @@ export async function buildData(s) {
|
|
|
60
63
|
const list = await guard(() => shoppingList(s));
|
|
61
64
|
const wires = await guard(() => (s.wires?.length ? wiresFor(s).map(({ route, ...w }) => w) : null));
|
|
62
65
|
const plates = await guard(() => platesOf(s).then(({ bed, gap, plates: p, findings }) => ({ bed, gap, plates: p, findings })));
|
|
63
|
-
const order = isBuilt(s) ? await guard(() => orderOf(s)) : null;
|
|
66
|
+
const order = isBuilt(s) ? await guard(() => withPreload(s, orderOf(s))) : null; // (with the slot nuts to load before a join closes their slot)
|
|
64
67
|
const machine = s.task ? await guard(() => machineOf(s)) : null;
|
|
65
68
|
// each mark's cut-and-drill sheet, by its file in the exports (cad beams writes them), and whether it is there yet
|
|
66
69
|
const beams = await guard(() => { const c = cutListOf(s); return c ? { sheets: c.marks.map((m) => ({ mark: m.mark, items: m.items, file: ['exports', s.project, path.basename(sheetFile(s, m.mark))].join('/'), written: fs.existsSync(sheetFile(s, m.mark)) })) } : null; });
|
|
67
|
-
return {
|
|
70
|
+
const frame = s.joins?.length ? await guard(() => { const { steps, sides, notFlat, bays, torques, stuck } = frameBuild(s); return { steps, sides: sides.map((x) => ({ beams: x.beams, name: x.name })), notFlat, bays: bays.map((b) => ({ beams: b.beams, name: b.name, width: b.width, height: b.height, diagonal: b.square.diagonal, accept: b.square.accept, lean: b.square.lean })), torques, stuck }; }) : null; // (from bars to a square frame)
|
|
71
|
+
// a frame's build is its one sequence, from bars to square with the rest mounted: the assembly order is not shown beside it
|
|
72
|
+
return { build: { list, wires, plates, order: frame && !frame.error ? null : order, machine, beams, ...(frame ? { frame } : {}) } };
|
|
68
73
|
}
|
|
69
74
|
|
|
70
75
|
// The ledger, in the rules sheet's own rows: each prediction the bench can measure, the measurement once it's in
|
package/lib/design.mjs
CHANGED
|
@@ -241,7 +241,7 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
241
241
|
// A JSCAD design runs in a sandbox (sandbox.mjs: another process that can't write files, start programs or reach
|
|
242
242
|
// the network) unless the workspace trusts its designs; a board design runs here, with the board engine
|
|
243
243
|
const pcb = object.engine === 'pcb' ? await pcbEngine() : null;
|
|
244
|
-
let parts, board = null, read, mechanism = null, fixings = null;
|
|
244
|
+
let parts, board = null, read, mechanism = null, fixings = null, mounted = false;
|
|
245
245
|
const optional = Object.keys(object.mirror || {}); // inputs only the on-screen copy has: main may ask for them when they aren't there
|
|
246
246
|
const stages = stageStore();
|
|
247
247
|
if (!pcb && sandboxed() && host.name === 'node') ({ parts, read, mechanism, fixings } = await runSandboxed(d, values, object.parts || {}, booleans(object), optional, stages, { frames: framed, fixings: fixed().context }).catch((e) => { throw syntaxAt(e, d); }));
|
|
@@ -255,7 +255,9 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
255
255
|
});
|
|
256
256
|
if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
|
|
257
257
|
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)
|
|
258
|
-
|
|
258
|
+
// v.pcb.mount('M2', ...) reads the workspace's thread sets, as v.fixings does: such a build is known by them too
|
|
259
|
+
const engine = pcb ? { ...pcb, mount: (thread, x, y, o = {}) => { mounted = true; return pcb.mount(thread, x, y, { sets: fixed().context.sets, ...o }); } } : null;
|
|
260
|
+
const w = watch(values, { shapes, flexures, gears, motors, frames: designFrames(framed), fixings: df.fixings, ops, ...(engine ? { pcb: engine } : {}) }, optional);
|
|
259
261
|
read = w.read;
|
|
260
262
|
let made;
|
|
261
263
|
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 }); }
|
|
@@ -277,9 +279,9 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
277
279
|
for (const e of entries) if (read.has(e.name)) e.used = true;
|
|
278
280
|
try {
|
|
279
281
|
prune();
|
|
280
|
-
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 } : {}) }));
|
|
282
|
+
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 || mounted ? { fixed: fixed().hash } : {}), ...(fixings ? { fixings } : {}) }));
|
|
281
283
|
} catch {} // a cache that can't be written is only slower
|
|
282
|
-
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 } : {}) };
|
|
284
|
+
return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: known(fixings || mounted ? fixed().hash : null), ...(fixings ? { fixings } : {}), ...(board || {}), ...(mechanism ? { mechanism } : {}) };
|
|
283
285
|
}
|
|
284
286
|
|
|
285
287
|
// A cache keeps its most recently used files, about `keep` of them (an old version's builds go first)
|
package/lib/edit.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// its schema, and an object's variables must still resolve. Used by cad set and cad add; a program can call them too.
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import { setAt, appendAt, getAt } from './jsonedit.mjs';
|
|
6
|
+
import { setAt, appendAt, getAt, removeAt } from './jsonedit.mjs';
|
|
7
7
|
import { validate, schema } from './schema.mjs';
|
|
8
8
|
import { CadError } from './errors.mjs';
|
|
9
9
|
import { paths } from './workspace.mjs';
|
|
@@ -58,18 +58,18 @@ const assemblyFile = (ref) => {
|
|
|
58
58
|
};
|
|
59
59
|
|
|
60
60
|
/**
|
|
61
|
-
* Add to an assembly: a fit, a joint, an item, a loop or a
|
|
62
|
-
* @param {string} ref project/assembly @param {'fit' | 'joint' | 'item' | 'loop' | 'fasten' | 'pose'} what @param {any} entry (a pose: { name, values })
|
|
61
|
+
* Add to an assembly: a fit, a joint, an item, a loop, a fasten or a join (appended to its list), or a pose (by name).
|
|
62
|
+
* @param {string} ref project/assembly @param {'fit' | 'joint' | 'item' | 'loop' | 'fasten' | 'join' | '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', fasten: 'fasten' }[what];
|
|
66
|
+
const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), list = { fit: 'fits', joint: 'joints', item: 'items', loop: 'loops', fasten: 'fasten', join: 'joins' }[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, fasten or pose)`);
|
|
72
|
+
if (!list) throw new CadError('edit.what', `can't add a ${what} (fit, joint, item, loop, fasten, join 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 });
|
|
@@ -92,8 +92,39 @@ export function addToAssembly(ref, what, entry) {
|
|
|
92
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
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
94
|
}
|
|
95
|
+
// a join names a beam's end and a place on another beam: each must be a beam item of the assembly
|
|
96
|
+
if (what === 'join') {
|
|
97
|
+
const beams = (getAt(text, ['items']) || []).filter((x) => x.beam).map((x) => x.id);
|
|
98
|
+
if (!entry.kind || !entry.a || !entry.b) throw new CadError('edit.incomplete', 'a join needs its kind and the two beams: --kind blind --a y1.a --b x1.back@120', { file });
|
|
99
|
+
for (const side of ['a', 'b']) { const id = String(entry[side]).split('.')[0]; if (!beams.includes(id)) throw new CadError('edit.part', `join ${side}: no beam "${id}" in ${ref} (beams: ${beams.join(', ') || 'none'})`, { file }); }
|
|
100
|
+
}
|
|
95
101
|
text = appendAt(text, [list], entry);
|
|
96
102
|
}
|
|
97
103
|
write(file, text, 'assembly');
|
|
98
104
|
return { file };
|
|
99
105
|
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Put a fasten in place of each holes fit and the fit that fastens the same two items (as lib/fasten.mjs's fastenFromFits
|
|
109
|
+
* finds them): the holes fit goes, the fit that fastens goes too, or keeps its gap range (min, max) with "fastens",
|
|
110
|
+
* "fastener" and "count" taken off, and the fasten is added. A screw given replaces the one found.
|
|
111
|
+
* @param {string} ref project/assembly @param {{ fasten: object, holes: number, fastens: number }[]} found @param {{ screw?: string }} [options]
|
|
112
|
+
* @returns {{ file: string, added: object[] }}
|
|
113
|
+
*/
|
|
114
|
+
export function fastenFromFitsEdit(ref, found, { screw } = {}) {
|
|
115
|
+
const file = assemblyFile(ref);
|
|
116
|
+
if (!found.length) throw new CadError('edit.nothing', `${ref} has no holes fit with a fit that fastens the same two items (and no fasten for them yet): nothing to put a fasten in place of`, { file });
|
|
117
|
+
let text = fs.readFileSync(file, 'utf8');
|
|
118
|
+
const fits = getAt(text, ['fits']), drop = new Set(), trim = new Set();
|
|
119
|
+
for (const g of found) { drop.add(g.holes); (fits[g.fastens].min != null || fits[g.fastens].max != null ? trim : drop).add(g.fastens); }
|
|
120
|
+
// last first, so the places of the others hold
|
|
121
|
+
for (const i of [...new Set([...drop, ...trim])].sort((a, b) => b - a)) {
|
|
122
|
+
if (drop.has(i)) { text = removeAt(text, ['fits', i]); continue; }
|
|
123
|
+
for (const k of ['count', 'fastener', 'fastens']) if (getAt(text, ['fits', i, k]) !== undefined) text = removeAt(text, ['fits', i, k]);
|
|
124
|
+
}
|
|
125
|
+
if (getAt(text, ['fasten']) === undefined) text = setAt(text, ['fasten'], []);
|
|
126
|
+
const added = found.map((g) => ({ ...g.fasten, ...(screw ? { screw } : {}) }));
|
|
127
|
+
for (const x of added) text = appendAt(text, ['fasten'], x);
|
|
128
|
+
write(file, text, 'assembly');
|
|
129
|
+
return { file, added };
|
|
130
|
+
}
|