@rulecad/cad 0.7.42 → 0.7.44

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/links.mjs CHANGED
@@ -6,8 +6,9 @@ import { fmt } from './rules.mjs';
6
6
  import { paths, config } from './workspace.mjs';
7
7
  import { host, readJson } from './host.mjs';
8
8
  import { pcbEngine } from './design.mjs';
9
- import { shapes, motionData } from './assembly.mjs';
9
+ import { shapes, motionData, checkAssembly, wireRoutesOf } from './assembly.mjs';
10
10
  import { slotOf } from './threemf.mjs';
11
+ import { taskData, stepsData, buildData, ledgerRows } from './buildpage.mjs';
11
12
 
12
13
  /** The project's filaments: { base: { slot: 1, … }, legend: { slot: 2, … } } in project.json. @param {string} project */
13
14
  export const filaments = (project) => readJson(path.join(paths.project(project), 'project.json')).filaments || {};
@@ -48,12 +49,26 @@ export async function objectModel(b, { title, version, src, set, filaments: fil
48
49
  rules: b.entries.filter((e) => e.show).map((e) => [e.label || e.name, fmt(e.value), e.unit || '']),
49
50
  ...sheet([[b.object.name, b.entries]], { noRules }),
50
51
  ...(b.circuit ? { views: await (await pcbEngine()).views(b.circuit) } : {}), // boards: the 2D board and schematic
52
+ ...(b.circuit ? await fabOf([[b.object.name, version, b]]) : {}), // and the zip to order it with
51
53
  ...fromParts(b.parts.map((p) => ({ name: p.name, role: p.role, label: p.label, slot: slotOf(fil, p.filament), triangles: triangles(p.triangles) }))),
52
54
  };
53
55
  }
54
56
 
57
+ // Each board's fab zip (cad export's: Gerbers, drill files, BOM, placement), for the page to offer as a download. A
58
+ // board whose files can't be made here (one that needs KiCad, without it) goes without, and says why
59
+ async function fabOf(boards) {
60
+ const pcb = await pcbEngine(), { zip } = await import('@rulecad/model-link'), fab = [];
61
+ for (const [name, version, b] of boards) {
62
+ try {
63
+ const files = await pcb.fabFiles(b.circuit, name, { source: b.source });
64
+ fab.push({ name: `${name}${version ? `@${version}` : ''}-fab.zip`.replace(/[^\w@.+-]/g, '-'), zip: Buffer.from(await zip(Object.entries(files))).toString('base64') });
65
+ } catch (e) { console.error(` ${name}: no fab zip in the link (${String(e.message || e).split('\n')[0]})`); }
66
+ }
67
+ return fab.length ? { fab } : {};
68
+ }
69
+
55
70
  /** A built assembly as a model: each shape once and placed (nine keys cost one keycap), its boards' views, its joints. */
56
- export async function assemblyModel(s, { title, versions, filaments: fil = {}, noRules = false }) {
71
+ export async function assemblyModel(s, { title, versions, filaments: fil = {}, noRules = false, steps }) {
57
72
  const placed = shapes(s.parts), list = placed.shapes.length ? placed.place.map(([i, ...m], n) => { const p = placed.shapes[i].part; return { shape: i, role: p.role, label: p.object || p.label, slot: slotOf(fil, p.filament), triangles: triangles(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; }) : [];
58
73
  // A pose that sets items' variables draws some parts differently (a flexure bent): each such part's shape in that
59
74
  // pose goes in the link as a "pose" part, placed as the part is, to be swapped in when the page shows the pose
@@ -77,7 +92,7 @@ export async function assemblyModel(s, { title, versions, filaments: fil = {}, n
77
92
  if (!boards.length) return {};
78
93
  const pcb = await pcbEngine(), views = [];
79
94
  for (const o of boards) for (const [n, svg] of await pcb.views(o.built.circuit)) views.push([boards.length > 1 ? `${o.objName} ${n}` : n, svg]);
80
- return { views };
95
+ return { views, ...(await fabOf(boards.map((o) => [o.objName, o.version || o.built.object?.version, o.built]))) };
81
96
  })()),
82
97
  ...fromShapes(list),
83
98
  };
@@ -87,5 +102,13 @@ export async function assemblyModel(s, { title, versions, filaments: fil = {}, n
87
102
  model.motion.swap = {};
88
103
  alts.forEach((x, i) => (model.motion.swap[x.pose] ||= []).push([x.of, list.length - alts.length + i]));
89
104
  }
105
+ // A machine's link carries the rest of the project: its task, a drawing to play, its wires' routes, the build page
106
+ if (s.wires?.length) model.wires = wireRoutesOf(s);
107
+ if (s.task || s.wires?.length || s.objects.some((o) => o.bought || o.motor)) {
108
+ const findings = s.task ? checkAssembly(s) : [];
109
+ if (s.task && model.motion) { model.task = taskData(s, findings); const carried = stepsData(s, steps); if (carried) model.steps = carried; }
110
+ Object.assign(model, await buildData(s));
111
+ if (!noRules && s.task) { const rows = ledgerRows(s, findings); if (rows.length) model.sheet = [...rows, ...(model.sheet ?? [])]; }
112
+ }
90
113
  return model;
91
114
  }
package/lib/loads.mjs ADDED
@@ -0,0 +1,224 @@
1
+ // What the machine's own weight and its payload do to it: the force and tipping moment each joint's bearing or printed
2
+ // location takes, how far the links bend, how fast the arm rings, and what acceleration the motors can give it. Masses come
3
+ // from the parts as drawn (volume and density) and the bought parts' rules. Findings in the assembly's shape.
4
+ import crypto from 'node:crypto';
5
+ import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
6
+ import { jacobian } from '@rulecad/robots';
7
+ import { performance } from '@rulecad/motors';
8
+ import { host } from './host.mjs';
9
+ import { paths } from './workspace.mjs';
10
+ import { peekRuleSet } from './rules.mjs';
11
+ import { solidFill } from './optimise.mjs';
12
+ import { materialOf } from './list.mjs';
13
+ import { axisOf, trainFrom, workingSpeed, atCurrent } from './motors.mjs';
14
+ import { sample, chainOf } from './task.mjs';
15
+
16
+ const G = 9.80665, sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
17
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]], add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]], scale = (a, k) => a.map((x) => x * k);
18
+ const norm = (a) => Math.hypot(a[0], a[1], a[2]), n3 = (x, d = 2) => String(Number(x.toFixed(d)));
19
+ const rowsAt = (W, p) => [0, 1, 2].map((k) => W[4 * k] * p[0] + W[4 * k + 1] * p[1] + W[4 * k + 2] * p[2] + W[4 * k + 3]);
20
+ const invAt = (W, p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
21
+
22
+ // A mesh's volume and centroid: signed tetrahedra from the origin
23
+ function solidOf(tris) {
24
+ let V = 0; const c = [0, 0, 0];
25
+ for (const [a, b, d] of tris) { const v = dot(a, cross(b, d)) / 6; V += v; for (let k = 0; k < 3; k++) c[k] += (v * (a[k] + b[k] + d[k])) / 4; }
26
+ return { volume: Math.abs(V), centroid: V ? c.map((x) => x / V) : [0, 0, 0] };
27
+ }
28
+
29
+ /** Each moving thing's mass in kg and its centre in its item's frame. */
30
+ export function massesOf(s, { placeItems, jointValues }) {
31
+ const motion = s.motion, ids = motion.items.map((x) => x[0]), W = placeItems(motion, jointValues(motion, motion.pose ?? undefined)), density = materialOf(s.project).density, out = [];
32
+ ids.forEach((id, k) => {
33
+ const parts = s.parts.filter((p) => p.item === id && p.role !== 'support'); if (!parts.length) return;
34
+ const o = s.objects.find((x) => x.id === id || String(x.id).startsWith(`${id}.`)), reference = parts.every((p) => p.role === 'reference');
35
+ let total = 0, c = [0, 0, 0];
36
+ for (const p of parts) { const q = solidOf(p.triangles); const kg = reference ? 0 : (q.volume / 1000) * density / 1000; total += kg; c = add(c, scale(q.centroid, kg || q.volume)); }
37
+ const weightSum = reference ? parts.reduce((t, p) => t + solidOf(p.triangles).volume, 0) : total;
38
+ const bought = reference ? o?.bought?.mass ?? null : null;
39
+ out.push({ item: k, id, kg: reference ? bought ?? 0 : total, centre: invAt(W[k], weightSum ? scale(c, 1 / weightSum) : c), known: !reference || bought != null });
40
+ });
41
+ return out;
42
+ }
43
+
44
+ // A joint's value set through its leader when it follows a motor off the chain (a gearbox's output): the model moves by its leader
45
+ const chainSet = (motion, names, q) => Object.fromEntries(names.map((n, i) => { const j = motion.joints.find((x) => x.id === n), lead = j?.follow && !names.includes(j.follow[0]) ? j.follow : null; return lead ? [lead[0], [(q[i] - (lead[2] ?? 0)) / (lead[1] ?? 1)]] : [n, [q[i]]]; }));
46
+ // A mesh's bounding box, as lo and hi: a loop, as a large part's triangles overflow Math.min(...spread)
47
+ function extent(tris) { const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; for (const t of tris) for (const p of t) for (let k = 0; k < 3; k++) { if (p[k] < lo[k]) lo[k] = p[k]; if (p[k] > hi[k]) hi[k] = p[k]; } return { lo, hi }; }
48
+ const beyond = (motion, j, item) => { const by = new Map(motion.joints.map((x) => [x.child, x])); for (let i = item, n = 0; i >= 0 && n < 99; n++) { const x = by.get(i); if (!x) return false; if (x === j) return true; i = x.parent; } return false; };
49
+
50
+ // Force and moment about a joint's origin, at one pose
51
+ function loadAt(motion, masses, payload, worlds, j, mul) {
52
+ const { O, Z } = axisOf(motion, worlds, j, mul), g = motion.gravity || [0, 0, -1], dir = scale(g, 1 / norm(g));
53
+ let F = [0, 0, 0], M = [0, 0, 0], carried = 0;
54
+ const addMass = (kg, X) => { const f = scale(dir, kg * G); F = add(F, f); M = add(M, scale(cross(sub(X, O), f), 1 / 1000)); carried += kg; };
55
+ for (const m of masses) if (beyond(motion, j, m.item)) addMass(m.kg, rowsAt(worlds[m.item], m.centre));
56
+ if (payload && beyond(motion, j, payload.item)) addMass(payload.kg, rowsAt(worlds[payload.item], payload.point));
57
+ const axial = dot(F, Z), radial = norm(sub(F, scale(Z, axial))), torque = dot(M, Z), tipping = norm(sub(M, scale(Z, torque)));
58
+ return { axial: Math.abs(axial), radial, tipping, torque, carried, F, O, Z };
59
+ }
60
+
61
+ // The poses the machine will be in: the task's samples, the named poses, or each joint at its ends
62
+ function posesOf(s, jointValues) {
63
+ const motion = s.motion, base = jointValues(motion, motion.pose ?? undefined), leads = Object.fromEntries(Object.entries(base).filter(([id]) => !motion.joints.find((x) => x.id === id)?.follow)), out = [];
64
+ for (const p of Object.keys(motion.poses || {})) out.push({ label: `pose ${p}`, values: jointValues(motion, p) });
65
+ if (s.task) { const { c, r } = sample(s), every = Math.max(1, Math.ceil(r.samples.length / 40)); r.samples.filter((x, i) => x.reachable && !(i % every)).forEach((x) => out.push({ label: 'on the task', point: x.point, values: jointValues(motion, { ...leads, ...chainSet(motion, c.names, x.q) }) })); }
66
+ if (!out.length) for (const j of motion.joints.filter((x) => !x.follow && x.dofs.length === 1)) for (const v of j.dofs[0].slice(0, 2)) out.push({ label: `${j.id} at ${n3(v, 1)}`, values: jointValues(motion, { ...leads, [j.id]: [v] }) });
67
+ out.push({ label: 'as drawn', values: base });
68
+ return out;
69
+ }
70
+
71
+ const X0 = 0.6, Y0 = 0.5; // ISO 76, a single deep-groove ball bearing's static factors
72
+ function bearingMargin(rows, loads) {
73
+ const [first] = rows, pair = rows.length >= 2;
74
+ const span = pair ? Math.abs(rows[1].along - rows[0].along) : (first.bore + first.outer) / 2; // mm: a pair's spacing, or the balls' pitch circle
75
+ const radial = pair ? loads.radial / rows.length + (loads.tipping * 1000) / span : loads.radial + (2 * loads.tipping * 1000) / span;
76
+ const P0 = Math.max(radial, X0 * radial + Y0 * (loads.axial / (pair ? 2 : 1)));
77
+ return { P0, C0: first.C0, margin: first.C0 / P0, span };
78
+ }
79
+
80
+ // A printed location's weakest clip, from FE on the part as drawn: fixed at its foot, the load at its head
81
+ function clipStress(tris, force, modulus, nu, cell) {
82
+ const key = crypto.createHash('sha256').update(JSON.stringify([tris.length, tris[0], force, modulus, cell])).digest('hex').slice(0, 20), file = paths.cache('clip', key);
83
+ if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
84
+ const { lo, hi } = extent(tris), n = hi.map((h, k) => Math.max(1, Math.ceil((h - lo[k]) / cell)));
85
+ const gr = { nx: n[0], ny: n[1], nz: n[2], h: cell }, density = solidFill(tris, gr, lo), g = makeGrid(gr), fixed = new Uint8Array(g.dofs), f = new Float64Array(g.dofs);
86
+ // nodes at the foot (the lowest two layers) are held, and the load shared over the top two layers
87
+ const at = positions(g), nodeZ = (id) => Math.round(at[id][2] / cell), onPart = new Uint8Array(g.nodes);
88
+ for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) for (let k = 0; k < 8; k++) onPart[g.edof[e * 24 + 3 * k] / 3] = 1;
89
+ const tops = []; for (let id = 0; id < g.nodes; id++) { if (!onPart[id]) continue; const z = nodeZ(id); if (z <= 1) for (let k = 0; k < 3; k++) fixed[3 * id + k] = 1; if (z >= n[2] - 1) tops.push(id); }
90
+ if (!tops.length) return { stress: 0, thin: true };
91
+ for (const id of tops) for (let k = 0; k < 3; k++) f[3 * id + k] = force[k] / tops.length;
92
+ const a = analyse({ grid: g, density, material: { E: modulus, nu }, fixed, loads: [f] });
93
+ let most = 0; for (let e = 0; e < density.length; e++) if (density[e] >= 0.5 && a.stress[0][e] > most) most = a.stress[0][e];
94
+ const out = { stress: most, deflection: a.deflection[0].most }; host.writeText(file, JSON.stringify(out)); return out;
95
+ }
96
+
97
+ export function momentChecks(s, f, helpers, masses, payload) {
98
+ const motion = s.motion, { placeItems, mul, jointValues } = helpers, specs = new Map((s.a.joints || []).map((j) => [j.id, j])), poses = posesOf(s, jointValues), out = {};
99
+ const mat = (() => { const n = materialOf(s.project).name; try { return Object.fromEntries(Object.entries(peekRuleSet(n).rules).map(([k, r]) => [k, r.value])); } catch { return null; } })();
100
+ for (const j of motion.joints) {
101
+ if (j.type !== 'revolute' && j.type !== 'prismatic') continue;
102
+ let worst = null;
103
+ for (const p of poses) { const w = placeItems(motion, p.values), L = loadAt(motion, masses, payload, w, j, mul); if (!worst || L.tipping + L.radial / 50 > worst.L.tipping + worst.L.radial / 50) worst = { L, p, w }; }
104
+ if (!worst || !worst.L.carried) continue;
105
+ const { L, p } = worst, spec = specs.get(j.id) ?? {}, at = L.O, refs = { joint: j.id }, say = `${n3(L.carried * 1000, 0)} g carried: ${n3(L.tipping, 3)} N m tipping, ${n3(L.radial, 2)} N across and ${n3(L.axial, 2)} N along it, worst ${p.label}`, values = { axial: L.axial, radial: L.radial, tipping: L.tipping, carried: L.carried };
106
+ out[j.id] = { ...values, pose: p.label };
107
+ if (spec.support?.bearings?.length) {
108
+ const rows = spec.support.bearings.map((id) => { const o = s.objects.find((x) => x.id === id); if (!o || !['bearing', 'linear_bearing'].includes(o.bought?.part)) throw new Error(`joint ${j.id}: support names "${id}", which isn't a bought bearing`); const v = o.built.values, W = worst.w[motion.items.findIndex((x) => x[0] === id)]; return { id, bore: v.bore, outer: v.outer_diameter, C0: v.static_rating, along: dot(sub([W[3], W[7], W[11]], L.O), L.Z) }; });
109
+ const m = bearingMargin(rows, L), level = m.margin < 1 ? 'fail' : m.margin < 2 ? 'warn' : 'pass';
110
+ f(level, `${j.id}: ${say}. ${rows.map((r) => r.id).join(' and ')} take ${n3(m.P0, 1)} N equivalent against ${n3(m.C0, 0)} N static, ${n3(m.margin, 1)} times over`, level === 'pass' ? null : `${j.id}: bearing ${n3(m.margin, 1)}×`, { code: 'joint.moment', at, refs: { ...refs, bearings: rows.map((r) => r.id) }, values: { ...values, equivalent: m.P0, rating: m.C0, margin: m.margin } });
111
+ } else if (spec.support?.clips?.length) {
112
+ const clips = spec.support.clips, D = s.num(spec.support.pitch ?? 40) / 2, share = L.axial / clips.length + (L.tipping * 1000 * 2) / (clips.length * D), cell = s.num(spec.support.cell ?? 0.8);
113
+ let worstClip = null;
114
+ for (const id of clips) {
115
+ const parts = s.parts.filter((x) => x.item === id || x.leaf === id); if (!parts.length) throw new Error(`joint ${j.id}: support names a clip "${id}", which isn't a part`);
116
+ const tris = parts.flatMap((x) => x.triangles), r = clipStress(tris, scale(L.Z, -share), mat?.modulus ?? 2500, mat?.poisson ?? 0.36, cell);
117
+ if (!worstClip || r.stress > worstClip.stress) worstClip = { id, ...r };
118
+ }
119
+ const strength = mat?.strength ?? 30, margin = strength / worstClip.stress, level = margin < 1 ? 'fail' : margin < 2 ? 'warn' : 'pass';
120
+ f(level, `${j.id}: ${say}. ${clips.length} printed clips, the worst (${worstClip.id}) at ${n3(worstClip.stress, 2)} MPa against ${strength} MPa (FE on ${cell} mm cells, an estimate), ${n3(margin, 1)} times over`, level === 'pass' ? null : `${j.id}: clip ${n3(margin, 1)}×`, { code: 'joint.moment', at, refs: { ...refs, clips }, values: { ...values, stress: worstClip.stress, strength, margin } });
121
+ } else f(s.task && (s.a.gravity || s.task.payload != null) ? 'warn' : 'info', `${j.id}: ${say}, and nothing named takes it: give the joint a "support" (bearings, or printed clips)`, `${j.id}: no support named`, { code: 'joint.moment', at, refs, values });
122
+ }
123
+ return out;
124
+ }
125
+
126
+ // A link bent: held at its parent joint, the carried weight at its far end. δ from the FE, the tilt from a cantilever's
127
+ // relation (1.5 δ / L), carried on to the tool. Kept in .cache, as this is the slow part.
128
+ function linkFE(tris, O, far, force, E, nu, cell) {
129
+ const key = crypto.createHash('sha256').update(JSON.stringify([tris.length, tris.slice(0, 4), O, far, force, E, cell])).digest('hex').slice(0, 20), file = paths.cache('link', key);
130
+ if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
131
+ const { lo, hi } = extent(tris), n = hi.map((h, k) => Math.max(1, Math.ceil((h - lo[k]) / cell)));
132
+ const gr = { nx: n[0], ny: n[1], nz: n[2], h: cell }, density = solidFill(tris, gr, lo), g = makeGrid(gr), fixed = new Uint8Array(g.dofs), f = new Float64Array(g.dofs), onPart = new Uint8Array(g.nodes);
133
+ for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) for (let k = 0; k < 8; k++) onPart[g.edof[e * 24 + 3 * k] / 3] = 1;
134
+ const nodeAt = positions(g), pos = (id) => [lo[0] + nodeAt[id][0], lo[1] + nodeAt[id][1], lo[2] + nodeAt[id][2]];
135
+ const R = 3 * cell, held = [], near = [];
136
+ for (let id = 0; id < g.nodes; id++) if (onPart[id]) { const p = pos(id); if (norm(sub(p, O)) <= R + 4) held.push(id); if (norm(sub(p, far)) <= R + 4) near.push(id); }
137
+ if (!held.length || !near.length) return { deflection: 0, cell, missing: true };
138
+ for (const id of held) for (let k = 0; k < 3; k++) fixed[3 * id + k] = 1;
139
+ for (const id of near) for (let k = 0; k < 3; k++) f[3 * id + k] = force[k] / near.length;
140
+ const size = norm(force), a = analyse({ grid: g, density, material: { E, nu }, fixed, loads: [f] }), out = { deflection: size ? a.compliance[0] / size : 0, stress: Array.from(a.stress[0]).reduce((m, x, e) => (density[e] >= 0.5 && x > m ? x : m), 0), cell };
141
+ host.writeText(file, JSON.stringify(out)); return out;
142
+ }
143
+
144
+ export function deflectionChecks(s, f, helpers, masses, payload) {
145
+ if (!s.task) return 0;
146
+ const motion = s.motion, { placeItems, mul, jointValues } = helpers, { c, r } = sample(s), ids = motion.items.map((x) => x[0]), mat = (() => { try { return Object.fromEntries(Object.entries(peekRuleSet(materialOf(s.project).name).rules).map(([k, x]) => [k, x.value])); } catch { return {}; } })(), E = mat.modulus ?? 2500, nu = mat.poisson ?? 0.36;
147
+ const reached = r.samples.filter((x) => x.reachable); if (!reached.length) return 0;
148
+ const lever = (x) => norm(sub(x.point, rowsAt(placeItems(motion, jointValues(motion, motion.pose ?? undefined))[0] || [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0])));
149
+ const far = reached.reduce((a, b) => (lever(b) > lever(a) ? b : a)), near = reached.reduce((a, b) => (lever(b) < lever(a) ? b : a));
150
+ const links = motion.joints.filter((j) => c.names.includes(j.id));
151
+ const at = (x, label) => {
152
+ const v = jointValues(motion, chainSet(motion, c.names, x.q)), W = placeItems(motion, v), rows = [];
153
+ let total = 0, carried = 0, tool = x.point, dir = (() => { const g = motion.gravity || [0, 0, -1], l = norm(g); return g.map((q) => q / l); })();
154
+ links.forEach((j, i) => {
155
+ const group = new Set([j.child]); for (let more = true; more;) { more = false; for (const x of motion.joints) if (x.type === 'fixed' && group.has(x.parent) && !group.has(x.child)) { group.add(x.child); more = true; } } // the link is everything bolted to the joint's child
156
+ const parts = s.parts.filter((p) => group.has(ids.indexOf(p.item)) && p.role !== 'support' && p.role !== 'reference'); if (!parts.length) return;
157
+ const m = masses.filter((q) => beyond(motion, j, q.item)).reduce((t, q) => t + q.kg, 0) + (payload && beyond(motion, j, payload.item) ? payload.kg : 0);
158
+ if (!m) return;
159
+ const O = axisOf(motion, W, j, mul).O, nextJ = links[i + 1], end = nextJ ? axisOf(motion, W, nextJ, mul).O : tool, Wc = W[j.child];
160
+ const local = parts.flatMap((p) => { const Wp = W[ids.indexOf(p.item)]; return p.localTriangles && Wp ? p.localTriangles.map((t) => t.map((q) => invAt(Wc, rowsAt(Wp, q)))) : p.triangles.map((t) => t.map((q) => invAt(Wc, q))); }), Lo = invAt(Wc, O), Le = invAt(Wc, end), F = [dir[0] * Wc[0] + dir[1] * Wc[4] + dir[2] * Wc[8], dir[0] * Wc[1] + dir[1] * Wc[5] + dir[2] * Wc[9], dir[0] * Wc[2] + dir[1] * Wc[6] + dir[2] * Wc[10]].map((q) => q * m * G);
161
+ const e = extent(local), box = [0, 1, 2].map((k) => e.hi[k] - e.lo[k]), sup = s.a.joints?.find((x) => x.id === j.id)?.support, cell = sup?.cell != null ? s.num(sup.cell) : Math.max(1, Math.min(4, Math.min(...box) / 3)), fe = linkFE(local, Lo, Le, F, E, nu, cell), L = norm(sub(Lo, Le)) || 1, beyondLength = norm(sub(tool, end)), drop = fe.deflection + (1.5 * fe.deflection * beyondLength) / L;
162
+ total += drop; carried = Math.max(carried, m); rows.push({ link: ids[j.child], deflection: fe.deflection, at_tool: drop, cell: fe.cell, stress: fe.stress });
163
+ });
164
+ return { label, total, carried, rows };
165
+ };
166
+ const stretch = at(far, 'at full stretch'), folded = at(near, 'folded'), worst = stretch.total >= folded.total ? stretch : folded;
167
+ if (!worst.rows.length) return 0;
168
+ f('info', `the tool drops ${n3(worst.total, 3)} mm ${worst.label}: ${worst.rows.map((x) => `${x.link} ${n3(x.at_tool, 3)} mm`).join(', ')} (FE from the parts as drawn, cells ${worst.rows.map((x) => n3(x.cell, 1)).join(', ')} mm: a person can refine with "cell" on the joint's support)`, null, { code: 'link.deflection', predict: { name: 'link.deflection', figure: `drop at ${s.task.tool}`, value: worst.total, unit: 'mm' }, values: { total: worst.total, rows: worst.rows, label: worst.label } });
169
+ const finds = [stretch, folded].filter((x) => x.rows.length).map((x) => { const k = (x.carried * G) / (x.total || 1e-9), Hz = Math.sqrt((k * 1000) / x.carried) / (2 * Math.PI); return { ...x, Hz }; }), low = finds.reduce((a, b) => (b.Hz < a.Hz ? b : a));
170
+ const rings = s.task.speed != null ? ` Expect visible ringing past about ${n3(Math.max(20, low.Hz * 3), 0)} mm/s.` : '';
171
+ f('info', `the lowest mode is about ${n3(low.Hz, 0)} Hz ${low.label}, from the tool's stiffness and the mass it carries.${rings}`, null, { code: 'assembly.frequency', values: { Hz: low.Hz, label: low.label } });
172
+ return worst.total;
173
+ }
174
+
175
+ // What the motors can do to the arm's inertia: the worst acceleration at the tool, and the time a move across the task takes
176
+ export function accelChecks(s, f, helpers, masses, payload) {
177
+ const motion = s.motion, { placeItems, jointValues, mul } = helpers; if (!motion.drives?.length) return null;
178
+ const c = s.task ? chainOf(s) : null, names = c ? c.names : motion.joints.filter((j) => !j.follow).map((j) => j.id), base = placeItems(motion, jointValues(motion, motion.pose ?? undefined)), limits = [];
179
+ for (const id of names) {
180
+ const j = motion.joints.find((x) => x.id === id), t = trainFrom(motion, id), d = motion.drives.find((x) => x.joint === t.root); if (!d) { limits.push(null); continue; }
181
+ const axis = axisOf(motion, base, j, mul);
182
+ let I = 0, gravity = 0; // kg mm² about the joint
183
+ for (const m of masses) if (beyond(motion, j, m.item)) { const X = rowsAt(base[m.item], m.centre), r = sub(X, axis.O), rad = norm(sub(r, scale(axis.Z, dot(r, axis.Z)))); I += m.kg * rad * rad; }
184
+ if (payload && beyond(motion, j, payload.item)) { const X = rowsAt(base[payload.item], payload.point), r = sub(X, axis.O), rad = norm(sub(r, scale(axis.Z, dot(r, axis.Z)))); I += payload.kg * rad * rad; }
185
+ for (const p of posesOf(s, jointValues).slice(0, 30)) gravity = Math.max(gravity, Math.abs(loadAt(motion, masses, payload, placeItems(motion, p.values), j, mul).torque));
186
+ const m = d.model, speed = workingSpeed(m, d.spec), ratio = t.ratio, eff = t.efficiency, rotor = (m.figures.rotor_inertia?.value ?? 0) * 0.1, kgmm2 = I / (ratio * ratio * eff) + rotor; // kg mm²
187
+ const avail = atCurrent(m, d.spec, performance(m, { speed }).motor.torque), left = avail - gravity / (ratio * eff), refs = { joint: id, item: d.id }, at = axis.O;
188
+ if (left <= 0) { f('fail', `${id} stalls: ${d.id} gives ${n3(avail, 3)} N m at ${n3(speed, 0)} rpm, and the load takes ${n3(gravity / (ratio * eff), 3)} N m of it through ${n3(ratio, 1)}:1`, `${id}: stalls`, { code: 'motor.accel', at, refs, values: { available: avail, gravity } }); limits.push(0); continue; }
189
+ const alphaMotor = (left * 1e6) / kgmm2, alpha = (alphaMotor / ratio) * (180 / Math.PI); // rad/s² at the motor, deg/s² at the joint
190
+ limits.push(alpha);
191
+ f('info', `${id} can accelerate at ${n3(alpha, 0)} °/s² (reflected inertia ${n3(kgmm2, 1)} kg mm², ${n3(left, 3)} N m left after the load)`, null, { code: 'motor.accel', at, refs, values: { alpha, inertia: kgmm2, torque: left } });
192
+ }
193
+ if (!s.task || limits.some((x) => x == null)) return limits;
194
+ const { r } = sample(s), frame = s.task.sheet ? s.task : null;
195
+ let worst = Infinity;
196
+ for (const x of r.samples) if (x.reachable) {
197
+ const J = jacobian(c, x.q), N = names.length, rows = J.map((row) => row.slice(0, N));
198
+ for (let d = 0; d < 12; d++) { const th = (d * Math.PI) / 6, v = [Math.cos(th), Math.sin(th), 0], lam = pinv2(rows, v); if (!lam) continue; let k = Infinity; for (let i = 0; i < N; i++) if (Math.abs(lam[i]) > 1e-12) k = Math.min(k, limits[i] / Math.abs(lam[i])); worst = Math.min(worst, k); }
199
+ }
200
+ if (worst === Infinity) return limits;
201
+ const accel = 0.7 * worst; s.task.accel = s.a.task.accel != null ? s.num(s.a.task.accel) : accel; void frame;
202
+ if (s.task.speed != null) {
203
+ const L = s.task.sheet ? Math.hypot(...(() => { const c0 = r.summary.corners; const a = c0[0].point, b = c0[2].point; return sub(a, b); })()) : 100, v = s.task.speed, a = s.task.accel, t = L > (v * v) / a ? v / a + L / v : 2 * Math.sqrt(L / a);
204
+ f('info', `a move across the task (${n3(L, 0)} mm) takes ${n3(t, 2)} s, at up to ${n3(worst, 0)} mm/s² at the tool, planned at ${n3(s.task.accel, 0)}`, null, { code: 'task.time', values: { time: t, accel: s.task.accel, limit: worst } });
205
+ }
206
+ return limits;
207
+ }
208
+ function pinv2(J, v) {
209
+ // Minimum-norm joint rates for a tool velocity, from a 2-row or 3-row Jacobian
210
+ const R = J.map((r) => r), n = R.length, M = R.map((a) => R.map((b) => a.reduce((t, x, i) => t + x * b[i], 0)));
211
+ const y = solveN(M.map((row, i) => [...row, v[i]])); return y && J[0].map((_, i) => R.reduce((t, r, k) => t + r[i] * y[k], 0));
212
+ function solveN(A) { const m = A.length; for (let c = 0; c < m; c++) { let p = c; for (let r = c + 1; r < m; r++) if (Math.abs(A[r][c]) > Math.abs(A[p][c])) p = r; [A[c], A[p]] = [A[p], A[c]]; if (Math.abs(A[c][c]) < 1e-9) { A[c][c] = 1e-9; } for (let r = 0; r < m; r++) if (r !== c) { const f = A[r][c] / A[c][c]; for (let k = c; k <= m; k++) A[r][k] -= f * A[c][k]; } } return A.map((r, i) => r[m] / r[i]); }
213
+ }
214
+
215
+ export function loadChecks(s, f, helpers) {
216
+ const motion = s.motion;
217
+ if (!motion?.joints?.length || !(s.task || s.a.gravity)) return;
218
+ const masses = massesOf(s, helpers), payload = s.task?.payload ? { kg: s.task.payload, item: motion.items.findIndex((x) => x[0] === s.task.item), point: s.task.point } : null;
219
+ const unknown = masses.filter((m) => !m.known).map((m) => m.id);
220
+ if (unknown.length && s.task) f('warn', `no mass known for ${unknown.join(', ')}: their rule sets give none, so they weigh nothing here`, 'masses unknown', { code: 'joint.moment.mass', refs: { items: unknown } });
221
+ s.jointLoads = momentChecks(s, f, helpers, masses, payload);
222
+ if (s.task?.payload != null || s.a.gravity) { const d = deflectionChecks(s, f, helpers, masses, payload); if (d && s.a.task?.deflection == null) s.task.deflection = d; }
223
+ accelChecks(s, f, helpers, masses, payload);
224
+ }
@@ -0,0 +1,92 @@
1
+ // One description of a machine, read from its assembly: the axes with the steps they take, where each comes from, and
2
+ // the task. cad plot plans a drawing on it, checks it against the task, and shows the result before anything moves.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { svgToStrokes, orderStrokes, planToolpath, stepBlocks, estimate, sheetFrame, fk } from '@rulecad/robots';
6
+ import { trainFrom, workingSpeed } from './motors.mjs';
7
+ import { chainOf, accuracyOf, sample, jacobianError } from './task.mjs';
8
+ import { paths } from './workspace.mjs';
9
+
10
+ const r6 = (x) => +Number(x).toFixed(6), n3 = (x, d = 2) => String(Number(x.toFixed(d)));
11
+
12
+ /** The machine as plain data. Every figure's origin is said in _why, by the name of the figure. @param {object} s a built assembly with a task */
13
+ export function machineOf(s) {
14
+ if (!s.task) throw new Error(`${s.project}/${s.name} has no "task": a machine says what it is for`);
15
+ const c = chainOf(s), motion = s.motion, specs = new Map((s.a.joints || []).map((j) => [j.id, j]));
16
+ const axes = c.names.map((id) => {
17
+ const t = trainFrom(motion, id), d = motion.drives.find((x) => x.joint === t.root), j = motion.joints.find((x) => x.id === id), spec = specs.get(id) ?? {};
18
+ if (!d?.model.stepAngle) throw new Error(`${s.project}/${s.name}: joint ${id} has no stepper driving it, and a step file needs one`);
19
+ const micro = d.spec.microsteps ?? 16, per = (360 / d.model.stepAngle) * micro, stepsPerUnit = j.type === 'prismatic' ? (per * t.ratio) / t.slide / 360 : (per * t.ratio) / 360;
20
+ const rpm = workingSpeed(d.model, d.spec), maxRate = (rpm / 60) * per, home = spec.home;
21
+ const homing = home ? { endstop: home.endstop, direction: home.direction ?? -1, rate: Math.round(maxRate / 8), back: Math.round(stepsPerUnit * 3) } : null;
22
+ return { name: id, joint: id, motor: d.id, model: d.model.name, driver: d.spec.driver ?? null, stepAngle: d.model.stepAngle, microsteps: micro, ratio: r6(t.ratio), stepsPerUnit: r6(stepsPerUnit), unit: j.type === 'prismatic' ? 'mm' : 'deg', limits: (j.limits ?? j.dofs[0].slice(0, 2)).map(r6), maxRate: Math.round(maxRate), homing,
23
+ _why: { stepAngle: `${d.model.name}.step_angle`, microsteps: d.spec.microsteps != null ? `the motor item's "microsteps" (resolution only, not accuracy)` : 'the default, 1/16 (resolution only, not accuracy)', ratio: t.stages.length ? `the train from ${t.root} to ${id}` : 'direct', maxRate: `${n3(rpm, 1)} rpm, ${d.spec.speed != null ? 'the motor item\'s speed' : `the working speed of a ${d.model.name}`}` } };
24
+ });
25
+ 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';
26
+ const pen = s.a.task.pen ?? null;
27
+ 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 }, ...(pen ? { pen } : {}) };
28
+ }
29
+
30
+ // A drawing's size against the sheet: the first stroke that leaves it, named
31
+ function fitsSheet(strokes, frame) {
32
+ const off = [];
33
+ for (const st of strokes) {
34
+ let worst = 0;
35
+ for (const p of st.points) worst = Math.max(worst, -p[0], p[0] - frame.width, -p[1], p[1] - frame.height);
36
+ if (worst > 1e-6) off.push({ stroke: st.name, by: worst });
37
+ }
38
+ return off.sort((a, b) => b.by - a.by);
39
+ }
40
+
41
+ export const CALIBRATION = (w, h) => {
42
+ const cx = w / 2, cy = h / 2, side = Math.min(100, Math.min(w, h) - 20), r = Math.min(15, (Math.min(w, h) - side) / 4 + 10);
43
+ const at = [[cx, cy], [cx - (side / 2 - r), cy - (side / 2 - r)], [cx + (side / 2 - r), cy + (side / 2 - r)]];
44
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}mm" height="${h}mm" viewBox="0 0 ${w} ${h}"><rect id="square" x="${cx - side / 2}" y="${cy - side / 2}" width="${side}" height="${side}" fill="none" stroke="black"/>${at.map(([x, y], i) => `<circle id="circle-${i + 1}" cx="${x}" cy="${y}" r="${r}" fill="none" stroke="black"/>`).join('')}</svg>`;
45
+ };
46
+
47
+ /**
48
+ * Plan a drawing on a machine. Refused (ok: false, nothing written) if it leaves the sheet or can't be reached.
49
+ * @param {object} s a built assembly with a task and a sheet @param {string} svg the drawing @param {{ tolerance?: number, name: string }} o
50
+ */
51
+ export function plot(s, svg, { tolerance, name } = {}) {
52
+ if (!s.task?.sheet) throw new Error(`${s.project}/${s.name}: plot draws on a "sheet", and the task has none`);
53
+ const m = machineOf(s), frame = sheetFrame(s.task.sheet), c = chainOf(s), tol = tolerance ?? Math.min(0.1, (s.task.accuracy ?? 0.3) / 3);
54
+ const page = svgToStrokes(svg, { tolerance: tol }), findings = [...page.findings], ok = () => findings.every((x) => x.level !== 'fail');
55
+ if (!page.strokes.length) return { ok: false, findings: [...findings, { level: 'fail', text: 'the drawing has no strokes', code: 'plot.empty' }] };
56
+ const off = fitsSheet(page.strokes, frame);
57
+ if (off.length) { findings.push({ level: 'fail', text: `stroke ${off[0].stroke} leaves the ${n3(frame.width, 0)} × ${n3(frame.height, 0)} mm sheet by ${n3(off[0].by)} mm${off.length > 1 ? `, and ${off.length - 1} more` : ''}: the drawing is larger than the sheet`, code: 'plot.sheet', refs: { stroke: off[0].stroke }, values: { by: off[0].by, count: off.length } }); return { ok: false, findings }; }
58
+ const ordered = orderStrokes(page, {}), plan = planToolpath(c, ordered, { tolerance: tol, elbow: m.elbow, sheet: s.task.sheet });
59
+ findings.push(...plan.findings);
60
+ if (!plan.ok) return { ok: false, findings, plan };
61
+ const speed = s.task.speed ?? 50, accel = m.task.accel, axes = m.axes.map((a) => ({ name: a.name, stepsPerUnit: a.stepsPerUnit, maxRate: a.maxRate }));
62
+ const steps = stepBlocks(plan, { axes, speed, accel, travelSpeed: speed * 2 });
63
+ // The pen-down lines, with what the budget predicts along them
64
+ const { list } = s.task.accuracy != null ? accuracyOf(s) : { list: null }, drawn = plan.moves.filter((x) => x.kind === 'draw').map((x) => ({ stroke: x.stroke, name: x.name, points: x.points.map((p) => p.map(r6)), error: list ? x.q.map((q) => +jacobianError(c, q, list, s.task.deflection).toFixed(4)) : null }));
65
+ const time = estimate(steps), out = { ...steps, machine: m.name, drawing: name, drawn };
66
+ findings.push(...steps.findings, { level: 'info', text: `${ordered.strokes?.length ?? ordered.length} strokes, ${n3(plan.length.draw, 0)} mm drawn, ${n3(plan.length.travel, 0)} mm of travel, ${n3(time.time, 1)} s, with tool speed ${speed} mm/s`, code: 'plot.time', values: { time: time.time, draw: plan.length.draw, travel: plan.length.travel } });
67
+ return { ok: ok(), findings, plan, steps: out, machine: m, time };
68
+ }
69
+
70
+ // An animated SVG: the sheet, the drawing appearing, the arm sweeping over it
71
+ export function animation(s, result) {
72
+ const { c } = sample(s), f = sheetFrame(s.task.sheet), plan = result.plan, moves = plan.moves, toS = (p) => { const d = p.map((x, k) => x - f.at[k]); return [r6(d[0] * f.u[0] + d[1] * f.u[1] + d[2] * f.u[2]), r6(-(d[0] * f.v[0] + d[1] * f.v[1] + d[2] * f.v[2]))]; };
73
+ const speed = s.task.speed ?? 50, frames = [];
74
+ let t = 0;
75
+ for (const m of moves) for (let i = 1; i < m.points.length; i++) { const dt = Math.hypot(...m.points[i].map((x, k) => x - m.points[i - 1][k])) / speed; frames.push({ t: t + dt, q: m.q[i], kind: m.kind }); t += dt; }
76
+ const every = Math.max(1, Math.floor(frames.length / 240)), keep = frames.filter((_, i) => !(i % every)), last = frames.at(-1) || { t: 1 }, T = last.t || 1;
77
+ const arm = (q) => armPoints(c, q).map(toS).map((p) => p.join(',')).join(' ');
78
+ const pts = [...moves.flatMap((m) => m.points.map(toS)), ...armPoints(c, moves[0].q[0]).map(toS)], lo = [0, 1].map((k) => Math.min(-f.width / 2 * (k ? f.height / f.width : 1), ...pts.map((p) => p[k]))), hi = [0, 1].map((k) => Math.max((k ? f.height : f.width) / 2, ...pts.map((p) => p[k])));
79
+ const m = 10, draw = result.steps.drawn;
80
+ const lines = draw.map((d, i) => { const len = d.points.reduce((a, p, j) => (j ? a + Math.hypot(...p.map((x, k) => x - d.points[j - 1][k])) : 0), 0), start = moves.slice(0, moves.findIndex((x) => x.kind === 'draw' && x.stroke === d.stroke)).reduce((a, x) => a + x.points.reduce((b, p, j) => (j ? b + Math.hypot(...p.map((v, k) => v - x.points[j - 1][k])) : 0), 0), 0) / speed; return `<polyline points="${d.points.map(toS).map((p) => p.join(',')).join(' ')}" fill="none" stroke="#135" stroke-width="0.5" stroke-dasharray="${len}" stroke-dashoffset="${len}"><animate attributeName="stroke-dashoffset" from="${len}" to="0" begin="${n3(start, 2)}s" dur="${n3(len / speed, 2)}s" fill="freeze"/></polyline>`; }).join('');
81
+ const values = keep.map((x) => arm(x.q)).join(';');
82
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${lo[0] - m} ${lo[1] - m} ${hi[0] - lo[0] + 2 * m} ${hi[1] - lo[1] + 2 * m}" width="${Math.round((hi[0] - lo[0] + 2 * m) * 3)}" height="${Math.round((hi[1] - lo[1] + 2 * m) * 3)}"><rect x="${-f.width / 2}" y="${-f.height / 2}" width="${f.width}" height="${f.height}" fill="#fff" stroke="#333" stroke-width="0.4"/>${lines}<polyline points="${arm(moves[0].q[0])}" fill="none" stroke="#c33" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><animate attributeName="points" dur="${n3(T, 2)}s" fill="freeze" values="${values}"/></polyline></svg>\n`;
83
+ }
84
+ const armPoints = (c, q) => { const F = fk(c, q); return [...F.frames.map((x) => x.at), F.position]; };
85
+
86
+ export function writePlot(s, result, base) {
87
+ const dir = paths.exports(s.project); fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, `${base}.steps.json`);
88
+ fs.writeFileSync(file, JSON.stringify(result.steps));
89
+ const prev = paths.preview(s.project, `${base}-plot.svg`); fs.mkdirSync(path.dirname(prev), { recursive: true }); fs.writeFileSync(prev, animation(s, result));
90
+ return { file, preview: prev };
91
+ }
92
+ export function writeMachine(s, m) { const dir = paths.exports(s.project); fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, `${s.name}.machine.json`); fs.writeFileSync(file, `${JSON.stringify(m, null, 2)}\n`); return file; }
package/lib/motors.mjs CHANGED
@@ -35,7 +35,8 @@ export function motorDrives(a, placed, joints, num) {
35
35
  if (id == null) { drives.push({ item: k, id: c.id, model: c.src.motor, spec: it.motor, joint: null }); return; } // on the bench, turning nothing
36
36
  const j = joints.find((x) => x.id === id);
37
37
  if (!j) throw new Error(`${what}: drives "${id}", which isn't a joint (${joints.map((x) => x.id).join(', ') || 'none'})`);
38
- if (j.type !== 'revolute') throw new Error(`${what}: a motor turns a revolute (${j.id} is a ${j.type}): drive the gear, and let the slide follow it`);
38
+ if (j.type === 'prismatic' && (it.motor.leadscrew || it.motor.belt)) j.slide = slideDrive(it.motor, what, j, num);
39
+ else if (j.type !== 'revolute') throw new Error(`${what}: a motor turns a revolute (${j.id} is a ${j.type}): drive the gear and let the slide follow it, or give "leadscrew" or "belt"`);
39
40
  if (j.follow) throw new Error(`${what}: ${j.id} follows ${j.follow[0]}: a motor drives the joint that leads the train`);
40
41
  if (taken.has(id)) throw new Error(`${what}: ${id} is driven by ${taken.get(id)} already: one motor to a joint`);
41
42
  taken.set(id, c.id);
@@ -51,6 +52,19 @@ export function motorDrives(a, placed, joints, num) {
51
52
  return drives;
52
53
  }
53
54
 
55
+ // A motor driving a slide directly, through a lead screw or a belt: mm per turn, how much power gets through, and whether
56
+ // it holds with the power off. A screw locks when its lead angle is under its friction angle
57
+ function slideDrive(spec, what, j, num) {
58
+ if (spec.leadscrew) {
59
+ const lead = num(spec.leadscrew.lead), d = num(spec.leadscrew.diameter ?? 8), mu = num(spec.leadscrew.friction ?? 0.2), lambda = Math.atan(lead / (Math.PI * d)), phi = Math.atan(mu);
60
+ if (!(lead > 0)) throw new Error(`${what}: a lead screw's lead is above 0 mm (got ${lead})`);
61
+ return { kind: 'screw', mmPerTurn: lead, efficiency: Math.tan(lambda) / Math.tan(lambda + phi), locks: lambda < phi ? `the lead screw (its ${n3((lambda * 180) / Math.PI, 1)}° lead is under the ${n3((phi * 180) / Math.PI, 1)}° friction angle)` : null, detail: `a ${lead} mm lead` };
62
+ }
63
+ const pitch = num(spec.belt.pitch ?? 2), teeth = num(spec.belt.teeth);
64
+ if (!(teeth > 0)) throw new Error(`${what}: a belt needs its pulley's "teeth"`);
65
+ return { kind: 'belt', mmPerTurn: teeth * pitch, efficiency: 0.95, locks: null, detail: `a ${teeth} T pulley`, stretch: spec.belt.stiffness != null ? { k: num(spec.belt.stiffness), width: num(spec.belt.width ?? 6), length: num(spec.belt.length ?? 300), load: num(spec.belt.load ?? 5) } : null };
66
+ }
67
+
54
68
  // The fits a motor brings with it, in the assembly's own shape
55
69
  export const shaftFits = (drives, joints, ids) => drives.filter((d) => d.joint && d.model.shaft.length).map((d) => ({ a: `${d.id}.shaft`, b: ids[joints.find((j) => j.id === d.joint).child], min: -1000, silent: true }));
56
70
 
@@ -69,9 +83,10 @@ export function loadsOf(a, anchor, num, joints) {
69
83
  // ---------- the train from a motor to a joint ----------
70
84
  // Walks up the follow links from a joint to the one that leads it: the turns of that lead per turn of this joint
71
85
  // (or per mm, where the joint slides), the share of power that gets through, what's in the way.
72
- function trainFrom(motion, id) {
86
+ export function trainFrom(motion, id) {
73
87
  const stages = [], meshes = motion.meshes || [];
74
88
  let j = motion.joints.find((x) => x.id === id), ratio = 1, efficiency = 1, slide = j.type === 'prismatic' ? 1 : null, locks = null;
89
+ if (j.slide) return { root: j.id, ratio: 1, efficiency: j.slide.efficiency, stages: [{ joint: j.id, kind: j.slide.kind, ratio: 1, efficiency: j.slide.efficiency }], slide: j.slide.mmPerTurn / 360, locks: j.slide.locks };
75
90
  while (j.follow) {
76
91
  const [lead, r] = j.follow, m = meshes.find((x) => x.joint === j.id) || meshes.find((x) => x.planetary && (x.members || []).includes(j.id));
77
92
  const kind = m?.kind === 'external' ? 'spur' : m?.kind || 'spur';
@@ -120,8 +135,11 @@ function worstLoad(motion, loads, j, drive, { placeItems, jointValues, mul }) {
120
135
  return { torque: Math.abs(worst), where };
121
136
  }
122
137
 
138
+ // What a stepper gives at the current it's set to: torque goes with the current, up to its rating
139
+ export const atCurrent = (m, spec, torque) => (m.type === 'stepper' && spec.current != null && m.figures.rated_current?.value ? torque * Math.min(1, spec.current / m.figures.rated_current.value) : torque);
140
+
123
141
  // A motor's speed if the assembly doesn't say: its corner speed, its rated speed, or half its free speed
124
- function workingSpeed(model, spec) {
142
+ export function workingSpeed(model, spec) {
125
143
  if (spec.speed != null) return spec.speed;
126
144
  const p = performance(model, {});
127
145
  return model.type === 'dc' ? p.limit / 2 : model.figures.pull_in_torque ? p.limit : model.type === 'servo' ? p.limit : model.type === 'brushless' ? p.limit / 4 : p.limit / 5;
@@ -133,7 +151,7 @@ const material = (name) => { const n = String(name || 'pla').toLowerCase().split
133
151
  export function motorChecks(s, f, helpers, materialName) {
134
152
  const motion = s.motion, drives = motion?.drives || [], loads = motion?.loads || [], { placeItems, jointValues, mul } = helpers;
135
153
  if (!drives.length) { if (loads.length) f('warn', `there are loads, but no motor: nothing has been checked against them (add a "motor" item that "drives" a joint)`, null, { code: 'motor.loads' }); return; }
136
- const worlds = placeItems(motion, jointValues(motion, motion.pose ?? undefined));
154
+ const worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined));
137
155
  for (const d of drives) {
138
156
  const m = d.model, grams = n3(m.mass * 1000, 1), K = d.spec.margin != null ? d.spec.margin : 2, W = worlds[d.item];
139
157
  f('info', `${d.id}: ${m.name}, ${grams} g${d.joint ? `, drives ${d.joint}` : ''}${m.stepAngle ? `, ${n3(m.stepAngle, 4)}° a step` : ''}${m.range ? `, ${m.range}° of travel` : ''}`, null, { code: 'motor.model', refs: { item: d.id, joint: d.joint }, values: { model: m.name, grams: m.mass * 1000, stepAngle: m.stepAngle } });
@@ -166,7 +184,7 @@ export function motorChecks(s, f, helpers, materialName) {
166
184
  back += (atLead / reduction) * ηback; backOn += atLead / reduction;
167
185
  lines.push({ x, t, load, unit, reduction, atLead, η });
168
186
  }
169
- const speedOut = motorSpeed / loaded[0].t.ratio, rated = performance(m, { speed: motorSpeed }), avail = rated.motor.torque, margin = need ? avail / need : Infinity;
187
+ const speedOut = motorSpeed / loaded[0].t.ratio, rated = performance(m, { speed: motorSpeed }), avail = atCurrent(m, d.spec, rated.motor.torque), margin = need ? avail / need : Infinity;
170
188
  const main = lines[0], what = main.unit === 'N m' ? `${n3(main.load.torque)} N m` : `${n3(main.load.torque, 2)} N`, gives = main.unit === 'N m' ? `${n3(avail * main.reduction * main.η)} N m` : `${n3((avail * main.reduction * main.η * Math.PI * 1000) / (main.t.slide * 180), 1)} N`;
171
189
  const trust = rated.rests.filter((k) => k !== 'spec' && k !== 'measured'), caveat = trust.length ? ` (rests on ${trust.join(' and ')} figures: measure it)` : '';
172
190
  const level = margin < 1 ? 'fail' : margin < K ? 'warn' : 'pass', fix = margin < 1 && main.t.slide == null ? ` A ratio of ${n3((main.reduction * K) / margin, 1)}:1 would give it ${K} times` : '';
@@ -179,7 +197,7 @@ export function motorChecks(s, f, helpers, materialName) {
179
197
  mountCheck(s, d, f, W, avail, materialName);
180
198
  // Does it hold?
181
199
  const fig = (k) => m.figures[k]?.value, kt = m.type === 'brushless' ? 60 / (2 * Math.PI * fig('kv')) : 0;
182
- const on = fig('holding_torque') ?? fig('stall_torque') ?? (kt ? kt * fig('rated_current') : 0), off_ = fig('detent_torque') ?? fig('friction_torque') ?? null, brake = lines.map((l) => motion.joints.find((x) => x.id === l.x.id)?.brake).find(Boolean) ?? motion.joints.find((x) => x.id === d.joint)?.brake;
200
+ const on = atCurrent(m, d.spec, fig('holding_torque') ?? fig('stall_torque') ?? (kt ? kt * fig('rated_current') : 0)), off_ = fig('detent_torque') ?? fig('friction_torque') ?? null, brake = lines.map((l) => motion.joints.find((x) => x.id === l.x.id)?.brake).find(Boolean) ?? motion.joints.find((x) => x.id === d.joint)?.brake;
183
201
  const backS = n3(back), pmargin = backOn ? on / backOn : Infinity;
184
202
  if (locked || brake) f('pass', `${main.x.id} holds with the power off: ${brake ? `its brake (${brake})` : locked} is what holds it`, null, { code: 'motor.holds', at: at(main.x) });
185
203
  else if (off_ != null && back <= off_) f('pass', `${main.x.id} holds with the power off: ${backS} N m back at the motor against ${n3(off_)} N m of ${fig('detent_torque') != null ? 'detent' : 'gearbox friction'}`, null, { code: 'motor.holds', at: at(main.x) });
@@ -191,8 +209,8 @@ export function motorChecks(s, f, helpers, materialName) {
191
209
  const mat = material(materialName), rise = fig('temperature_rise');
192
210
  if (mat?.softening != null && rise != null) {
193
211
  const duty = d.spec.duty != null ? d.spec.duty : 1, room = 25, caseT = room + rise * duty, ok = caseT <= mat.softening, name = mat.name.toUpperCase(), I = fig('rated_current');
194
- if (ok) f('pass', `${d.id}'s case reaches at most ${n3(caseT, 1)} °C ${duty < 1 ? `at ${n3(duty * 100, 0)}% duty` : 'at rated current'}, under ${name}'s ${mat.softening} °C`, null, { code: 'motor.heat', at: S });
195
- else { const k = Math.sqrt((mat.softening - room) / (rise * duty)); f('warn', `${d.id}'s case can reach ${n3(caseT, 1)} °C at rated current, past where ${name} softens (${mat.softening} °C). Set the driver to ${I ? `${n3(I * k, 2)} A` : `${n3(k * 100, 0)}% of its current`} (${n3(k * 100, 0)}% of the torque), or print the mount in a material that takes it`, `${d.id}: mount will soften`, { code: 'motor.heat', at: S, values: { case: caseT, softening: mat.softening } }); }
212
+ if (ok) f('pass', `${d.id}'s case reaches at most ${n3(caseT, 1)} °C ${duty < 1 ? `at ${n3(duty * 100, 0)}% duty` : 'at rated current'}, under ${name}'s ${mat.softening} °C`, null, { code: 'motor.heat', at: S, refs: { item: d.id }, values: { case: caseT, softening: mat.softening } });
213
+ else { const k = Math.sqrt((mat.softening - room) / (rise * duty)); f('warn', `${d.id}'s case can reach ${n3(caseT, 1)} °C at rated current, past where ${name} softens (${mat.softening} °C). Set the driver to ${I ? `${n3(I * k, 2)} A` : `${n3(k * 100, 0)}% of its current`} (${n3(k * 100, 0)}% of the torque), or print the mount in a material that takes it`, `${d.id}: mount will soften`, { code: 'motor.heat', at: S, refs: { item: d.id }, values: { case: caseT, softening: mat.softening } }); }
196
214
  }
197
215
  }
198
216
  }
@@ -220,7 +238,7 @@ export function shaftFit(x, s, f, { placeItems, jointValues, mul, materialName,
220
238
  // (a printed hole comes out holeComp smaller across, so a drawn bore is that much tighter on the real shaft)
221
239
  const motion = s.motion, top = (n) => String(n).split(/[.@]/)[0], drives = motion?.drives || [], d = drives.find((y) => y.id === top(x.a) || y.id === top(x.b)), other = d && (top(x.a) === d.id ? top(x.b) : top(x.a)), label = x.note || `${d?.id ?? x.a}'s shaft in ${other ?? x.b}`;
222
240
  if (!d) return f('fail', `${label}: neither ${x.a} nor ${x.b} is a motor`, null, { code: 'shaft.motor' });
223
- const worlds = placeItems(motion, jointValues(motion, motion.pose ?? undefined)), W = worlds[d.item], m = d.model, S = m.shaft, r = S.diameter / 2;
241
+ const worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined)), W = worlds[d.item], m = d.model, S = m.shaft, r = S.diameter / 2;
224
242
  const inv = (p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
225
243
  const parts = s.parts.filter((p) => p.item === other || p.leaf === other);
226
244
  if (!parts.length) return f('fail', `${label}: no part "${other}"`, null, { code: 'shaft.part' });