@rulecad/cad 0.7.56 → 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/lib/assembly.mjs CHANGED
@@ -18,6 +18,8 @@
18
18
  // diameter) half way down, so the screw has something to grip. "direction": "up" for screws from below.
19
19
  // A screwed joint is a fasten (lib/fasten.mjs): { "screw": "M3 cap", "through": ["bracket"], "into": "base", "at": ["bracket.h1"] }.
20
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.
21
+ // Beams are held to each other by joins (lib/joins.mjs): { "kind": "blind", "a": "y1.a", "b": "x1.back@120" }. Each puts
22
+ // its operations on both beams and its screws into fasten before anything is built, and is checked once it is.
21
23
  import { host, readJson } from './host.mjs';
22
24
  import fs from 'node:fs';
23
25
  import crypto from 'node:crypto';
@@ -41,12 +43,19 @@ import { wiresOf, wireChecks, wireRows, wireTubes, wireRoutes } from './wires.mj
41
43
  import { printedParts } from './list.mjs';
42
44
  import { taskOf, taskChecks } from './task.mjs';
43
45
  import { powerChecks } from './power.mjs';
44
- import { loadChecks } from './loads.mjs';
46
+ import { loadChecks, beyond } from './loads.mjs';
45
47
  import { gripChecks } from './grip.mjs';
46
48
  import { gaitOf, gaitChecks, gaitSequence } from './gait.mjs';
47
49
  import { boughtBuilt, boughtFindings, boughtSets } from './bought.mjs';
48
50
  import { orderChecks } from './order.mjs';
49
- import { beamBuilt, beamPlace, beamAddress, beamFindings, marksOf } from './beams.mjs';
51
+ import { beamBuilt, beamPlace, beamAddress, beamFindings, marksOf, framesContext } from './beams.mjs';
52
+ import { fittingBuilt, fittingFindings, plasticOf } from './fittings.mjs';
53
+ import { expandJoins, joinChecks } from './joins.mjs';
54
+ import { expandPanels, panelBuilt, panelFindings, PANEL_CHECK } from './panels.mjs';
55
+ import { expandServices, serviceFindings } from './services.mjs';
56
+ import { expandGuides, guideBuilt, guideFindings } from './guides.mjs';
57
+ import { slotNutChecks } from './slotnuts.mjs';
58
+ import { frameSquareChecks, frameBuild } from './framebuild.mjs';
50
59
  let fastening = null; // lib/fasten.mjs, loaded with the first assembly that has a fasten: the rest start as fast as before
51
60
 
52
61
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
@@ -79,7 +88,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
79
88
  const outer = overrides;
80
89
  const [project, name] = ref.split('/');
81
90
  if (stack.includes(ref)) throw new Error(`assembly ${ref} contains itself (${[...stack, ref].join(' → ')})`);
82
- const a = readJson(assemblyPath(ref));
91
+ let a = readJson(assemblyPath(ref));
83
92
  // A pose may set items' variables as well as joints ("cocked": { "run": -30, "action.travel": 25 }): a flexure bent
84
93
  // as the pose bends it, while the part itself is printed as drawn. The pose being built sets them on its items.
85
94
  const itemSets = (name) => { const out = {}; for (const [k, v] of Object.entries(a.poses?.[name] || {})) if (k.includes('.')) { const [item, ...rest] = k.split('.'); (out[item] ||= {})[rest.join('.')] = v; } return out; };
@@ -104,6 +113,18 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
104
113
  return v;
105
114
  };
106
115
  const num = (x) => evaluate(x, lookup);
116
+ // Joins between beams (lib/joins.mjs): their operations go on the beams and their screws into fasten before anything is built
117
+ let joins = [];
118
+ if (a.joins != null) ({ a, joins } = expandJoins(a, num, undefined, plasticOf(project)));
119
+ // Panels (lib/panels.mjs): each placed on its bay, its clips or a door's hinges, handle and catch added with their fastens
120
+ let panels = [];
121
+ if ((a.items || []).some((it) => it?.panel)) ({ a, panels } = expandPanels(a, num, undefined, plasticOf(project)));
122
+ // Services (lib/services.mjs): a bought board or supply on its printed mount, a wire's run along a slot held by clips
123
+ let mounts = [], runs = [];
124
+ if ((a.items || []).some((it) => it?.mount != null) || (a.wires || []).some((w) => (w?.via ?? []).some((v) => v && typeof v === 'object'))) ({ a, mounts, runs } = expandServices(a, num, undefined, plasticOf(project)));
125
+ // Guides (lib/guides.mjs): a rail on a beam's face, its screws into the slot, each carriage on its own sliding joint
126
+ let guides = [];
127
+ if (a.guides != null) ({ a, guides } = expandGuides(a, num, undefined, plasticOf(project)));
107
128
  const { translate, rotate, transform } = jscad.transforms, deg = Math.PI / 180;
108
129
 
109
130
  const items = [], parts = [], objects = [], fits = [], requires = [];
@@ -112,6 +133,9 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
112
133
  const source = async (it, extra) => {
113
134
  if (it.motor) { const key = JSON.stringify(['motor', it.id, it.motor]); if (!built.has(key)) built.set(key, motorBuilt(it.motor, num, it.id)); return built.get(key); }
114
135
  if (it.beam) { const b = beamBuilt(it, num, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/beams.mjs)
136
+ if (it.fitting) { const b = await fittingBuilt(it, it.id, framesContext(), plasticOf(project)); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/fittings.mjs)
137
+ if (it.panel) { const b = await panelBuilt(it, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/panels.mjs)
138
+ if (it._guide) { const b = guideBuilt(it, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/guides.mjs)
115
139
  if (it.bought) {
116
140
  const key = JSON.stringify(['bought', it.id, it.bought, it.variant, it.set]);
117
141
  if (!built.has(key)) built.set(key, boughtSets().get(it.bought) === 'motor' ? motorBuilt({ model: it.bought }, num, it.id) : boughtBuilt(it.bought, it, num, it.id));
@@ -153,7 +177,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
153
177
  let builtCount = 0;
154
178
  for (const it of a.items || []) {
155
179
  if (!/^[a-z][\w-]*$/.test(it.id || '')) throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
156
- if ([it.object, it.assembly, it.motor, it.bought, it.beam].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly", "motor", "bought" or "beam"`);
180
+ if ([it.object, it.assembly, it.motor, it.bought, it.beam, it.fitting, it.panel].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly", "motor", "bought", "beam", "fitting" or "panel"`);
157
181
  if (!it.beam && (it.to != null || it.roll != null)) throw new Error(`item ${it.id}: to and roll place a beam by its ends: place ${it.object || it.assembly || it.motor?.model || it.bought} with at and rotate`);
158
182
  // Copies: one, a grid from repeat x/y, or a layout's keys. Each: { id, offset (from at), extra (values to set) }
159
183
  const rx = it.repeat?.x, ry = it.repeat?.y, rl = it.repeat?.layout, copies = [];
@@ -219,7 +243,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
219
243
  for (const n of sub.seen) seen.add(n);
220
244
  items.push({ ...it, id, sub, role: 'part' });
221
245
  } else {
222
- objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role, ...(src.set ? { set: src.set } : {}), ...(src.variant ? { variant: src.variant } : {}), ...(src.bought ? { bought: src.bought } : {}), ...(src.motor ? { motor: src.motor } : {}), ...(src.beam ? { beam: src.beam } : {}) });
246
+ objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role, ...(src.set ? { set: src.set } : {}), ...(src.variant ? { variant: src.variant } : {}), ...(src.bought ? { bought: src.bought } : {}), ...(src.motor ? { motor: src.motor } : {}), ...(src.beam ? { beam: src.beam } : {}), ...(src.fitting ? { fitting: src.fitting } : {}), ...(src.panel ? { panel: src.panel } : {}) });
223
247
  items.push({ ...it, id, objName: src.objName, built: src.b, version: src.version, role: src.role, ...(src.beam ? { beam: src.beam } : {}) });
224
248
  }
225
249
  }
@@ -303,7 +327,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
303
327
  const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
304
328
  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) };
305
329
  };
306
- 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,
330
+ const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, wires, task, gait, fastened, hardware, joins, panels, mounts, runs, guides, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
307
331
  polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
308
332
  return s;
309
333
  }
@@ -742,7 +766,7 @@ function pairOverlap(pa, pb) {
742
766
  if (!pa.hash || !pb.hash) return overlap(solidOf(pa), solidOf(pb));
743
767
  remembered ||= (() => { try { return JSON.parse(host.readText(OVERLAPS)); } catch { return {}; } })();
744
768
  const at = (p) => `${p.hash}@${Array.from(p.m || []).map((x) => Math.round(x * 1e6) / 1e6).join(',')}`;
745
- const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`crossing+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
769
+ const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`crossing+tracks+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
746
770
  if (!(k in remembered)) { remembered[k] = overlap(solidOf(pa), solidOf(pb)); fresh++; }
747
771
  return remembered[k];
748
772
  }
@@ -767,6 +791,8 @@ function massFinding(s, f) {
767
791
  }
768
792
 
769
793
  export function checkAssembly(s) {
794
+ // the screws found in this pose (at(pose) leaves them to be found again): the fasten and slot nut checks read the same
795
+ if (!s.fastened && s.a.fasten?.length && fastening) s = { ...s, fastened: fastening.fastenOf(s, placeItems(s.motion, s.jointValues)) };
770
796
  const out = [], f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }), mm = (n) => `${Number(n.toFixed(3))}`;
771
797
  // Versions: every pin, from this assembly and its components, against every copy of that object
772
798
  const pins = new Map();
@@ -909,12 +935,28 @@ export function checkAssembly(s) {
909
935
  // nowhere else: a ring gear resting on its case turns with the planets; a pawl resting on its post walks off it.
910
936
  if (s.motion.joints.some((j) => j.type !== 'fixed')) {
911
937
  const ids = s.motion.items.map((x) => x[0]), top = (n) => String(n).split(/[.@]/)[0];
912
- const held = new Set([ids[0], ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child])]), links = s.fits.filter((x) => x.fastens).map((x) => [top(x.a), top(x.b)]);
938
+ // (a beam placed by its ends is the frame, held where it is drawn: what is screwed to it is held by it)
939
+ const held = new Set([ids[0], ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]), ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id)]), links = s.fits.filter((x) => x.fastens).map((x) => [top(x.a), top(x.b)]);
913
940
  for (let grew = true; grew;) { grew = false; for (const [a, b] of links) { if (held.has(a) && !held.has(b)) { held.add(b); grew = true; } if (held.has(b) && !held.has(a)) { held.add(a); grew = true; } } }
914
941
  const placed = new Set(s.objects.filter((o) => !o.unplaced && o.role !== 'reference').map((o) => top(o.id)));
915
942
  const loose = ids.filter((id) => !held.has(id) && placed.has(id));
916
943
  if (loose.length) f('warn', `${loose.join(', ')} ${loose.length > 1 ? 'are' : 'is'} placed, but nothing holds ${loose.length > 1 ? 'them' : 'it'}: give ${loose.length > 1 ? 'each' : 'it'} a joint, or fasten it to what it sits on (pins, screws, a press) and say so with a fit that "fastens"`, `${loose.length} loose`, { code: 'assembly.loose', refs: { items: loose } });
917
944
  else f('pass', `every part turns or slides on a joint, or is fastened to the ${ids[0]}`, null, { code: 'assembly.held' });
945
+ // A fit that fastens holds two items as one, but only a joint or an anchor moves them: one fastened to a part a
946
+ // joint moves, and placed where it stands, stays behind in every pose and is left out of what that joint carries
947
+ // (one also fastened to what stays, as a servo to its stand with its arm fastened to the horn, is held there)
948
+ const moving = s.motion.joints.filter((j) => !j.at && j.type !== 'fixed'), across = (a, b) => moving.find((jj) => beyond(s.motion, jj, ids.indexOf(a)) !== beyond(s.motion, jj, ids.indexOf(b)));
949
+ const still = new Set([ids[0], ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]), ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id)]), same = links.filter(([a, b]) => ids.includes(a) && ids.includes(b) && !across(a, b));
950
+ for (let grew = true; grew;) { grew = false; for (const [a, b] of same) { if (still.has(a) && !still.has(b)) { still.add(b); grew = true; } if (still.has(b) && !still.has(a)) { still.add(a); grew = true; } } }
951
+ for (const x of s.fits.filter((q) => q.fastens)) {
952
+ const [a, b] = [top(x.a), top(x.b)], ia = ids.indexOf(a), ib = ids.indexOf(b);
953
+ if (ia < 0 || ib < 0) continue;
954
+ const j = across(a, b);
955
+ if (!j || (still.has(a) && still.has(b))) continue;
956
+ const [mover, left] = beyond(s.motion, j, ia) ? [a, b] : [b, a];
957
+ f('warn', `${left} is fastened to ${mover} (a fit that fastens), but only ${mover} moves on ${j.id}: ${left} is placed where it stands, so it stays there in every pose and its mass is left out of what ${j.id} carries (joint.moment). Place ${left} on ${mover} by an anchor or an address ("at": "${mover}.<anchor>")`,
958
+ `${left}: left behind by ${j.id}`, { code: 'assembly.fastened', refs: { items: [left, mover], joint: j.id } });
959
+ }
918
960
  }
919
961
  // Gears: each mesh's centre distance and contact ratio, said between the two axes (the rest by --sweep)
920
962
  for (const g of s.motion.meshes || []) {
@@ -933,6 +975,13 @@ export function checkAssembly(s) {
933
975
  }
934
976
  boughtFindings(s, f);
935
977
  beamFindings(s, f);
978
+ fittingFindings(s, f);
979
+ panelFindings(s, f);
980
+ serviceFindings(s, f);
981
+ guideFindings(s, f);
982
+ joinChecks(s, f);
983
+ slotNutChecks(s, f);
984
+ frameSquareChecks(s, f);
936
985
  massFinding(s, f);
937
986
  runningChecks(s, f, { axisOf, placeItems, jointValues, mul });
938
987
  if (s.wires?.length) wireChecks(s, f, { placeItems, jointValues, mul });
@@ -942,7 +991,7 @@ export function checkAssembly(s) {
942
991
  gripChecks(s, f);
943
992
  gaitChecks(s, f, { jointValues, placeItems, sweepOne: (v) => clashesOf(s.at(v), named) });
944
993
  taskChecks(s, f);
945
- orderChecks(s, f);
994
+ orderChecks(s, f, { frame: frameBuild });
946
995
  // Plates print everything: no references
947
996
  if (s.a.kind === 'plate') {
948
997
  const refs = s.objects.filter((o) => o.role === 'reference' && !o.unplaced); // an unplaced item only lends its numbers
@@ -992,20 +1041,24 @@ export function sweep(s, { joint, steps = 24, progress } = {}) {
992
1041
  for (const j of free) j.dofs.forEach(([lo, hi], d) => {
993
1042
  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]}` : ''}`;
994
1043
  const bad = []; // [value, what]
995
- for (let i = 0; i <= steps; i++) {
996
- const v = lo + ((hi - lo) * i) / steps, set = { ...base, [j.id]: base[j.id].map((x, k) => (k === d ? v : x)) };
1044
+ // a door with its latch shut: also tried just off shut, finer than a step, so a hit within the first degree is seen
1045
+ const held = (s.panels ?? []).find((p) => p.latch && p.joint === j.id && DOFS[j.type][d] === 'angle'), probe = held ? Math.min(PANEL_CHECK.latch_probe.value, (hi - lo) / steps) : 0;
1046
+ const values = [...Array(steps + 1).keys()].map((i) => lo + ((hi - lo) * i) / steps);
1047
+ if (probe > 0 && probe < (hi - lo) / steps) values.splice(1, 0, lo + probe);
1048
+ for (const [i, v] of values.entries()) {
1049
+ const set = { ...base, [j.id]: base[j.id].map((x, k) => (k === d ? v : x)) };
997
1050
  const t = s.at(Object.fromEntries(Object.entries(set).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow)));
998
1051
  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`)];
999
1052
  if (what.length) bad.push([v, what]);
1000
- progress?.({ stage: 'sweep', joint: j.id, step: i, steps });
1053
+ progress?.({ stage: 'sweep', joint: j.id, step: Math.min(i, steps), steps });
1001
1054
  }
1002
1055
  const ranges = []; // runs of steps in a row that collide
1003
1056
  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 }); }
1004
- const span = `${mm(lo)} to ${mm(hi)}${unit}`;
1005
- if (!ranges.length) f('pass', `sweep ${name}, ${span} in ${steps} steps: nothing collides`, `${name}: clear ${span}`, { code: 'sweep', values: { from: lo, to: hi, steps }, refs: { joint: name, collisions: [] } });
1006
- 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(' | ')}`,
1057
+ const span = `${mm(lo)} to ${mm(hi)}${unit}`, note = held ? ` (${held.latch} shut over ${held.id}: also tried ${mm(probe)}${unit} off shut)` : '';
1058
+ if (!ranges.length) f('pass', `sweep ${name}, ${span} in ${steps} steps${note}: nothing collides`, `${name}: clear ${span}`, { code: 'sweep', values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) }, refs: { joint: name, collisions: [], ...(held ? { latch: held.latch } : {}) } });
1059
+ else f('fail', `sweep ${name}, ${span} in ${steps} steps${note}: ${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(' | ')}`,
1007
1060
  `${name}: collides ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`,
1008
- { code: 'sweep', values: { from: lo, to: hi, steps }, refs: { joint: name, collisions: ranges.map((r) => ({ from: r.from, to: r.to, what: r.what })) } });
1061
+ { code: 'sweep', values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) }, refs: { joint: name, ...(held ? { latch: held.latch } : {}), collisions: ranges.map((r) => ({ from: r.from, to: r.to, what: r.what })) } });
1009
1062
  });
1010
1063
  saveOverlaps();
1011
1064
  return out;
package/lib/beams.mjs CHANGED
@@ -87,8 +87,8 @@ export function beamPlace(it, num) {
87
87
  export function beamBuilt(it, num, id, context = framesContext()) {
88
88
  const { model: m, length } = beamOf(it, num, context);
89
89
  const meta = { body: { label: `${m.profile.name} x ${mm(length)} mm` } };
90
- const parts = named({ body: beam(m) }, meta), link = named({ body: beam(m, { display: 'link' }) }, meta)[0];
91
- parts[0].collide = link.geometry; // (the overlap check measures the envelope: light, and a beam's slots hold nothing else)
90
+ const parts = named({ body: beam(m) }, meta), link = named({ body: beam(m, { display: 'link', tracks: true }) }, meta)[0];
91
+ parts[0].collide = link.geometry; // (the overlap check measures the envelope, light, less any V tracks: a V-wheel's rim runs in them, and a rim out of them hits the beam)
92
92
  const anchors = Object.fromEntries(Object.entries(m.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis, ref: a.ref }]));
93
93
  const values = { length, width: m.profile.width, height: m.profile.height, area: m.area, ...(m.mass != null ? { mass: m.mass } : {}) };
94
94
  const entries = Object.entries(m.profile.figures).filter(([, f]) => typeof f?.value === 'number').map(([k, f]) => ({ name: `${m.profile.name}.${k}`, value: f.value, unit: f.unit, rule: f.rule, kind: f.kind, source: f.source, checked: f.checked, set: m.profile.name }));
package/lib/bought.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // Bought parts in assemblies: a bearing, a switch, a driver, a board or a supply named by its rule set, drawn from the
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
- return { parts: { body: box(w, d, t) }, anchors: { centre: z([0, 0, t / 2]), top: z([0, 0, t]), bottom: z([0, 0, 0]), ...sockets } };
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
- 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 }])) };
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, machine settings).
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 { build: { list, wires, plates, order, machine, beams } };
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/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, 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 })
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,6 +92,12 @@ 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');