@rulecad/cad 0.7.97 → 0.9.0

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.
Files changed (86) hide show
  1. package/AGENTS.md +26 -10
  2. package/CHANGELOG.md +442 -2
  3. package/EXAMPLES.md +48 -42
  4. package/README.md +226 -73
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2253 -514
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1854 -437
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +734 -113
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +900 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2710 -502
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +792 -176
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +149 -18
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +3 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1022 -212
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +41 -0
  57. package/lib/optimise.mjs +979 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +224 -36
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +38 -4
  68. package/lib/sandbox-hooks.mjs +154 -12
  69. package/lib/sandbox-preload.mjs +2 -2
  70. package/lib/sandbox-run.mjs +127 -12
  71. package/lib/sandbox.mjs +632 -35
  72. package/lib/schema.mjs +43 -11
  73. package/lib/seats.mjs +227 -49
  74. package/lib/services.mjs +261 -52
  75. package/lib/sheet.mjs +851 -178
  76. package/lib/slotnuts.mjs +213 -34
  77. package/lib/targets/gist.mjs +4 -1
  78. package/lib/targets.mjs +42 -6
  79. package/lib/task.mjs +376 -79
  80. package/lib/versions.mjs +113 -28
  81. package/lib/wires.mjs +228 -45
  82. package/lib/workspace.mjs +216 -17
  83. package/package.json +19 -19
  84. package/schemas/assembly.schema.json +2 -2
  85. package/schemas/object.schema.json +1 -1
  86. package/schemas/project.schema.json +1 -1
package/lib/versions.mjs CHANGED
@@ -11,10 +11,13 @@ import { fileURLToPath } from 'node:url';
11
11
  import crypto from 'node:crypto';
12
12
  import { resolve, loadRuleSet } from './rules.mjs';
13
13
  import { WS, paths } from './workspace.mjs';
14
+ import { readJson, readOwnText } from './host.mjs';
15
+ import { plainName, isPlainName } from './names.mjs';
14
16
  import { readLayout, hasLayout } from './layout.mjs';
15
17
  import { newer } from '@rulecad/versions';
16
18
 
17
- export const git = (...args) => execFileSync('git', args, { cwd: WS, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trimEnd();
19
+ export const git = (...args) =>
20
+ execFileSync('git', args, { cwd: WS, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trimEnd();
18
21
 
19
22
  // ---------- semver: @rulecad/versions ----------
20
23
  export { parse, bump, newer, bigger, compare } from '@rulecad/versions';
@@ -24,17 +27,34 @@ export { parse, bump, newer, bigger, compare } from '@rulecad/versions';
24
27
  export function tags(project, name) {
25
28
  const prefix = name ? `${project}/${name}@` : `${project}@`;
26
29
  let out;
27
- try { out = git('for-each-ref', `refs/tags/${prefix}*`, '--format=%(refname:strip=2)%09%(creatordate:short)%09%(contents:subject)'); }
28
- catch (e) { if (/not a git repository/.test(e.stderr || e.message)) return []; throw e; } // a workspace outside git: no releases yet
29
- return out.split('\n').filter(Boolean).map((l) => {
30
- const [tag, date, subject = ''] = l.split('\t'), [, kind, message] = subject.match(/^(major|minor|patch|first): (.*)$/) || [, '', subject];
31
- return { tag, version: tag.slice(prefix.length), date, kind, message };
32
- }).filter((t) => /^\d+\.\d+\.\d+$/.test(t.version)).sort((a, b) => (newer(a.version, b.version) ? 1 : -1));
30
+ try {
31
+ out = git(
32
+ 'for-each-ref',
33
+ `refs/tags/${prefix}*`,
34
+ '--format=%(refname:strip=2)%09%(creatordate:short)%09%(contents:subject)',
35
+ );
36
+ } catch (e) {
37
+ if (/not a git repository/.test(e.stderr || e.message)) return [];
38
+ throw e;
39
+ } // a workspace outside git: no releases yet
40
+ return out
41
+ .split('\n')
42
+ .filter(Boolean)
43
+ .map((l) => {
44
+ const [tag, date, subject = ''] = l.split('\t'),
45
+ [, kind, message] = subject.match(/^(major|minor|patch|first): (.*)$/) || [, '', subject];
46
+ return { tag, version: tag.slice(prefix.length), date, kind, message };
47
+ })
48
+ .filter((t) => /^\d+\.\d+\.\d+$/.test(t.version))
49
+ .sort((a, b) => (newer(a.version, b.version) ? 1 : -1));
33
50
  }
34
51
 
35
52
  // The layout files an object can pick (its layout variables' choices that are files), by name
36
- const layoutNames = (d, object) => Object.values(object.variables || {}).filter((v) => v.type === 'layout')
37
- .flatMap((v) => v.choice || [v.value]).filter((n) => hasLayout(d.project, n, d.layoutsDir));
53
+ const layoutNames = (d, object) =>
54
+ Object.values(object.variables || {})
55
+ .filter((v) => v.type === 'layout')
56
+ .flatMap((v) => v.choice || [v.value])
57
+ .filter((n) => hasLayout(d.project, n, d.layoutsDir));
38
58
 
39
59
  // A file's path in git's terms: relative to the workspace, forward slashes on every system (git show tag:path needs them)
40
60
  const rel = (f) => path.relative(WS, f).split(path.sep).join('/');
@@ -42,27 +62,54 @@ const rel = (f) => path.relative(WS, f).split(path.sep).join('/');
42
62
  // The files a design depends on, relative to the workspace (its git repo): its .js and .json, the rule sets and the layouts it uses.
43
63
  // (A board's engine is the tool's code, not the workspace's: its release records engineId() instead.)
44
64
  export function files(d, object) {
45
- return [rel(d.js), rel(d.json), ...(object.uses || []).filter((u) => !u.includes('/')).map((u) => `rules/${u}.json`),
46
- ...layoutNames(d, object).map((n) => `projects/${d.project}/layouts/${n}.json`)];
65
+ return [
66
+ rel(d.js),
67
+ rel(d.json),
68
+ ...(object.uses || []).filter((u) => !u.includes('/')).map((u) => `rules/${u}.json`),
69
+ ...layoutNames(d, object).map((n) => `projects/${d.project}/layouts/${n}.json`),
70
+ ];
47
71
  }
48
72
 
49
73
  // A released version's files, written under .versions/ so its imports still find node_modules. -> a design to build
50
74
  export function materialise(d, version) {
51
75
  const tag = `${d.project}/${d.name}@${version}`;
52
- try { git('rev-parse', '--verify', `refs/tags/${tag}`); } catch { throw new Error(`no release ${tag} (releases: ${tags(d.project, d.name).map((t) => t.version).join(', ') || 'none'})`); }
76
+ try {
77
+ git('rev-parse', '--verify', `refs/tags/${tag}`);
78
+ } catch {
79
+ throw new Error(
80
+ `no release ${tag} (releases: ${
81
+ tags(d.project, d.name)
82
+ .map((t) => t.version)
83
+ .join(', ') || 'none'
84
+ })`,
85
+ );
86
+ }
53
87
  const base = paths.versions(d.project, `${d.name}@${version}`);
54
88
  const show = (rel) => git('show', `${tag}:${rel}`);
55
89
  const object = JSON.parse(show(rel(d.json)));
56
90
  fs.mkdirSync(path.join(base, 'rules'), { recursive: true });
57
- const js = path.join(base, `${d.name}.js`), json = path.join(base, `${d.name}.json`);
91
+ const js = path.join(base, `${d.name}.js`),
92
+ json = path.join(base, `${d.name}.json`);
58
93
  fs.writeFileSync(js, show(rel(d.js)));
59
94
  fs.writeFileSync(json, JSON.stringify(object, null, 2));
60
- for (const u of (object.uses || []).filter((x) => !x.includes('/'))) fs.writeFileSync(path.join(base, 'rules', `${u}.json`), show(`rules/${u}.json`)); // objects it reads are released on their own
95
+ // (names from the release's own file, each written as a file here: plain names only, never ../)
96
+ for (const u of (object.uses || []).filter((x) => !x.includes('/')))
97
+ fs.writeFileSync(
98
+ path.join(base, 'rules', `${plainName(u, 'rule set name', `${tag}'s ${d.name}.json, in its "uses"`)}.json`),
99
+ show(`rules/${u}.json`),
100
+ ); // objects it reads are released on their own
61
101
  // The layouts it could pick, as they were then (only files that existed in that release)
62
102
  fs.mkdirSync(path.join(base, 'layouts'), { recursive: true });
63
- for (const v of Object.values(object.variables || {})) if (v.type === 'layout') for (const n of v.choice || [v.value]) {
64
- try { fs.writeFileSync(path.join(base, 'layouts', `${n}.json`), show(`projects/${d.project}/layouts/${n}.json`)); } catch {} // a built-in (grid)
65
- }
103
+ for (const v of Object.values(object.variables || {}))
104
+ if (v.type === 'layout')
105
+ for (const n of (v.choice || [v.value]).filter(isPlainName)) {
106
+ // (another name is refused where the layout is read)
107
+ try {
108
+ fs.writeFileSync(path.join(base, 'layouts', `${n}.json`), show(`projects/${d.project}/layouts/${n}.json`));
109
+ } catch {
110
+ // (a built-in layout (grid): nothing to write)
111
+ }
112
+ }
66
113
  return { ...d, js, json, rulesDir: path.join(base, 'rules'), layoutsDir: path.join(base, 'layouts'), version, tag };
67
114
  }
68
115
 
@@ -75,18 +122,35 @@ export function materialise(d, version) {
75
122
  export function packageVersion(name, from = import.meta.url) {
76
123
  for (let dir = path.dirname(createRequire(from).resolve(name)); dir !== path.dirname(dir); dir = path.dirname(dir)) {
77
124
  const f = path.join(dir, 'package.json');
78
- if (fs.existsSync(f)) { const pj = JSON.parse(fs.readFileSync(f, 'utf8')); if (pj.name === name) return pj.version; }
125
+ if (fs.existsSync(f)) {
126
+ const pj = JSON.parse(fs.readFileSync(f, 'utf8'));
127
+ if (pj.name === name) return pj.version;
128
+ }
79
129
  }
80
130
  return '';
81
131
  }
82
- const ENGINE_LIBS = ['@tscircuit/capacity-autorouter', '@tscircuit/footprinter', '@tscircuit/checks', 'schematic-symbols'];
83
- const engineLibs = () => ENGINE_LIBS.map((n) => `${n}@${packageVersion(n, import.meta.resolve('@rulecad/pcb'))}`).join(' ');
84
- const engineHash = (code) => crypto.createHash('sha256').update(`${code.trimEnd()}\n${engineLibs()}`).digest('hex').slice(0, 16);
132
+ const ENGINE_LIBS = [
133
+ '@tscircuit/capacity-autorouter',
134
+ '@tscircuit/footprinter',
135
+ '@tscircuit/checks',
136
+ 'schematic-symbols',
137
+ ];
138
+ const engineLibs = () =>
139
+ ENGINE_LIBS.map((n) => `${n}@${packageVersion(n, import.meta.resolve('@rulecad/pcb'))}`).join(' ');
140
+ const engineHash = (code) =>
141
+ crypto.createHash('sha256').update(`${code.trimEnd()}\n${engineLibs()}`).digest('hex').slice(0, 16);
85
142
  // The board engine's code: @rulecad/pcb's modules, and @rulecad/smooth's, which a board's build runs too (smoothing its
86
143
  // tracks, finishing them): a change to either is a change to what a board builds, so it must miss the cache
87
- const sources = (dir) => fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs').sort().map((f) => fs.readFileSync(path.join(dir, f), 'utf8')).join('\n');
144
+ const sources = (dir) =>
145
+ fs
146
+ .readdirSync(dir)
147
+ .filter((f) => f.endsWith('.mjs') && f !== 'test.mjs' && !f.startsWith('.'))
148
+ .sort()
149
+ .map((f) => fs.readFileSync(path.join(dir, f), 'utf8'))
150
+ .join('\n');
88
151
  export const engineId = () => {
89
- const pcb = import.meta.resolve('@rulecad/pcb'), dir = path.dirname(fileURLToPath(pcb));
152
+ const pcb = import.meta.resolve('@rulecad/pcb'),
153
+ dir = path.dirname(fileURLToPath(pcb));
90
154
  const smooth = path.dirname(createRequire(pcb).resolve('@rulecad/smooth'));
91
155
  return engineHash(`${sources(dir)}\n${sources(smooth)}`);
92
156
  };
@@ -94,18 +158,35 @@ export const engineId = () => {
94
158
  function taggedEngine(tag) {
95
159
  const m = git('tag', '-l', '--format=%(contents)', tag).match(/^engine: (\w+)$/m);
96
160
  if (m) return m[1];
97
- try { return engineHash(git('show', `${tag}:lib/pcb.mjs`)); } catch { return ''; } // (the engine once lived in the workspace)
161
+ try {
162
+ return engineHash(git('show', `${tag}:lib/pcb.mjs`));
163
+ } catch {
164
+ return '';
165
+ } // (the engine once lived in the workspace)
98
166
  }
99
167
 
100
168
  // Resolve a design as it is on disk, or as materialised from a release.
101
169
  // refs: the numbers of objects it reads (design.mjs objectSets), which a snapshot can't build itself.
102
170
  export function snapshot(d, refs = {}) {
103
- const object = JSON.parse(fs.readFileSync(d.json, 'utf8'));
104
- const sets = { ...(d.rulesDir ? Object.fromEntries((object.uses || []).filter((u) => !u.includes('/')).map((u) => [u, loadRuleSet(u, d.rulesDir)])) : {}), ...refs };
171
+ const object = readJson(d.json); // (the workspace's own files only where they really are inside it: host.mjs)
172
+ const sets = {
173
+ ...(d.rulesDir
174
+ ? Object.fromEntries(
175
+ (object.uses || []).filter((u) => !u.includes('/')).map((u) => [u, loadRuleSet(u, d.rulesDir)]),
176
+ )
177
+ : {}),
178
+ ...refs,
179
+ };
105
180
  const layouts = Object.fromEntries(layoutNames(d, object).map((n) => [n, readLayout(d.project, n, d.layoutsDir)]));
106
181
  // A board is also made by the board engine (footprints, the router): which engine, as recorded at the release
107
182
  const engine = object.engine === 'pcb' ? (d.tag ? taggedEngine(d.tag) : engineId()) : null;
108
- return { object, entries: resolve(object, { sets }).entries, js: fs.readFileSync(d.js, 'utf8'), layouts, ...(engine != null ? { engine } : {}) };
183
+ return {
184
+ object,
185
+ entries: resolve(object, { sets }).entries,
186
+ js: readOwnText(d.js),
187
+ layouts,
188
+ ...(engine != null ? { engine } : {}),
189
+ };
109
190
  }
110
191
 
111
192
  // ---------- prints log ----------
@@ -114,5 +195,9 @@ export const printsFile = (d) => path.join(d.dir, 'prints.jsonl');
114
195
  export function prints(d) {
115
196
  const f = printsFile(d);
116
197
  if (!fs.existsSync(f)) return [];
117
- return fs.readFileSync(f, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)).filter((p) => !d.name || p.object === d.name);
198
+ return readOwnText(f)
199
+ .split('\n')
200
+ .filter(Boolean)
201
+ .map((l) => JSON.parse(l))
202
+ .filter((p) => !d.name || p.object === d.name);
118
203
  }
package/lib/wires.mjs CHANGED
@@ -6,26 +6,61 @@ import { placeItems, jointValues, mul } from '@rulecad/model-link';
6
6
 
7
7
  const n3 = (x, d = 1) => String(Number(x.toFixed(d)));
8
8
  const GAUGE = /^awg(\d{1,2})$/i;
9
- const areaOf = (gauge, base) => { const d = base * Math.pow(92, (36 - gauge) / 39); return (Math.PI * d * d) / 4; };
9
+ const areaOf = (gauge, base) => {
10
+ const d = base * Math.pow(92, (36 - gauge) / 39);
11
+ return (Math.PI * d * d) / 4;
12
+ };
10
13
 
11
14
  // Anchors to world points at given joint values
12
- function pointer(s, { placeItems, jointValues, mul, marksOf }) {
13
- const motion = s.motion, ids = motion.items.map((x) => x[0]);
15
+ function pointer(s, { mul }) {
16
+ const motion = s.motion,
17
+ ids = motion.items.map((x) => x[0]);
14
18
  const marks = (id, name) => motion.marks.find((m) => m.id === id && m.name === name);
15
19
  return (ref, what) => {
16
- const bits = String(ref).split('.'), name = bits.pop(), id = bits.join('.'), m = marks(id, name);
17
- if (!m) throw new Error(`${what}: no anchor "${ref}" (give <item>.<anchor>${ids.includes(id) ? `; ${id} has ${motion.marks.filter((x) => x.id === id).map((x) => x.name).join(', ') || 'none'}` : ''})`);
18
- const k = ids.indexOf(id), F = m.frame;
19
- return (worlds) => { const W = mul(worlds[k], F); return [W[3], W[7], W[11]]; };
20
+ const bits = String(ref).split('.'),
21
+ name = bits.pop(),
22
+ id = bits.join('.'),
23
+ m = marks(id, name);
24
+ if (!m)
25
+ throw new Error(
26
+ `${what}: no anchor "${ref}" (give <item>.<anchor>${
27
+ ids.includes(id)
28
+ ? `; ${id} has ${
29
+ motion.marks
30
+ .filter((x) => x.id === id)
31
+ .map((x) => x.name)
32
+ .join(', ') || 'none'
33
+ }`
34
+ : ''
35
+ })`,
36
+ );
37
+ const k = ids.indexOf(id),
38
+ F = m.frame;
39
+ return (worlds) => {
40
+ const W = mul(worlds[k], F);
41
+ return [W[3], W[7], W[11]];
42
+ };
20
43
  };
21
44
  }
22
45
  // Joint values to try: each named pose, each moving joint at its ends and middle, all together when few enough
23
46
  function samples(motion, jointValues) {
24
- const base = jointValues(motion, motion.pose ?? undefined), free = motion.joints.filter((j) => !j.follow && j.type !== 'fixed' && j.dofs.length === 1), out = [base];
47
+ const base = jointValues(motion, motion.pose ?? undefined),
48
+ free = motion.joints.filter((j) => !j.follow && j.type !== 'fixed' && j.dofs.length === 1),
49
+ out = [base];
25
50
  for (const p of Object.keys(motion.poses || {})) out.push(jointValues(motion, p));
26
- const levels = (j) => { const [lo, hi] = j.dofs[0]; return [lo, (lo + hi) / 2, hi]; }, leads = Object.fromEntries(Object.entries(base).filter(([id]) => !motion.joints.find((x) => x.id === id)?.follow));
51
+ const levels = (j) => {
52
+ const [lo, hi] = j.dofs[0];
53
+ return [lo, (lo + hi) / 2, hi];
54
+ },
55
+ leads = Object.fromEntries(Object.entries(base).filter(([id]) => !motion.joints.find((x) => x.id === id)?.follow));
27
56
  if (free.length && free.length <= 5) {
28
- const go = (i, set) => { if (i === free.length) { out.push(jointValues(motion, set)); return; } for (const v of levels(free[i])) go(i + 1, { ...set, [free[i].id]: [v] }); };
57
+ const go = (i, set) => {
58
+ if (i === free.length) {
59
+ out.push(jointValues(motion, set));
60
+ return;
61
+ }
62
+ for (const v of levels(free[i])) go(i + 1, { ...set, [free[i].id]: [v] });
63
+ };
29
64
  go(0, leads);
30
65
  } else for (const j of free) for (const v of levels(j)) out.push(jointValues(motion, { ...leads, [j.id]: [v] }));
31
66
  return out;
@@ -37,8 +72,11 @@ export function wiresOf(a, placed, joints) {
37
72
  const what = `wire ${w.id || i + 1}`;
38
73
  if (!w.from || !w.to) throw new Error(`${what}: give "from" and "to", anchors as <item>.<anchor>`);
39
74
  const g = GAUGE.exec(String(w.gauge ?? ''));
40
- if (w.gauge != null && !g) throw new Error(`${what}: gauge is awg and a number (awg22), not ${JSON.stringify(w.gauge)}`);
41
- for (const v of w.via ?? []) if (typeof v === 'string' && !v.includes('.') && !joints.some((j) => j.id === v && j.type === 'path')) throw new Error(`${what}: via "${v}" is neither an anchor (<item>.<anchor>) nor a path joint`);
75
+ if (w.gauge != null && !g)
76
+ throw new Error(`${what}: gauge is awg and a number (awg22), not ${JSON.stringify(w.gauge)}`);
77
+ for (const v of w.via ?? [])
78
+ if (typeof v === 'string' && !v.includes('.') && !joints.some((j) => j.id === v && j.type === 'path'))
79
+ throw new Error(`${what}: via "${v}" is neither an anchor (<item>.<anchor>) nor a path joint`);
42
80
  return { ...w, id: w.id || `w${i + 1}` };
43
81
  });
44
82
  }
@@ -47,14 +85,19 @@ export function wiresOf(a, placed, joints) {
47
85
  function currentOf(w, s, top, signal) {
48
86
  if (w.current != null) return { current: Number(w.current), why: 'as given' };
49
87
  const motors = s.motion.drives.filter((d) => [top(w.from), top(w.to)].includes(d.id));
50
- for (const d of motors) { const I = d.spec.current ?? d.model.figures.rated_current?.value; if (I != null) return { current: I, why: `${d.id}'s rated current` }; }
88
+ for (const d of motors) {
89
+ const I = d.spec.current ?? d.model.figures.rated_current?.value;
90
+ if (I != null) return { current: I, why: `${d.id}'s rated current` };
91
+ }
51
92
  return { current: signal, why: 'a signal' };
52
93
  }
53
94
 
54
95
  // A wire ending on a board's axis connector: the board's pins for that axis, from its rule set
55
96
  export function pinsAt(w, s) {
56
97
  for (const end of [w.from, w.to]) {
57
- const [id, anchor] = String(end).split('.'), o = s.objects.find((x) => x.id === id && x.bought?.part === 'board'), e = o?.built.entries;
98
+ const [id, anchor] = String(end).split('.'),
99
+ o = s.objects.find((x) => x.id === id && x.bought?.part === 'board'),
100
+ e = o?.built.entries;
58
101
  if (!e || !/^[A-Z]\d?$/.test(anchor ?? '')) continue; // (a shield's X, Y, Z; a Mega's S0 to S7)
59
102
  const pin = (k) => e.find((x) => x.name === `${o.bought.set}.${k}_pin_${anchor.toLowerCase()}`)?.value;
60
103
  if (!pin('step')) continue;
@@ -68,64 +111,188 @@ export function pinsAt(w, s) {
68
111
  }
69
112
 
70
113
  export function wireRows(s, helpers) {
71
- const motion = s.motion, wires = s.wires; if (!wires?.length) return [];
72
- const rules = loadRuleSet('wire').rules, density = rules.current_density.value, loop = rules.service_loop.value, base = rules.awg_base.value, signal = rules.signal_current.value;
73
- const point = pointer(s, helpers), { placeItems, jointValues } = helpers, top = (n) => String(n).split('.')[0], poses = samples(motion, jointValues).map((v) => placeItems(motion, v));
114
+ const motion = s.motion,
115
+ wires = s.wires;
116
+ if (!wires?.length) return [];
117
+ const rules = loadRuleSet('wire').rules,
118
+ density = rules.current_density.value,
119
+ loop = rules.service_loop.value,
120
+ base = rules.awg_base.value,
121
+ signal = rules.signal_current.value;
122
+ const point = pointer(s, helpers),
123
+ { placeItems, jointValues } = helpers,
124
+ top = (n) => String(n).split('.')[0],
125
+ poses = samples(motion, jointValues).map((v) => placeItems(motion, v));
74
126
  return wires.map((w) => {
75
- const what = `wire ${w.id}`, chain = [w.from, ...(w.via ?? []), w.to];
127
+ const what = `wire ${w.id}`,
128
+ chain = [w.from, ...(w.via ?? []), w.to];
76
129
  const fns = chain.flatMap((v) => (typeof v === 'string' && !v.includes('.') ? [] : [point(v, what)]));
77
- const pathLen = (w.via ?? []).reduce((t, v) => { const j = typeof v === 'string' && !v.includes('.') && motion.joints.find((x) => x.id === v); if (!j) return t; let l = 0; for (let k = 1; k < j.path.length; k++) l += Math.hypot(...j.path[k].map((c, m) => c - j.path[k - 1][m])); return t + l; }, 0);
78
- let longest = 0, shortest = Infinity, atLongest = null;
79
- for (const W of poses) { const P = fns.map((fn) => fn(W)); let l = pathLen; for (let k = 1; k < P.length; k++) l += Math.hypot(P[k][0] - P[k - 1][0], P[k][1] - P[k - 1][1], P[k][2] - P[k - 1][2]); if (l > longest) { longest = l; atLongest = P; } shortest = Math.min(shortest, l); }
80
- const { current, why } = currentOf(w, s, top, signal), gauge = w.gauge ? Number(GAUGE.exec(w.gauge)[1]) : null, area = gauge != null ? areaOf(gauge, base) : null, capacity = area != null ? area * density : null;
81
- return { id: w.id, from: w.from, to: w.to, via: w.via ?? [], pins: pinsAt(w, s), gauge: w.gauge ?? null, colour: w.colour ?? null, conductors: w.conductors ?? (s.motion.drives.some((d) => [top(w.from), top(w.to)].includes(d.id)) ? 4 : 1), connectors: w.connectors ?? null,
82
- longest, shortest, length: Math.ceil(longest + loop), loop, current, why, area, capacity, route: atLongest };
130
+ const pathLen = (w.via ?? []).reduce((t, v) => {
131
+ const j = typeof v === 'string' && !v.includes('.') && motion.joints.find((x) => x.id === v);
132
+ if (!j) return t;
133
+ let l = 0;
134
+ for (let k = 1; k < j.path.length; k++) l += Math.hypot(...j.path[k].map((c, m) => c - j.path[k - 1][m]));
135
+ return t + l;
136
+ }, 0);
137
+ let longest = 0,
138
+ shortest = Infinity,
139
+ atLongest = null;
140
+ for (const W of poses) {
141
+ const P = fns.map((fn) => fn(W));
142
+ let l = pathLen;
143
+ for (let k = 1; k < P.length; k++)
144
+ l += Math.hypot(P[k][0] - P[k - 1][0], P[k][1] - P[k - 1][1], P[k][2] - P[k - 1][2]);
145
+ if (l > longest) {
146
+ longest = l;
147
+ atLongest = P;
148
+ }
149
+ shortest = Math.min(shortest, l);
150
+ }
151
+ const { current, why } = currentOf(w, s, top, signal),
152
+ gauge = w.gauge ? Number(GAUGE.exec(w.gauge)[1]) : null,
153
+ area = gauge != null ? areaOf(gauge, base) : null,
154
+ capacity = area != null ? area * density : null;
155
+ return {
156
+ id: w.id,
157
+ from: w.from,
158
+ to: w.to,
159
+ via: w.via ?? [],
160
+ pins: pinsAt(w, s),
161
+ gauge: w.gauge ?? null,
162
+ colour: w.colour ?? null,
163
+ conductors: w.conductors ?? (s.motion.drives.some((d) => [top(w.from), top(w.to)].includes(d.id)) ? 4 : 1),
164
+ connectors: w.connectors ?? null,
165
+ longest,
166
+ shortest,
167
+ length: Math.ceil(longest + loop),
168
+ loop,
169
+ current,
170
+ why,
171
+ area,
172
+ capacity,
173
+ route: atLongest,
174
+ };
83
175
  });
84
176
  }
85
177
 
86
178
  export function wireChecks(s, f, helpers) {
87
179
  for (const w of wireRows(s, helpers)) {
88
- const refs = { wire: w.id, from: w.from, to: w.to }, at = w.route?.[0], values = { length: w.length, longest: w.longest, shortest: w.shortest, current: w.current, capacity: w.capacity };
89
- const run = (s.runs ?? []).filter((r) => r.wire === w.id), clips = run.reduce((t, r) => t + r.count, 0);
90
- f('info', `${w.id}: ${w.from} to ${w.to}, ${n3(w.length, 0)} mm with its ${w.loop} mm loop (${n3(w.shortest, 0)} to ${n3(w.longest, 0)} mm as the joints move)${run.length ? `; ${run.map((r) => `${n3(r.length, 0)} mm of it along ${r.along}`).join(', ')}, held by ${clips} cable clip${clips > 1 ? 's' : ''}` : ''}`, null, { code: 'wire.length', at, refs, values: { ...values, ...(run.length ? { along: run.reduce((t, r) => t + r.length, 0), clips } : {}) } });
91
- if (w.capacity == null) { f('warn', `${w.id}: no gauge given, so nothing checks it against ${n3(w.current, 2)} A (${w.why})`, `${w.id}: no gauge`, { code: 'wire.gauge', at, refs, values }); continue; }
92
- if (w.current > w.capacity) f('fail', `${w.id}: ${w.gauge} carries ${n3(w.capacity, 2)} A at most, and this carries ${n3(w.current, 2)} A (${w.why}): a thicker wire`, `${w.id}: too thin`, { code: 'wire.gauge', at, refs, values });
93
- else f('pass', `${w.id}: ${w.gauge} takes ${n3(w.current, 2)} A (${w.why}), up to ${n3(w.capacity, 2)} A`, null, { code: 'wire.gauge', at, refs, values });
180
+ const refs = { wire: w.id, from: w.from, to: w.to },
181
+ at = w.route?.[0],
182
+ values = { length: w.length, longest: w.longest, shortest: w.shortest, current: w.current, capacity: w.capacity };
183
+ const run = (s.runs ?? []).filter((r) => r.wire === w.id),
184
+ clips = run.reduce((t, r) => t + r.count, 0);
185
+ f(
186
+ 'info',
187
+ `${w.id}: ${w.from} to ${w.to}, ${n3(w.length, 0)} mm with its ${w.loop} mm loop (${n3(w.shortest, 0)} to ${n3(w.longest, 0)} mm as the joints move)${run.length ? `; ${run.map((r) => `${n3(r.length, 0)} mm of it along ${r.along}`).join(', ')}, held by ${clips} cable clip${clips > 1 ? 's' : ''}` : ''}`,
188
+ null,
189
+ {
190
+ code: 'wire.length',
191
+ at,
192
+ refs,
193
+ values: { ...values, ...(run.length ? { along: run.reduce((t, r) => t + r.length, 0), clips } : {}) },
194
+ },
195
+ );
196
+ if (w.capacity == null) {
197
+ f(
198
+ 'warn',
199
+ `${w.id}: no gauge given, so nothing checks it against ${n3(w.current, 2)} A (${w.why})`,
200
+ `${w.id}: no gauge`,
201
+ { code: 'wire.gauge', at, refs, values },
202
+ );
203
+ continue;
204
+ }
205
+ if (w.current > w.capacity)
206
+ f(
207
+ 'fail',
208
+ `${w.id}: ${w.gauge} carries ${n3(w.capacity, 2)} A at most, and this carries ${n3(w.current, 2)} A (${w.why}): a thicker wire`,
209
+ `${w.id}: too thin`,
210
+ { code: 'wire.gauge', at, refs, values },
211
+ );
212
+ else
213
+ f('pass', `${w.id}: ${w.gauge} takes ${n3(w.current, 2)} A (${w.why}), up to ${n3(w.capacity, 2)} A`, null, {
214
+ code: 'wire.gauge',
215
+ at,
216
+ refs,
217
+ values,
218
+ });
94
219
  }
95
220
  }
96
221
 
97
222
  // A route's stations: each anchor as [item, local point]; a path joint in the route is its whole polyline, on its parent
98
223
  function stations(s, chain, mul) {
99
- const motion = s.motion, out = [], ids = motion.items.map((x) => x[0]);
224
+ const motion = s.motion,
225
+ out = [],
226
+ ids = motion.items.map((x) => x[0]);
100
227
  for (const v of chain) {
101
- if (typeof v === 'string' && !v.includes('.')) { const j = motion.joints.find((x) => x.id === v); if (j) for (const p of j.path) { const W = mul(j.a, [1, 0, 0, p[0], 0, 1, 0, p[1], 0, 0, 1, p[2]]); out.push([j.parent, W[3], W[7], W[11]]); } continue; }
102
- const bits = String(v).split('.'), name = bits.pop(), id = bits.join('.'), m = motion.marks.find((x) => x.id === id && x.name === name);
228
+ if (typeof v === 'string' && !v.includes('.')) {
229
+ const j = motion.joints.find((x) => x.id === v);
230
+ if (j)
231
+ for (const p of j.path) {
232
+ const W = mul(j.a, [1, 0, 0, p[0], 0, 1, 0, p[1], 0, 0, 1, p[2]]);
233
+ out.push([j.parent, W[3], W[7], W[11]]);
234
+ }
235
+ continue;
236
+ }
237
+ const bits = String(v).split('.'),
238
+ name = bits.pop(),
239
+ id = bits.join('.'),
240
+ m = motion.marks.find((x) => x.id === id && x.name === name);
103
241
  if (m) out.push([ids.indexOf(id), m.frame[3], m.frame[7], m.frame[11]]);
104
242
  }
105
243
  return out;
106
244
  }
107
- const worldOf = (W, [, x, y, z]) => [W[0] * x + W[1] * y + W[2] * z + W[3], W[4] * x + W[5] * y + W[6] * z + W[7], W[8] * x + W[9] * y + W[10] * z + W[11]];
245
+ const worldOf = (W, [, x, y, z]) => [
246
+ W[0] * x + W[1] * y + W[2] * z + W[3],
247
+ W[4] * x + W[5] * y + W[6] * z + W[7],
248
+ W[8] * x + W[9] * y + W[10] * z + W[11],
249
+ ];
108
250
  const I = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
109
251
 
110
252
  /** Each wire's route as stations a link carries: [[id, [[item, x, y, z], …]]], the item -1 (world) when nothing moves. */
111
253
  export function wireRoutes(s, { placeItems, mul }) {
112
- const hasJoints = s.motion.joints.length > 0, W = hasJoints ? null : placeItems(s.motion, s.jointValues);
113
- return (s.wires || []).map((w) => [w.id, stations(s, [w.from, ...(w.via ?? []), w.to], mul).map((p) => (hasJoints ? p.map((v) => +v.toFixed(3)) : [-1, ...worldOf(p[0] < 0 ? I : W[p[0]], p).map((v) => +v.toFixed(3))]))]);
254
+ const hasJoints = s.motion.joints.length > 0,
255
+ W = hasJoints ? null : placeItems(s.motion, s.jointValues);
256
+ return (s.wires || []).map((w) => [
257
+ w.id,
258
+ stations(s, [w.from, ...(w.via ?? []), w.to], mul).map((p) =>
259
+ hasJoints ? p.map((v) => +v.toFixed(3)) : [-1, ...worldOf(p[0] < 0 ? I : W[p[0]], p).map((v) => +v.toFixed(3))],
260
+ ),
261
+ ]);
114
262
  }
115
263
 
116
264
  // A thin square tube along each wire at the assembly's pose, for previews: drawn faint, never a part, so no check sees it
117
265
  export function wireTubes(s, { placeItems, mul }) {
118
- const worlds = placeItems(s.motion, s.jointValues), r = 0.5, out = [];
266
+ const worlds = placeItems(s.motion, s.jointValues),
267
+ r = 0.5,
268
+ out = [];
119
269
  for (const w of s.wires || []) {
120
- const pts = stations(s, [w.from, ...(w.via ?? []), w.to], mul).map((p) => worldOf(p[0] < 0 ? I : worlds[p[0]], p)), tris = [];
270
+ const pts = stations(s, [w.from, ...(w.via ?? []), w.to], mul).map((p) => worldOf(p[0] < 0 ? I : worlds[p[0]], p)),
271
+ tris = [];
121
272
  for (let k = 1; k < pts.length; k++) {
122
- const a = pts[k - 1], b = pts[k], d = b.map((c, i) => c - a[i]), l = Math.hypot(...d); if (l < 1e-6) continue;
123
- const z = d.map((c) => c / l), side = Math.abs(z[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0], x0 = [z[1] * side[2] - z[2] * side[1], z[2] * side[0] - z[0] * side[2], z[0] * side[1] - z[1] * side[0]], m = Math.hypot(...x0), x = x0.map((c) => c / m), y = [z[1] * x[2] - z[2] * x[1], z[2] * x[0] - z[0] * x[2], z[0] * x[1] - z[1] * x[0]];
124
- const corner = (o, sx, sy) => o.map((c, i) => c + (sx * x[i] + sy * y[i]) * r), ring = (o) => [corner(o, 1, 1), corner(o, -1, 1), corner(o, -1, -1), corner(o, 1, -1)], A = ring(a), B = ring(b);
125
- for (let q = 0; q < 4; q++) { const n = (q + 1) % 4; tris.push([A[q], A[n], B[n]], [A[q], B[n], B[q]]); }
273
+ const a = pts[k - 1],
274
+ b = pts[k],
275
+ d = b.map((c, i) => c - a[i]),
276
+ l = Math.hypot(...d);
277
+ if (l < 1e-6) continue;
278
+ const z = d.map((c) => c / l),
279
+ side = Math.abs(z[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0],
280
+ x0 = [z[1] * side[2] - z[2] * side[1], z[2] * side[0] - z[0] * side[2], z[0] * side[1] - z[1] * side[0]],
281
+ m = Math.hypot(...x0),
282
+ x = x0.map((c) => c / m),
283
+ y = [z[1] * x[2] - z[2] * x[1], z[2] * x[0] - z[0] * x[2], z[0] * x[1] - z[1] * x[0]];
284
+ const corner = (o, sx, sy) => o.map((c, i) => c + (sx * x[i] + sy * y[i]) * r),
285
+ ring = (o) => [corner(o, 1, 1), corner(o, -1, 1), corner(o, -1, -1), corner(o, 1, -1)],
286
+ A = ring(a),
287
+ B = ring(b);
288
+ for (let q = 0; q < 4; q++) {
289
+ const n = (q + 1) % 4;
290
+ tris.push([A[q], A[n], B[n]], [A[q], B[n], B[q]]);
291
+ }
126
292
  tris.push([A[0], A[2], A[1]], [A[0], A[3], A[2]], [B[0], B[1], B[2]], [B[0], B[2], B[3]]);
127
293
  }
128
- if (tris.length) out.push({ name: `wire.${w.id}`, role: 'wire', label: `wire ${w.id}`, item: null, triangles: tris });
294
+ if (tris.length)
295
+ out.push({ name: `wire.${w.id}`, role: 'wire', label: `wire ${w.id}`, item: null, triangles: tris });
129
296
  }
130
297
  return out;
131
298
  }
@@ -133,8 +300,24 @@ export function wireTubes(s, { placeItems, mul }) {
133
300
  // The sheet: each wire, its length, gauge, colour and connectors, in Markdown
134
301
  export function wiringSheet(rows) {
135
302
  const line = (a) => `| ${a.join(' | ')} |`;
136
- return [line(['Wire', 'From', 'To', 'Length (mm)', 'Gauge', 'Conductors', 'Colour', 'Connectors', 'Board pins', 'Carries']), line(['---', '---', '---', '---:', '---', '---:', '---', '---', '---', '---']),
137
- ...rows.map((w) => line([w.id, w.from, w.to, w.length, w.gauge ?? '', w.conductors, w.colour ?? '', Array.isArray(w.connectors) ? w.connectors.join(' to ') : w.connectors ?? '', w.pins ?? '', `${n3(w.current, 2)} A, ${w.why}`]))].join('\n');
303
+ return [
304
+ line(['Wire', 'From', 'To', 'Length (mm)', 'Gauge', 'Conductors', 'Colour', 'Connectors', 'Board pins', 'Carries']),
305
+ line(['---', '---', '---', '---:', '---', '---:', '---', '---', '---', '---']),
306
+ ...rows.map((w) =>
307
+ line([
308
+ w.id,
309
+ w.from,
310
+ w.to,
311
+ w.length,
312
+ w.gauge ?? '',
313
+ w.conductors,
314
+ w.colour ?? '',
315
+ Array.isArray(w.connectors) ? w.connectors.join(' to ') : (w.connectors ?? ''),
316
+ w.pins ?? '',
317
+ `${n3(w.current, 2)} A, ${w.why}`,
318
+ ]),
319
+ ),
320
+ ].join('\n');
138
321
  }
139
322
 
140
323
  // An assembly's wires with model-link's placing: their rows (lengths, gauges, pins), tubes to draw and routes. Here