@rulecad/cad 0.7.89 → 0.7.97

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/fittings.mjs CHANGED
@@ -76,14 +76,19 @@ export function plasticNamed(raw, where = 'the project') {
76
76
  if (['pla', 'petg'].includes(m)) return m;
77
77
  let set = null; try { set = peekRuleSet(m); } catch {}
78
78
  const lacks = ['strength', 'modulus', 'density'].filter((k) => !(typeof set?.rules?.[k]?.value === 'number'));
79
- if (set && !lacks.length) return set;
80
79
  const have = plastics().join(', ');
80
+ if (set && !lacks.length && rubber(set.rules)) throw new Error(`${where}: its material is ${JSON.stringify(raw)}, a rubber (its strength over its modulus is ${(set.rules.strength.value / set.rules.modulus.value).toFixed(2)}, a strain far past where its stiffness holds), and printed fittings are sized with sums for a stiff plastic that do not hold for it. Set the material to one of ${have}`);
81
+ if (set && !lacks.length) return set;
81
82
  throw new Error(`${where}: its material is ${JSON.stringify(raw)}, and printed fittings are sized from their plastic's strength, modulus and density: ${set ? `rules/${m}.json gives no ${lacks.join(', ')}` : `the kit and this workspace have rule sets for ${have}, and there is no rules/${m}.json`}. Give rules/${m}.json with all three, or set the material to one of ${have}`);
82
83
  }
83
84
 
85
+ // A rubber (TPU): its strength over its modulus, the strain where a stiff plastic yields, is past 0.5. Its stiffness
86
+ // holds only at small strains and it never yields as a plastic does, so the fittings' sums are not for it
87
+ const rubber = (r) => r.strength.value / r.modulus.value > 0.5;
88
+
84
89
  /**
85
90
  * The plastics a project can name: the rule sets (the workspace's rules/, then the kit's) that give strength, modulus,
86
- * density and modulus_z, the modulus across a print's layers, which only a printed plastic's set gives.
91
+ * density and modulus_z, the modulus across a print's layers, which only a printed plastic's set gives; a rubber's is left out.
87
92
  * @returns {string[]} their names, sorted
88
93
  */
89
94
  export function plastics() {
@@ -92,7 +97,7 @@ export function plastics() {
92
97
  let files = []; try { files = fs.readdirSync(d).filter((f) => f.endsWith('.json')); } catch { continue; }
93
98
  for (const f of files) {
94
99
  let r; try { r = JSON.parse(fs.readFileSync(path.join(d, f), 'utf8')).rules; } catch { continue; }
95
- if (['strength', 'modulus', 'density', 'modulus_z'].every((k) => typeof r?.[k]?.value === 'number')) out.add(f.slice(0, -5));
100
+ if (['strength', 'modulus', 'density', 'modulus_z'].every((k) => typeof r?.[k]?.value === 'number') && !rubber(r)) out.add(f.slice(0, -5));
96
101
  }
97
102
  }
98
103
  return [...out].sort();
package/lib/machine.mjs CHANGED
@@ -22,14 +22,45 @@ function axisOf(s, id) {
22
22
  }
23
23
 
24
24
  /** The slots of a CNC shield each motor is wired to, by motor item: from a wire "<motor>.<anchor>" to "<item>.X" (X, Y, Z or A). */
25
- export function shieldSlots(a) {
26
- const out = {};
27
- for (const w of a.wires || []) { const [from, to] = [String(w.from), String(w.to)], m = /^[^.]+\.([XYZA])$/.exec(to); if (m) out[from.split('.')[0]] = m[1]; }
28
- return out;
29
- }
25
+ export function shieldSlots(a) { return slotsOf(a, CONTROLLERS['cnc-shield-v3']); }
30
26
  /** The step and direction slots of the streamer (arm.ino on a CNC Shield V3), in its axis order: axis 0 on X, 1 on Y, 2 on Z. */
31
27
  export const STREAMER_SLOTS = ['X', 'Y', 'Z'];
32
28
 
29
+ /** The boards the streamer runs on, by the bought part that is the machine's controller: its build (board, as send.mjs and
30
+ * scripts/firmware.mjs name it), its step and direction slots in its axis order, the anchor a wire ends on for each, and
31
+ * how a finding names them. The Mega's slots S0 to S7 are its pins for axes 0 to 7 (arduino-mega-2560's rules). */
32
+ export const CONTROLLERS = {
33
+ 'cnc-shield-v3': { board: 'uno', title: 'an Uno under a CNC Shield V3', of: "the shield's", any: "a shield's slot", slots: STREAMER_SLOTS, wired: /^[^.]+\.([XYZA])$/ },
34
+ 'arduino-mega-2560': { board: 'mega', title: 'a Mega 2560', of: "the Mega's", any: "a slot of the Mega", slots: ['S0', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7'], wired: /^[^.]+\.(S[0-7])$/ },
35
+ };
36
+
37
+ /** The machine's controller: the bought board in its assembly that the streamer runs on, or the Uno under a CNC shield where
38
+ * it has none (as every machine had before the Mega). Two different ones are refused by name.
39
+ * @param {object} a the assembly's JSON @returns {{ set: string, item: string | null, board: string, title: string, of: string, any: string, slots: string[], wired: RegExp }} */
40
+ export function controllerOf(a) {
41
+ const found = (a.items || []).filter((it) => typeof it.bought === 'string' && CONTROLLERS[it.bought]);
42
+ if (new Set(found.map((it) => it.bought)).size > 1) throw new Error(`items ${found.map((it) => `${it.id} (${it.bought})`).join(', ')}: a machine streams through one controller, ${Object.keys(CONTROLLERS).join(' or ')}`);
43
+ const set = found[0]?.bought ?? 'cnc-shield-v3';
44
+ return { set, item: found[0]?.id ?? null, ...CONTROLLERS[set] };
45
+ }
46
+
47
+ /** The controller's slot each motor is wired to, by motor item: a wire from "<motor>.<anchor>" to "<board>.<slot>" (a CNC
48
+ * shield's slot), or a signal wire to the slot from the motor's driver (its "driver" item) or from the board its own wire
49
+ * ends on (an external driver's breakout: the motor's wire to it, its STEP and DIR on to the controller).
50
+ * @param {object} a the assembly's JSON @param {{ wired: RegExp }} c a controller (CONTROLLERS) */
51
+ export function slotsOf(a, c) {
52
+ const out = {}, motors = new Set((a.items || []).filter((it) => it.motor).map((it) => it.id)), top = (x) => String(x).split('.')[0];
53
+ const driverOf = Object.fromEntries((a.items || []).filter((it) => it.motor?.driver).map((it) => [it.motor.driver, it.id]));
54
+ for (const w of a.wires || []) for (const [m, o] of [[top(w.from), top(w.to)], [top(w.to), top(w.from)]]) if (motors.has(m) && !motors.has(o) && !(o in driverOf)) driverOf[o] = m;
55
+ for (const w of a.wires || []) {
56
+ for (const [from, to] of [[String(w.from), String(w.to)], [String(w.to), String(w.from)]]) {
57
+ const m = c.wired.exec(to), id = from.split('.')[0];
58
+ if (m && from.includes('.')) out[driverOf[id] ?? id] = m[1];
59
+ }
60
+ }
61
+ return out;
62
+ }
63
+
33
64
  /** The machine as plain data. Every figure's origin is said in _why, by the name of the figure. A machine with a gait and no
34
65
  * task is its legs: an axis for each joint a motor turns, in the order the shield's slots are wired. @param {object} s a built assembly with a task or a gait */
35
66
  export function machineOf(s) {
@@ -39,22 +70,26 @@ export function machineOf(s) {
39
70
  const axes = c.names.map((id) => axisOf(s, id));
40
71
  const kinematics = c.names.length === 2 && motion.joints.filter((j) => c.names.includes(j.id)).every((j) => j.type === 'revolute') ? 'scara' : motion.joints.filter((j) => c.names.includes(j.id)).every((j) => j.type === 'prismatic') ? 'cartesian' : 'serial';
41
72
  const pen = s.a.task.pen ?? null;
42
- return { format: 'rulecad.machine/1', name: `${s.project}/${s.name}`, kinematics, tool: s.task.tool, elbow: sample(s).elbow, axes, task: { sheet: s.a.task.sheet ?? null, region: s.a.task.region ?? null, volume: s.a.task.volume ?? null, speed: s.task.speed, accuracy: s.task.accuracy, accel: s.task.accel ?? 500, ...(s.task.blockTime ? { blockTime: s.task.blockTime } : {}) }, ...(pen ? { pen } : {}) };
73
+ return { format: 'rulecad.machine/1', name: `${s.project}/${s.name}`, kinematics, tool: s.task.tool, elbow: sample(s).elbow, axes, controller: controllerSummary(controllerOf(s.a)), task: { sheet: s.a.task.sheet ?? null, region: s.a.task.region ?? null, volume: s.a.task.volume ?? null, speed: s.task.speed, accuracy: s.task.accuracy, accel: s.task.accel ?? 500, ...(s.task.blockTime ? { blockTime: s.task.blockTime } : {}) }, ...(pen ? { pen } : {}) };
43
74
  }
44
75
 
76
+ // The controller as the machine description carries it: its build, and the bought item it is
77
+ const controllerSummary = (c) => ({ board: c.board, set: c.set, item: c.item, slots: c.slots });
78
+
45
79
  function gaitMachineOf(s) {
46
- const seq = gaitSequence(s), slots = shieldSlots(s.a);
80
+ const seq = gaitSequence(s), c = controllerOf(s.a), slots = slotsOf(s.a, c);
47
81
  let axes = seq.names.map((id) => { const a = axisOf(s, id); return { ...a, ...(slots[a.motor] ? { slot: slots[a.motor] } : {}) }; });
48
- if (axes.every((a) => STREAMER_SLOTS.includes(a.slot))) axes = [...axes].sort((a, b) => STREAMER_SLOTS.indexOf(a.slot) - STREAMER_SLOTS.indexOf(b.slot));
82
+ if (axes.every((a) => c.slots.includes(a.slot))) axes = [...axes].sort((a, b) => c.slots.indexOf(a.slot) - c.slots.indexOf(b.slot));
49
83
  const g = s.gait, pattern = typeof s.a.gait.pattern === 'string' ? s.a.gait.pattern : `duty ${s.a.gait.pattern?.duty}`;
50
- return { format: 'rulecad.machine/1', name: `${s.project}/${s.name}`, kinematics: 'legged', tool: null, axes, task: null,
84
+ return { format: 'rulecad.machine/1', name: `${s.project}/${s.name}`, kinematics: 'legged', tool: null, axes, task: null, controller: controllerSummary(c),
51
85
  gait: { legs: g.legs.map((l) => l.name), pattern, period: g.period, stride: g.stride, lift: g.lift, height: g.height, frames: seq.q.length } };
52
86
  }
53
87
 
54
88
  /**
55
89
  * A gait as a step file: its cycle played for some cycles from a pose of the assembly and back to it, every leg's joints
56
90
  * in the same blocks. Findings say how long a cycle takes on the motors against the gait's period, and whether the
57
- * streamer can take the file: three axes at most, each on the shield's slot of its own number.
91
+ * streamer can take the file: as many axes as its controller has slots (three on an Uno under a CNC shield, eight on a
92
+ * Mega 2560), each on the slot of its own number.
58
93
  * @param {object} s a built assembly with a gait @param {{ cycles?: number, period?: number, from?: string }} [o] from: a pose's name (default the pose the assembly shows)
59
94
  */
60
95
  export function plotGait(s, { cycles = 3, period, from } = {}) {
@@ -68,11 +103,12 @@ export function plotGait(s, { cycles = 3, period, from } = {}) {
68
103
  if (poseName && !start) findings.push({ level: 'info', text: `the pose "${poseName}" does not set ${names.filter((n) => !num(pose?.[n])).join(', ')}, so the file starts and ends at the cycle's first frame`, code: 'gait.from', values: {} });
69
104
  const r = gaitBlocks(ordered, { axes: m.axes.map((a) => ({ name: a.name, stepsPerUnit: a.stepsPerUnit, maxRate: a.maxRate, unit: a.unit })), cycles, ...(period != null ? { period } : {}), ...(start ? { from: start } : {}) });
70
105
  findings.push(...r.findings);
71
- // the streamer: three axes, axis k on the shield's slot X, Y or Z in that order
72
- if (names.length > STREAMER_SLOTS.length) findings.push({ level: 'warn', text: `${names.length} axes, and the streamer steps ${STREAMER_SLOTS.length} (an Uno under a CNC Shield V3): the file is written, and send.mjs refuses it`, code: 'stream.axes', values: { axes: names.length, streamer: STREAMER_SLOTS.length } });
106
+ // the streamer: as many axes as the controller has slots, axis k on its slot k (the shield's X, Y, Z; the Mega's S0 to S7)
107
+ const c = CONTROLLERS[m.controller.set], slots = c.slots;
108
+ if (names.length > slots.length) findings.push({ level: 'warn', text: `${names.length} axes, and the streamer steps ${slots.length} on ${c.title}: the file is written, and send.mjs refuses it${c.board === 'uno' ? ' (an arduino-mega-2560 in the assembly streams up to 8)' : ''}`, code: 'stream.axes', values: { axes: names.length, streamer: slots.length } });
73
109
  else for (const [k, a] of m.axes.entries()) {
74
- if (!a.slot) findings.push({ level: 'info', text: `${a.name}'s motor ${a.motor} has no wire to a shield's slot: the streamer steps it as axis ${k}, on ${STREAMER_SLOTS[k]}`, code: 'stream.wiring', refs: { item: a.motor } });
75
- else if (a.slot !== STREAMER_SLOTS[k]) findings.push({ level: 'fail', text: `${a.name}'s motor ${a.motor} is wired to the shield's ${a.slot}, and the streamer steps axis ${k} on ${STREAMER_SLOTS[k]}`, code: 'stream.wiring', refs: { item: a.motor } });
110
+ if (!a.slot) findings.push({ level: 'info', text: `${a.name}'s motor ${a.motor} has no wire to ${c.any}: the streamer steps it as axis ${k}, on ${slots[k]}`, code: 'stream.wiring', refs: { item: a.motor } });
111
+ else if (a.slot !== slots[k]) findings.push({ level: 'fail', text: `${a.name}'s motor ${a.motor} is wired to ${c.of} ${a.slot}, and the streamer steps axis ${k} on ${slots[k]}`, code: 'stream.wiring', refs: { item: a.motor } });
76
112
  }
77
113
  const n = r.blocks.length;
78
114
  findings.push({ level: 'info', text: `${cycles} cycle${cycles === 1 ? '' : 's'} of the gait (${m.gait.pattern}) in ${n} blocks, ${n3(r.time, 1)} s${start ? `, from the pose "${poseName}" and back to it` : ''}`, code: 'plot.time', values: { time: r.time, cycles, blocks: n } });
package/lib/mesh.mjs CHANGED
@@ -3,6 +3,7 @@
3
3
  // readMesh(file) -> triangles
4
4
  // profiles(tris, axis) -> the stretches along an axis where the cross-section stays the same, each with its outline
5
5
  // spans(tris, axis, at) -> where a line along an axis is inside the solid
6
+ // slabLevels(tris, lo, hi, step) -> heights whose sections together cover what lies between z lo and hi
6
7
  // align(moving, fixed) -> the turn and shift that best lays moving over fixed
7
8
  // deviation(from, to) -> how far points on one surface are from the other, signed (+ outside, - inside)
8
9
  import fs from 'node:fs';
@@ -140,6 +141,29 @@ export function section(tris, axis, v) {
140
141
  return segs;
141
142
  }
142
143
 
144
+ // Where to take sections along z so that, together, they hold all of a solid that lies within the slab from lo to hi
145
+ // (open: a part only touching a face of it is outside) to half of `step`, the grid's cell. They are no more than half a
146
+ // step apart up the slab, the first and last just inside its faces, so a feature as thick as half a cell is caught as
147
+ // a cell of the grid catches it. Where a face leans, the outline it makes moves across as the section rises, by its
148
+ // lean (its normal's z over its normal across) for each mm up, so a stretch is cut finer until no face's outline moves
149
+ // more than half a step from one section to the next. A face lying flat moves no outline: the sections either side of
150
+ // it hold what it covers.
151
+ export function slabLevels(tris, lo, hi, step) {
152
+ const eps = 1e-5, a = lo + eps, b = hi - eps, n0 = Math.max(1, Math.ceil((b - a) / (step / 2))), gap = (b - a) / n0, need = new Float64Array(n0);
153
+ for (const [p, q, r] of tris) {
154
+ const z0 = Math.max(a, Math.min(p[2], q[2], r[2])), z1 = Math.min(b, Math.max(p[2], q[2], r[2]));
155
+ if (!(z1 > z0)) continue;
156
+ const u = [q[0] - p[0], q[1] - p[1], q[2] - p[2]], v = [r[0] - p[0], r[1] - p[1], r[2] - p[2]];
157
+ const nx = u[1] * v[2] - u[2] * v[1], ny = u[2] * v[0] - u[0] * v[2], nz = u[0] * v[1] - u[1] * v[0], across = Math.hypot(nx, ny);
158
+ if (!(across > 1e-12)) continue;
159
+ const lean = Math.abs(nz) / across;
160
+ for (let i = Math.max(0, Math.floor((z0 - a) / gap)); i < n0 && a + i * gap < z1; i++) need[i] = Math.max(need[i], lean * (Math.min(z1, a + (i + 1) * gap) - Math.max(z0, a + i * gap)));
161
+ }
162
+ const out = [a];
163
+ for (let i = 0; i < n0; i++) { const m = Math.max(1, Math.ceil((2 * need[i]) / step)); for (let k = 1; k <= m; k++) out.push(a + gap * (i + k / m)); }
164
+ return out;
165
+ }
166
+
143
167
  // Where a line through a section, at height h, is inside: [[from, to], …] across
144
168
  export function crossings(segs, h) {
145
169
  const xs = [];
package/lib/optimise.mjs CHANGED
@@ -12,9 +12,10 @@ import { host, readJson } from './host.mjs';
12
12
  import { paths, printerOf } from './workspace.mjs';
13
13
  import { resolve, evaluate } from './rules.mjs';
14
14
  import { located } from './errors.mjs';
15
- import { discretise, optimise, outlines, surface, area, bounds, resultant, printable, refine, despike, reduce, undercuts, voids, grey } from '@rulecad/topopt';
15
+ import { discretise, optimise, outlines, surface, area, bounds, resultant, printable, refine, despike, reduce, undercuts, voids, grey, featureCells, thin } from '@rulecad/topopt';
16
16
  import { islands } from '@rulecad/printcheck';
17
- import { turn } from '@rulecad/model-link';
17
+ import { turn, mul, inv, placeItems, jointValues } from '@rulecad/model-link';
18
+ import { section, loops, slabLevels } from './mesh.mjs';
18
19
  import { threadsBackend } from '@rulecad/fea/threads'; // the solver's products shared over the machine's cores
19
20
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
20
21
 
@@ -102,16 +103,131 @@ async function readOne(project, ref, link) {
102
103
  }
103
104
  return anchors.get(ref);
104
105
  };
106
+ // The assembly the problem is placed in ("in": { "assembly", "item", "pose", "z" }): its coordinates are that item's
107
+ // own there, as the item's design draws the result. Built once, in its pose (default the one it shows), for its
108
+ // joints and its moving parts; the item itself, and any other made from this very problem, is drawn without a result
109
+ // (its problem variables set to none), since the result can't be needed to place the problem it comes from.
110
+ const fileName = path.basename(file);
111
+ let placing = null;
112
+ const inAssembly = (what) => {
113
+ if (!p.in) throw new Error(`${fileName}: ${what} needs the problem placed in an assembly: "in": { "assembly": "<name>", "item": "<the item it is drawn in>" }`);
114
+ return (placing ||= (async () => {
115
+ const { buildAssembly, assemblyPath } = await import('./assembly.mjs'), { locate, readObject } = await import('./design.mjs');
116
+ const ref = `${project}/${p.in.assembly}`, overrides = {};
117
+ if (!host.exists(assemblyPath(ref))) throw new Error(`${fileName}: no assembly "${p.in.assembly}" to place the problem in (projects/${project}/assemblies/${p.in.assembly}.json)`);
118
+ for (const it of readJson(assemblyPath(ref)).items || []) if (typeof it.object === 'string') {
119
+ let vars = {};
120
+ try { vars = readObject(locate(`${project}/${it.object.split(/[:@]/)[0]}`)).variables || {}; } catch { continue; }
121
+ for (const [k, v] of Object.entries(vars)) if (v.type === 'problem' && (it.id === p.in.item || String(it.set?.[k] ?? v.value).split(':')[0] === name)) (overrides[it.id] ||= {})[k] = 'none';
122
+ }
123
+ const chain = reading.getStore();
124
+ const s = await reading.run([...chain.slice(0, -1), { ...link, object: `the assembly ${p.in.assembly}` }], () => buildAssembly(ref, [], overrides, { pose: p.in.pose, onePose: true }));
125
+ const k = s.motion.items.findIndex((x) => x[0] === p.in.item);
126
+ if (k < 0) throw new Error(`${fileName}: ${p.in.assembly} has no item "${p.in.item}" (items: ${s.motion.items.map((x) => x[0]).join(', ')})`);
127
+ return { s, k, W0: placeItems(s.motion, s.jointValues) };
128
+ })());
129
+ };
130
+ // A joint of that assembly, where it is in the item's frame: the joint's anchor on the item when the item is one of
131
+ // its ends (the same in every pose), else the parent's anchor as the pose places it. Its axis is the anchor's z.
132
+ const joints = new Map(), clean = (c) => (Math.abs(c) < 1e-9 ? 0 : round(c, 9));
133
+ const jointAt = async (id) => {
134
+ if (!joints.has(id)) {
135
+ const { s, k, W0 } = await inAssembly(`the joint "${id}"`), j = s.motion.joints.find((x) => x.id === id);
136
+ if (!j) throw new Error(`${fileName}: ${p.in.assembly} has no joint "${id}" (joints: ${s.motion.joints.map((x) => x.id).join(', ') || 'none'})`);
137
+ const F = j.child === k ? j.b : j.parent === k ? j.a : mul(inv(W0[k]), j.parent < 0 ? j.a : mul(W0[j.parent], j.a));
138
+ joints.set(id, { joint: id, at: [F[3], F[7], F[11]].map(clean), axis: [F[2], F[6], F[10]].map(clean) });
139
+ }
140
+ return joints.get(id);
141
+ };
142
+ // A part of the assembly swept through a joint's range, as regions to keep clear: the part at each step, in the
143
+ // item's frame (the other joints held at the pose). Steps by default so no point of it moves more than half a cell
144
+ // between two (its travel measured in 32 pieces of the range). In a flat problem, each step is all of the part that
145
+ // lies within the plate's thickness (about in.z, default half its thickness, a plate drawn up from z 0): its sections
146
+ // at heights close enough that, together, they cover it to half a cell, each distinct one a region. A part dipping
147
+ // into the plate's top or bottom is kept clear; one only passing over or under it, or touching a face, is not.
148
+ const sweeps = [];
149
+ const swept = async (r) => {
150
+ const { s, k, W0 } = await inAssembly(`the sweep of "${r.sweep}"`), item = p.in.item, cell = ev(p.cell);
151
+ const isNamed = (q, n) => q.name === n || q.leaf === n || q.item === n || q.name.startsWith(`${n}.`), moving = s.parts.filter((q) => isNamed(q, r.sweep));
152
+ if (!moving.length) throw new Error(`${fileName}: ${p.in.assembly} has no item or part "${r.sweep}" to sweep (items: ${s.motion.items.map((x) => x[0]).join(', ')})`);
153
+ if (moving.some((q) => (q.moves ?? q.item) === item)) throw new Error(`${fileName}: "${r.sweep}" is ${item} itself, the item this problem is in: sweep a part that moves against it`);
154
+ const free = s.motion.joints.filter((j) => !j.follow && j.dofs.length), through = [r.through ?? []].flat();
155
+ if (!through.length) throw new Error(`${fileName}: the sweep of "${r.sweep}" needs the joint it moves through: "through": "<joint>" (joints: ${free.map((j) => j.id).join(', ') || 'none'})`);
156
+ const apply = (M, [x, y, z]) => [M[0] * x + M[1] * y + M[2] * z + M[3], M[4] * x + M[5] * y + M[6] * z + M[7], M[8] * x + M[9] * y + M[10] * z + M[11]];
157
+ const idx = moving.map((q) => s.motion.items.findIndex((x) => x[0] === (q.moves ?? q.item)));
158
+ const local = moving.map((q, i) => { const L = inv(W0[idx[i]]); return q.triangles.map((t) => t.map((v) => apply(L, v))); }); // each in its own item's frame
159
+ const sample = local.map((tris) => { const v = tris.flat(), n = Math.ceil(v.length / 400); return v.filter((_, i) => i % n === 0); }); // (no more than about 400 points a part)
160
+ const held = Object.fromEntries(Object.entries(s.jointValues).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow));
161
+ const z = flat ? (p.in.z != null ? ev(p.in.z) : ev(p.thickness) / 2) : null, zlo = flat ? z - ev(p.thickness) / 2 : null, zhi = flat ? z + ev(p.thickness) / 2 : null, out = [];
162
+ for (const id of through) {
163
+ const j = free.find((x) => x.id === id);
164
+ if (!j) throw new Error(`${fileName}: ${p.in.assembly} has no joint "${id}" that moves on its own to sweep "${r.sweep}" through (joints: ${free.map((x) => x.id).join(', ') || 'none'})`);
165
+ j.dofs.forEach(([lo, hi], d) => {
166
+ const at = (v) => { const W = placeItems(s.motion, jointValues(s.motion, { ...held, [id]: held[id].map((x, i) => (i === d ? v : x)) })), T = inv(W[k]); return idx.map((m) => mul(T, W[m])); };
167
+ let travel = 0, before = at(lo).map((M, m) => sample[m].map((v) => apply(M, v)));
168
+ for (let i = 1; i <= 32; i++) {
169
+ const now = at(lo + ((hi - lo) * i) / 32).map((M, m) => sample[m].map((v) => apply(M, v)));
170
+ travel += Math.max(0, ...now.flatMap((pts, m) => pts.map((q, n) => Math.hypot(...q.map((c, a) => c - before[m][n][a])))));
171
+ before = now;
172
+ }
173
+ const what = `${id}${j.dofs.length > 1 ? ` (its value ${d + 1})` : ''}`;
174
+ if (!(travel > 1e-6)) throw new Error(`${fileName}: ${what} doesn't move "${r.sweep}" against ${item} (from ${round(lo)} to ${round(hi)}): sweep it through a joint between them`);
175
+ const steps = r.steps ?? Math.max(1, Math.ceil((2 * travel) / cell));
176
+ if (r.steps == null && steps > 360) throw new Error(`${fileName}: sweeping "${r.sweep}" through ${what} would take ${steps} steps on ${cell} mm cells (its farthest point travels ${round(travel, 1)} mm): give the sweep its steps, or larger cells`);
177
+ let made = 0;
178
+ for (let i = 0; i <= steps; i++) {
179
+ const v = lo + ((hi - lo) * i) / steps, Ms = at(v);
180
+ for (const [m, tris] of local.entries()) {
181
+ const moved = tris.map((t) => t.map((q) => apply(Ms[m], q).map(clean)));
182
+ if (!flat) { out.push({ triangles: moved, sweep: r.sweep, joint: id, value: round(v, 6) }); made++; continue; }
183
+ // Each section's outlines, each a ring turned solid on its left (an outline counter-clockwise, a hole in it
184
+ // clockwise), for the design to cut exactly (rings); and for the solver one polygon of them all, each closed and
185
+ // back to the first one's start, so a point is inside where it is inside an odd number of them (a hole in the
186
+ // part stays open) and the joins cancel out. A point within 0.001 mm of the line through its neighbours (where a face's diagonal is
187
+ // cut, or a boolean left a sliver) is dropped, and a section whose corners all lie within 0.01 mm of one already taken at this step is left out.
188
+ const same = (a, b) => Math.abs(a[0] - b[0]) < 1e-9 && Math.abs(a[1] - b[1]) < 1e-9, kept = [];
189
+ const off = (q, a, b) => { const d = [b[0] - a[0], b[1] - a[1]], L = Math.hypot(...d); return L < 1e-12 ? Math.hypot(q[0] - a[0], q[1] - a[1]) : Math.abs(d[0] * (q[1] - a[1]) - d[1] * (q[0] - a[0])) / L; };
190
+ const straight = (ring) => { const l = [...ring]; for (let n = 0; n < l.length && l.length > 3;) if (off(l[n], l[(n + l.length - 1) % l.length], l[(n + 1) % l.length]) < 1e-3) { l.splice(n, 1); n = Math.max(0, n - 1); } else n++; return l; };
191
+ for (const h of slabLevels(moved, zlo, zhi, cell)) {
192
+ const rings = loops(section(moved, 2, h)).map((l) => straight((same(l[0], l.at(-1)) ? l.slice(0, -1) : l).map((q) => q.map(clean)))).filter((l) => l.length >= 3);
193
+ if (!rings.length) continue;
194
+ const within = (q, P) => { let c = false; for (let a = 0, b = P.length - 1; a < P.length; b = a++) if ((P[a][1] > q[1]) !== (P[b][1] > q[1]) && q[0] < ((P[b][0] - P[a][0]) * (q[1] - P[a][1])) / (P[b][1] - P[a][1]) + P[a][0]) c = !c; return c; };
195
+ const turned = rings.map((l, n) => {
196
+ const depth = rings.filter((o, m) => m !== n && within(l[0], o)).length, ccw = l.reduce((t, q, a) => t + q[0] * l[(a + 1) % l.length][1] - l[(a + 1) % l.length][0] * q[1], 0) > 0;
197
+ return ccw === (depth % 2 === 0) ? l : [...l].reverse();
198
+ });
199
+ const near = (l, o) => l.length === o.length && l.every((q) => o.some((w) => Math.hypot(q[0] - w[0], q[1] - w[1]) < 0.01));
200
+ if (kept.some((k) => k.length === turned.length && turned.every((l) => k.some((o) => near(l, o))))) continue;
201
+ kept.push(turned);
202
+ const start = turned[0][0], points = turned.flatMap((l, n) => [...l, l[0], ...(n ? [start] : [])]);
203
+ out.push({ points, rings: turned, sweep: r.sweep, joint: id, value: round(v, 6) }); made++;
204
+ }
205
+ }
206
+ }
207
+ sweeps.push({ sweep: r.sweep, through: what, from: round(lo, 6), to: round(hi, 6), steps, regions: made });
208
+ });
209
+ }
210
+ if (!out.length) throw new Error(`${fileName}: "${r.sweep}" never reaches into the plate (z ${round(zlo)} to ${round(zhi)} mm in ${item}) through ${through.join(', ')}: nothing to keep clear there (set in.z, the plate's middle, if it lies elsewhere)`);
211
+ return out;
212
+ };
105
213
  // The build direction: a direction ('+z'), or a variable holding one
106
214
  const overhang = p.overhang ? (typeof values[p.overhang] === 'string' ? values[p.overhang] : p.overhang) : null;
215
+ // The sides it is milled from, and a one-way mould's draw, likewise: or a variable holding them ('+z', '+z +x', or
216
+ // 'none': not milled, not cast), so a variant can switch the process
217
+ const named = (v) => (typeof v === 'string' && typeof values[v] === 'string' ? values[v] : v);
218
+ const millSides = (() => { const v = named(p.mill); if (typeof v !== 'string') return v; const list = v.trim().split(/[\s,]+/).filter(Boolean); return v === 'none' ? null : list.length > 1 ? list : v; })();
219
+ const castWay = (() => { const v = named(p.cast); return v === 'none' ? null : v; })();
107
220
  // A teardrop's point: a direction, or up or down the build direction (+z, as drawn, when it's free)
108
221
  const point = (t) => { const up = overhang && overhang !== 'none' ? overhang : '+z'; return t === 'up' ? up : t === 'down' ? (up[0] === '-' ? '+' : '-') + up[1] : t; };
109
222
  const region = async (r) => {
110
- if (r.anchor) { // at an anchor: its place (x and y in a flat problem), and a cylinder along the anchor's axis unless it names one
111
- if (r.at) throw new Error(`${path.basename(file)}: a region at an anchor ("${r.anchor}") takes no at: the anchor places it`);
112
- const a = await anchor(r.anchor), along = a.axis.map((c) => Math.abs(c) > 1e-9);
113
- if (r.length != null && !r.axis && along.filter(Boolean).length !== 1) throw new Error(`${path.basename(file)}: the anchor "${r.anchor}" points along [${a.axis.map((c) => round(c, 3)).join(', ')}], not along x, y or z: give the cylinder an axis`);
114
- return region({ ...r, anchor: undefined, at: flat ? a.at.slice(0, 2) : a.at, ...(r.length != null && !r.axis ? { axis: 'xyz'[along.indexOf(true)] } : {}) });
223
+ if (r.sweep != null) throw new Error(`${path.basename(file)}: a swept part ("${r.sweep}") is a region to keep clear: put it under avoid`);
224
+ if (r.anchor || r.joint) { // at an anchor, or an assembly's joint: its place (x and y in a flat problem), and a cylinder along its axis unless it names one
225
+ const kind = r.anchor ? 'anchor' : 'joint', named = `the ${kind} "${r.anchor || r.joint}"`;
226
+ if (r.anchor && r.joint) throw new Error(`${path.basename(file)}: a region is at an anchor or at a joint, not both ("${r.anchor}", "${r.joint}")`);
227
+ if (r.at) throw new Error(`${path.basename(file)}: a region at an ${kind} ("${r.anchor || r.joint}") takes no at: the ${kind} places it`);
228
+ const a = r.anchor ? await anchor(r.anchor) : await jointAt(r.joint), along = a.axis.map((c) => Math.abs(c) > 1e-9);
229
+ if (r.length != null && !r.axis && along.filter(Boolean).length !== 1) throw new Error(`${path.basename(file)}: ${named} points along [${a.axis.map((c) => round(c, 3)).join(', ')}], not along x, y or z: give the cylinder an axis`);
230
+ return region({ ...r, anchor: undefined, joint: undefined, at: flat ? a.at.slice(0, 2) : a.at, ...(r.length != null && !r.axis ? { axis: 'xyz'[along.indexOf(true)] } : {}) });
115
231
  }
116
232
  if (r.part) { // with where it is (its box's centre), for a load's or support's resultant
117
233
  const triangles = await part(r.part), lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
@@ -132,16 +248,20 @@ async function readOne(project, ref, link) {
132
248
  const printer = printerOf(project), line = printer ? resolve({ uses: [printer] }).values[printer]?.line : null, lines = typeof line === 'number' ? 2 * line : 0;
133
249
  const space = await regions(p.space), dim = flat ? 2 : space[0].triangles || space[0].length != null || (space[0].size || space[0].at)?.length === 3 ? 3 : 2;
134
250
  const problem = {
135
- space, keep: await regions(p.keep), avoid: await regions(p.avoid),
251
+ space, keep: await regions(p.keep), avoid: (await Promise.all([p.avoid || []].flat().map(async (r) => (r.sweep != null ? swept(r) : [await region(r)])))).flat(),
136
252
  supports: await Promise.all(p.supports.map(async (s) => ({ ...(await region(s)), fix: s.fix || 'xyz'.slice(0, dim) }))),
137
253
  loads: await Promise.all(p.loads.map(async (l) => ({ ...(await region(l)), force: pt(l.force), case: l.case || 'load' }))),
138
254
  cases: Object.fromEntries(Object.entries(p.cases || {}).map(([k, w]) => [k, ev(w)])),
139
- material: { E: m.modulus, nu: m.poisson }, ...(dim === 2 ? { thickness: ev(p.thickness) } : {}), cell: ev(p.cell), ...(p.volume != null ? { volume: ev(p.volume) } : {}), ...(p.stress != null ? { stress: ev(p.stress) } : {}), ...(p.strain != null ? { strain: ev(p.strain) } : {}),
255
+ material: { E: m.modulus, nu: m.poisson }, ...(dim === 2 ? { thickness: ev(p.thickness) } : {}), cell: ev(p.cell), ...(p.volume != null ? { volume: ev(p.volume) } : {}), ...(p.stress != null ? { stress: ev(p.stress) } : {}), ...(p.strain != null ? { strain: ev(p.strain) } : {}), ...(p.robust ? { robust: true } : {}),
140
256
  ...(p.filter != null ? { filter: ev(p.filter) } : lines > ev(p.cell) * 1.5 ? { filter: lines } : {}), ...(p.penal != null ? { penal: ev(p.penal) } : {}),
141
257
  ...(p.projection != null ? { projection: p.projection } : {}), ...(p.steps != null ? { steps: p.steps } : {}),
142
258
  ...(overhang && overhang !== 'none' ? { overhang } : {}),
143
259
  // How it's made other than printed: milled from a side, cast in a mould; symmetric, extruded (topopt's filters)
144
- ...(p.mill ? { mill: p.mill } : {}), ...(p.cast ? { cast: typeof p.cast === 'string' ? p.cast : { draw: p.cast.draw, ...(p.cast.parting != null ? { parting: ev(p.cast.parting) } : {}) } } : {}),
260
+ ...(millSides ? { mill: millSides } : {}), ...(castWay ? { cast: typeof castWay === 'string' ? castWay : { draw: castWay.draw, ...(castWay.parting != null ? { parting: ev(castWay.parting) } : {}) } } : {}),
261
+ // (a tool or draft with the process switched off by its variable is left out with it; one with no such process
262
+ // at all goes on, for topopt to refuse by name)
263
+ ...(p.tool != null && (millSides || !p.mill) ? { tool: ev(p.tool) } : {}), ...(p.draft != null && (castWay || !p.cast) ? { draft: ev(p.draft) } : {}), ...(p.voids === 'prevented' ? { voids: 'prevented' } : {}),
264
+ ...(p.feature != null ? { feature: ev(p.feature) } : {}),
145
265
  ...(p.symmetry ? { symmetry: p.symmetry } : {}), ...(p.extrude ? { extrude: p.extrude } : {}),
146
266
  // A mechanism: where the output should move, along one axis, against a spring; a spring the input pushes against
147
267
  ...(p.output ? { output: { ...(await region(p.output)), direction: pt(p.output.direction), ...(p.output.spring != null ? { spring: ev(p.output.spring) } : {}) } } : {}),
@@ -156,7 +276,7 @@ async function readOne(project, ref, link) {
156
276
  // What the result is made from, for cad why: the rule sets, the problem's own values, the parts and anchors of other
157
277
  // designs it reads, and where its filter came from
158
278
  const inputs = { uses, variables: Object.fromEntries(Object.keys(p.variables || {}).map((k) => [k, values[k]])), ...(variant ? { set: p.variants[variant] } : {}),
159
- parts: [...parts.keys()].sort(), anchors: [...anchors.values()].sort((a, b) => (a.anchor < b.anchor ? -1 : 1)).map(({ anchor: a, at }) => ({ anchor: a, at: at.map((c) => round(c, 4)) })),
279
+ parts: [...parts.keys()].sort(), ...(p.in ? { assembly: { name: p.in.assembly, item: p.in.item, pose: placing ? (await placing).s.pose : p.in.pose ?? null, joints: [...joints.values()].sort((a, b) => (a.joint < b.joint ? -1 : 1)).map(({ joint: j, at }) => ({ joint: j, at: at.map((c) => round(c, 4)) })), sweeps } } : {}), anchors: [...anchors.values()].sort((a, b) => (a.anchor < b.anchor ? -1 : 1)).map(({ anchor: a, at }) => ({ anchor: a, at: at.map((c) => round(c, 4)) })),
160
280
  filter: p.filter != null ? { value: problem.filter, from: `the problem: ${p.filter}` } : problem.filter ? { value: problem.filter, from: `two of ${printer}'s lines (2 × ${line} mm), more than a cell and a half` } : { value: round(problem.cell * 1.5), from: 'a cell and a half' } };
161
281
  return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline, critical: !!p.critical, inputs, voids: p.voids || 'allowed' };
162
282
  }
@@ -178,19 +298,36 @@ function holdEmpty(spec) {
178
298
  }
179
299
  // How a result is made, and what that process can't make in it: for a milled or cast part, the cells a tool or mould
180
300
  // half could not reach (undercuts, none by construction unless an avoid region or the space's own shape leaves material between a cell and its side), how grey it is; where enclosed voids are
181
- // refused (a powder bed print, a trapped core), each void with its volume (mm³, or mm² in 2D) and where it is
301
+ // refused or prevented (a powder bed print, a trapped core), each void left with its volume (mm³, or mm² in 2D) and
302
+ // where it is, and with prevented that they were
182
303
  function made(r, spec, density) {
183
304
  const p = r.problem, out = {};
184
305
  if (p.mill || p.cast) {
185
- const c = spec.cast, from = p.mill || (typeof c === 'string' ? c : c.draw), u = undercuts(spec.grid, density, { from, ...(c && typeof c === 'object' ? { parting: c.parting } : {}) });
186
- out.process = p.mill ? { mill: p.mill } : { cast: typeof c === 'string' ? c : { draw: c.draw, parting: round(c.at, 3) } };
306
+ const c = spec.cast, from = p.mill || (typeof c === 'string' ? c : c.draw), tool = p.tool ? p.tool / spec.grid.h : undefined;
307
+ const u = undercuts(spec.grid, density, { from, ...(c && typeof c === 'object' ? { parting: c.parting } : {}), ...(p.draft ? { draft: p.draft } : {}) });
308
+ // With a tool's size: the cells it can't get its end into besides, in the design (none, by construction) and in
309
+ // avoid regions (a hole narrower than the tool: drilled, or a smaller tool)
310
+ if (tool) {
311
+ const hidden = new Set(u.cells), narrow = undercuts(spec.grid, density, { from, tool }).cells.filter((e) => !hidden.has(e));
312
+ out.narrow = { design: narrow.filter((e) => spec.passive[e] === 0).length, avoided: narrow.filter((e) => spec.passive[e] === -1).length };
313
+ }
314
+ // (a draft at the grid: a step out every whole number of layers in 1 / tan, so the angle made is atan of one over it)
315
+ const every = p.draft ? Math.max(1, Math.floor(1 / Math.tan((p.draft * Math.PI) / 180) + 1e-9)) : 0;
316
+ out.process = p.mill ? { mill: p.mill, ...(p.tool ? { tool: p.tool } : {}) } : { cast: typeof c === 'string' ? c : { draw: c.draw, parting: round(c.at, 3) }, ...(every ? { draft: p.draft, every, made: round((Math.atan(1 / every) * 180) / Math.PI, 2) } : {}) };
187
317
  out.undercuts = u.count;
188
318
  }
189
319
  if (p.symmetry) out.symmetry = p.symmetry;
190
320
  if (p.extrude) out.extrude = p.extrude;
191
321
  // How grey it came out: a process or a tie can leave no clear part (a 2D section milled from its side)
192
322
  if (p.mill || p.cast || p.symmetry || p.extrude) out.grey = round(grey(density, spec.passive), 3);
193
- if (r.voids === 'refused') out.voids = voids(spec.grid, density, { origin: spec.origin }).map((v) => ({ volume: round(v.volume, 3), at: v.at.map((x) => round(x, 3)) }));
323
+ if (r.voids === 'refused' || r.voids === 'prevented') out.voids = voids(spec.grid, density, { origin: spec.origin }).map((v) => ({ volume: round(v.volume, 3), at: v.at.map((x) => round(x, 3)) }));
324
+ if (r.voids === 'prevented') out.vented = true;
325
+ // The thinnest member asked: the ball's radius on the grid, the width it holds members to (a cell, where the grid
326
+ // already does), and the solid cells left in members narrower (or on a square outside corner)
327
+ if (p.feature != null) {
328
+ const h = spec.grid.h, cells = featureCells(p.feature, h);
329
+ out.feature = { asked: p.feature, cells, holds: round((2 * cells + 1) * h, 3), thin: cells ? thin(spec.grid, density, { radius: cells }).count : 0 };
330
+ }
194
331
  return out;
195
332
  }
196
333
  const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
package/lib/wires.mjs CHANGED
@@ -52,12 +52,17 @@ function currentOf(w, s, top, signal) {
52
52
  }
53
53
 
54
54
  // A wire ending on a board's axis connector: the board's pins for that axis, from its rule set
55
- function pinsAt(w, s) {
55
+ export function pinsAt(w, s) {
56
56
  for (const end of [w.from, w.to]) {
57
57
  const [id, anchor] = String(end).split('.'), o = s.objects.find((x) => x.id === id && x.bought?.part === 'board'), e = o?.built.entries;
58
- if (!e || !/^[A-Z]$/.test(anchor ?? '')) continue;
58
+ if (!e || !/^[A-Z]\d?$/.test(anchor ?? '')) continue; // (a shield's X, Y, Z; a Mega's S0 to S7)
59
59
  const pin = (k) => e.find((x) => x.name === `${o.bought.set}.${k}_pin_${anchor.toLowerCase()}`)?.value;
60
- if (pin('step')) return `step ${pin('step')}, dir ${pin('dir')}${pin('limit') ? `, limit ${pin('limit')}` : ''}`;
60
+ if (!pin('step')) continue;
61
+ // A Mega's slots (S0 to S7) go to driver boards of their own: the wire carries the driver's EN, STEP, DIR and GND, every
62
+ // slot's EN on the one enable pin, and the axis's home switch is a wire of its own. A shield's axis carries its limit pin
63
+ const en = /^S\d+$/.test(anchor) ? e.find((x) => x.name === `${o.bought.set}.enable_pin`)?.value : null;
64
+ if (en) return `step ${pin('step')}, dir ${pin('dir')}, enable ${en} (every slot's)`;
65
+ return `step ${pin('step')}, dir ${pin('dir')}${pin('limit') ? `, limit ${pin('limit')}` : ''}`;
61
66
  }
62
67
  return null;
63
68
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.89",
3
+ "version": "0.7.97",
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": {
@@ -64,13 +64,13 @@
64
64
  "@rulecad/fit": "^0.4.0",
65
65
  "@rulecad/model-link": "^0.3.2",
66
66
  "@rulecad/versions": "^0.1.6",
67
- "@rulecad/shapes": "^0.4.8",
68
- "@rulecad/rules": "^0.3.28",
67
+ "@rulecad/shapes": "^0.4.9",
68
+ "@rulecad/rules": "^0.3.30",
69
69
  "@jscad/modeling": "^2.12.0",
70
70
  "three": "^0.186.1",
71
71
  "@rulecad/fea": "^0.2.14",
72
- "@rulecad/topopt": "^0.3.6",
73
- "@rulecad/flexures": "^0.5.12",
72
+ "@rulecad/topopt": "^0.3.8",
73
+ "@rulecad/flexures": "^0.5.17",
74
74
  "@rulecad/gears": "^0.3.4",
75
75
  "@rulecad/motors": "^0.1.6",
76
76
  "@rulecad/fixings": "^0.1.8",