@rulecad/cad 0.8.0 → 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 (83) hide show
  1. package/AGENTS.md +24 -10
  2. package/CHANGELOG.md +404 -0
  3. package/EXAMPLES.md +40 -38
  4. package/README.md +193 -67
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2250 -512
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1847 -434
  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 +649 -121
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +899 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2702 -507
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +790 -175
  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 +123 -21
  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 +2 -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 +1021 -213
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +3 -1
  57. package/lib/optimise.mjs +978 -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 +223 -35
  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 +15 -5
  68. package/lib/sandbox-hooks.mjs +77 -19
  69. package/lib/sandbox-run.mjs +117 -18
  70. package/lib/sandbox.mjs +509 -60
  71. package/lib/schema.mjs +42 -11
  72. package/lib/seats.mjs +227 -49
  73. package/lib/services.mjs +261 -52
  74. package/lib/sheet.mjs +851 -178
  75. package/lib/slotnuts.mjs +213 -34
  76. package/lib/targets/gist.mjs +4 -1
  77. package/lib/targets.mjs +22 -4
  78. package/lib/task.mjs +376 -79
  79. package/lib/versions.mjs +111 -28
  80. package/lib/wires.mjs +228 -45
  81. package/lib/workspace.mjs +197 -12
  82. package/package.json +19 -19
  83. package/schemas/assembly.schema.json +2 -2
package/lib/assembly.mjs CHANGED
@@ -20,7 +20,7 @@
20
20
  // Its holes are read from the parts as drawn, its screws placed as reference parts, and it holds as a fit that fastens does.
21
21
  // Beams are held to each other by joins (lib/joins.mjs): { "kind": "blind", "a": "y1.a", "b": "x1.back@120" }. Each puts
22
22
  // its operations on both beams and its screws into fasten before anything is built, and is checked once it is.
23
- import { host, readJson } from './host.mjs';
23
+ import { host, readJson, cached } from './host.mjs';
24
24
  import fs from 'node:fs';
25
25
  import crypto from 'node:crypto';
26
26
  import path from 'node:path';
@@ -33,9 +33,22 @@ import { materialise } from './versions.mjs';
33
33
  import { satisfies } from '@rulecad/versions';
34
34
  import { bounds } from '@rulecad/printcheck';
35
35
  import { closest, closestAt, inside, distanceToFace, overlapAt } from '@rulecad/fit';
36
- import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
36
+ import { keys as keyCentres, readLayout } from './layout.mjs';
37
37
  import { DOFS, frame, turn, mul, inv, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
38
- import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase, contact, wormModel, wormMesh, bevelModel, bevelMesh, compoundEfficiency } from '@rulecad/gears';
38
+ import {
39
+ gearModel,
40
+ internalModel,
41
+ rackModel,
42
+ mesh as meshOf,
43
+ phase,
44
+ rackPhase,
45
+ contact,
46
+ wormModel,
47
+ wormMesh,
48
+ bevelModel,
49
+ bevelMesh,
50
+ compoundEfficiency,
51
+ } from '@rulecad/gears';
39
52
  import { ops as booleans } from '@rulecad/shapes';
40
53
  import { motorBuilt, motorDrives, shaftFits, loadsOf, motorChecks, shaftFit, axisOf } from './motors.mjs';
41
54
  import { runningChecks, seatFit, printerRules } from './seats.mjs';
@@ -50,8 +63,8 @@ import { gaitOf, gaitChecks, gaitSequence } from './gait.mjs';
50
63
  import { boughtBuilt, boughtFindings, boughtSets } from './bought.mjs';
51
64
  import { orderChecks } from './order.mjs';
52
65
  import { beamBuilt, beamPlace, beamAddress, beamFindings, marksOf, framesContext } from './beams.mjs';
53
- import { fittingBuilt, fittingFindings, plasticOf } from './fittings.mjs';
54
- import { expandJoins, joinChecks } from './joins.mjs';
66
+ import { fittingBuilt, fittingFindings, footFindings, plasticOf } from './fittings.mjs';
67
+ import { expandJoins, joinChecks, joinDropChecks } from './joins.mjs';
55
68
  import { expandFrame, frameText } from './framegen.mjs';
56
69
  import { frameChecks } from './framecheck.mjs';
57
70
  import { sizeChecks } from './framesize.mjs';
@@ -65,8 +78,14 @@ import { frameSquareChecks, frameBuild } from './framebuild.mjs';
65
78
  let pinning = null; // lib/pins.mjs, loaded with the first assembly whose fits name pins
66
79
  let fastening = null; // lib/fasten.mjs, loaded with the first assembly that has a fasten: the rest start as fast as before
67
80
 
68
- export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project), 'assemblies', `${plainName(name, 'assembly name')}.json`); };
69
- export const isAssembly = (ref) => { const [project, name] = String(ref).split('@')[0].split('/'); return isPlainName(project) && isPlainName(name) && host.exists(assemblyPath(`${project}/${name}`)); }; // (a path or a name that climbs is not an assembly: locate() says what it is)
81
+ export const assemblyPath = (ref) => {
82
+ const [project, name] = String(ref).split('/');
83
+ return path.join(paths.project(project), 'assemblies', `${plainName(name, 'assembly name')}.json`);
84
+ };
85
+ export const isAssembly = (ref) => {
86
+ const [project, name] = String(ref).split('@')[0].split('/');
87
+ return isPlainName(project) && isPlainName(name) && host.exists(assemblyPath(`${project}/${name}`));
88
+ }; // (a path or a name that climbs is not an assembly: locate() says what it is)
70
89
 
71
90
  export { satisfies }; // from @rulecad/versions
72
91
 
@@ -89,40 +108,60 @@ export { satisfies }; // from @rulecad/versions
89
108
  // checked or printed.
90
109
  // An object item can be a variant: "object": "keycap:oem-r3" (or "variant": "oem-r3"), and pin a release: "keycap@0.4.0".
91
110
  // overrides: { itemId: { variable: value } }, set on this assembly's items by the assembly that uses it.
92
- // opts: { mirror: true } builds each object with its mirror settings (cad show).
111
+ // opts: { mirror: true } builds each object with its mirror settings (cad show); { assembly } builds that assembly, as
112
+ // read, in place of the file's (cad frame --size --write checks what it would write before writing it).
93
113
  export async function buildAssembly(ref, stack = [], overrides = {}, opts = {}) {
94
114
  await measurer();
95
115
  const outer = overrides;
96
116
  const [project, name] = ref.split('/');
97
117
  if (stack.includes(ref)) throw new Error(`assembly ${ref} contains itself (${[...stack, ref].join(' → ')})`);
98
- let a = readJson(assemblyPath(ref));
118
+ let a = opts.assembly ? structuredClone(opts.assembly) : readJson(assemblyPath(ref));
99
119
  // A pose may set items' variables as well as joints ("cocked": { "run": -30, "action.travel": 25 }): a flexure bent
100
120
  // as the pose bends it, while the part itself is printed as drawn. The pose being built sets them on its items.
101
- const itemSets = (name) => { const out = {}; for (const [k, v] of Object.entries(a.poses?.[name] || {})) if (k.includes('.')) { const [item, ...rest] = k.split('.'); (out[item] ||= {})[rest.join('.')] = v; } return out; };
121
+ const itemSets = (name) => {
122
+ const out = {};
123
+ for (const [k, v] of Object.entries(a.poses?.[name] || {}))
124
+ if (k.includes('.')) {
125
+ const [item, ...rest] = k.split('.');
126
+ (out[item] ||= {})[rest.join('.')] = v;
127
+ }
128
+ return out;
129
+ };
102
130
  const builtPose = opts.pose ?? a.pose ?? Object.keys(a.poses || {})[0];
103
131
  const ownSets = typeof builtPose === 'string' ? itemSets(builtPose) : {};
104
132
  overrides = { ...overrides };
105
133
  const printer = printerOf(project);
106
134
  if (a.kind === 'plate' && !(a.uses || []).includes(printer)) a.uses = [...(a.uses || []), printer]; // a plate is checked as a print
107
- const values = Object.fromEntries((a.uses || []).map((u) => { const s = loadRuleSet(u); return [u, Object.fromEntries(Object.entries(s.rules).map(([k, r]) => [k, r.value]))]; }));
135
+ const values = Object.fromEntries(
136
+ (a.uses || []).map((u) => {
137
+ const s = loadRuleSet(u);
138
+ return [u, Object.fromEntries(Object.entries(s.rules).map(([k, r]) => [k, r.value]))];
139
+ }),
140
+ );
108
141
 
109
142
  // Names in positions: rule sets (mx.pitch), items' variables (cap.lift), or into components (key-0-0.cap.lift).
110
143
  // Rule values may still be expressions (rules referring to rules): resolved on demand.
111
- const seen = new Set(), ids = [];
144
+ const seen = new Set(),
145
+ ids = [];
112
146
  const lookup = (n) => {
113
147
  const path = n.split('.');
114
148
  if ((a.uses || []).includes(path[0])) seen.add(n);
115
- if (!(path[0] in values)) throw new Error(`"${n}": no item or rule set "${path[0]}" (items: ${ids.join(', ') || 'none yet'}; uses: ${(a.uses || []).join(', ') || 'none'})`);
149
+ if (!(path[0] in values))
150
+ throw new Error(
151
+ `"${n}": no item or rule set "${path[0]}" (items: ${ids.join(', ') || 'none yet'}; uses: ${(a.uses || []).join(', ') || 'none'})`,
152
+ );
116
153
  let v = values;
117
154
  for (const k of path) v = v?.[k];
118
- if (typeof v === 'string') v = evaluate(v, (k) => lookup(k.includes('.') ? k : `${path.slice(0, -1).join('.')}.${k}`));
155
+ if (typeof v === 'string')
156
+ v = evaluate(v, (k) => lookup(k.includes('.') ? k : `${path.slice(0, -1).join('.')}.${k}`));
119
157
  if (typeof v !== 'number') throw new Error(`"${n}" isn't a number`);
120
158
  return v;
121
159
  };
122
160
  const num = (x) => evaluate(x, lookup);
123
161
  // A generated frame (lib/framegen.mjs): "frame": { "kind": "box", "inside": [..] } into beams, joins and their ends, first
124
162
  let generated = null;
125
- if (a.frame && typeof a.frame === 'object' && !Array.isArray(a.frame)) ({ a, frame: generated } = expandFrame(a, num, framesContext()));
163
+ if (a.frame && typeof a.frame === 'object' && !Array.isArray(a.frame))
164
+ ({ a, frame: generated } = expandFrame(a, num, framesContext()));
126
165
  // Joins between beams (lib/joins.mjs): their operations go on the beams and their screws into fasten before anything is built
127
166
  let joins = [];
128
167
  if (a.joins != null) ({ a, joins } = expandJoins(a, num, undefined, plasticOf(project)));
@@ -130,25 +169,60 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
130
169
  let panels = [];
131
170
  if ((a.items || []).some((it) => it?.panel)) ({ a, panels } = expandPanels(a, num, undefined, plasticOf(project)));
132
171
  // Services (lib/services.mjs): a bought board or supply on its printed mount, a wire's run along a slot held by clips
133
- let mounts = [], runs = [];
134
- if ((a.items || []).some((it) => it?.mount != null) || (a.wires || []).some((w) => (w?.via ?? []).some((v) => v && typeof v === 'object'))) ({ a, mounts, runs } = expandServices(a, num, undefined, plasticOf(project)));
172
+ let mounts = [],
173
+ runs = [];
174
+ if (
175
+ (a.items || []).some((it) => it?.mount != null) ||
176
+ (a.wires || []).some((w) => (w?.via ?? []).some((v) => v && typeof v === 'object'))
177
+ )
178
+ ({ a, mounts, runs } = expandServices(a, num, undefined, plasticOf(project)));
135
179
  // Guides (lib/guides.mjs): a rail on a beam's face, its screws into the slot, each carriage on its own sliding joint
136
180
  let guides = [];
137
181
  if (a.guides != null) ({ a, guides } = expandGuides(a, num, undefined, plasticOf(project)));
138
- const { translate, rotate, transform } = jscad.transforms, deg = Math.PI / 180;
182
+ const { transform } = jscad.transforms;
139
183
 
140
- const items = [], parts = [], objects = [], fits = [], requires = [];
184
+ const items = [],
185
+ parts = [],
186
+ objects = [],
187
+ fits = [],
188
+ requires = [];
141
189
  for (const [k, r] of Object.entries(a.requires || {})) requires.push({ object: k, range: r, from: ref });
142
190
  const built = new Map(); // each object or component is built once per set of values, however many copies are placed
143
191
  const source = async (it, extra) => {
144
- if (it.motor) { const key = JSON.stringify(['motor', it.id, it.motor]); if (!built.has(key)) built.set(key, motorBuilt(it.motor, num, it.id)); return built.get(key); }
145
- if (it.beam) { const b = beamBuilt(it, num, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/beams.mjs)
146
- if (it.fitting) { const b = await fittingBuilt(it, it.id, framesContext(), plasticOf(project)); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/fittings.mjs)
147
- if (it.panel) { const b = await panelBuilt(it, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/panels.mjs)
148
- if (it._guide) { const b = guideBuilt(it, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/guides.mjs)
192
+ if (it.motor) {
193
+ const key = JSON.stringify(['motor', it.id, it.motor]);
194
+ if (!built.has(key)) built.set(key, motorBuilt(it.motor, num, it.id));
195
+ return built.get(key);
196
+ }
197
+ if (it.beam) {
198
+ const b = beamBuilt(it, num, it.id);
199
+ if (!built.has(b.key)) built.set(b.key, b);
200
+ return built.get(b.key);
201
+ } // (lib/beams.mjs)
202
+ if (it.fitting) {
203
+ const b = await fittingBuilt(it, it.id, framesContext(), plasticOf(project));
204
+ if (!built.has(b.key)) built.set(b.key, b);
205
+ return built.get(b.key);
206
+ } // (lib/fittings.mjs)
207
+ if (it.panel) {
208
+ const b = await panelBuilt(it, it.id);
209
+ if (!built.has(b.key)) built.set(b.key, b);
210
+ return built.get(b.key);
211
+ } // (lib/panels.mjs)
212
+ if (it._guide) {
213
+ const b = guideBuilt(it, it.id);
214
+ if (!built.has(b.key)) built.set(b.key, b);
215
+ return built.get(b.key);
216
+ } // (lib/guides.mjs)
149
217
  if (it.bought) {
150
218
  const key = JSON.stringify(['bought', it.id, it.bought, it.variant, it.set]);
151
- if (!built.has(key)) built.set(key, boughtSets().get(it.bought) === 'motor' ? motorBuilt({ model: it.bought }, num, it.id) : boughtBuilt(it.bought, it, num, it.id));
219
+ if (!built.has(key))
220
+ built.set(
221
+ key,
222
+ boughtSets().get(it.bought) === 'motor'
223
+ ? motorBuilt({ model: it.bought }, num, it.id)
224
+ : boughtBuilt(it.bought, it, num, it.id),
225
+ );
152
226
  return built.get(key);
153
227
  }
154
228
  // from: inputs worked out from items built before this one ({ "usb_y": "board.pcb.pico_y" }): numbers, in this
@@ -160,25 +234,75 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
160
234
  let own = null;
161
235
  const ownValue = async (x) => {
162
236
  if (typeof x !== 'string') return x;
163
- try { return num(x); } catch {}
237
+ try {
238
+ return num(x);
239
+ } catch {
240
+ // (not a plain number: read below as an address on another item)
241
+ }
164
242
  if (!it.object || !new RegExp(`\\b${it.id}\\.`).test(x)) return x;
165
- if (!own) { const [r, named] = String(it.object).split(':'), [objName, pin] = r.split('@'), d = locateIn(project, objName, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`); own = (await build({ ...(pin ? materialise(d, pin) : d), ...((named || it.variant) ? { variant: named || it.variant } : {}) }, base, opts)).values; }
166
- return evaluate(x, (n) => { if (n.startsWith(`${it.id}.`)) { const v = own[n.slice(it.id.length + 1)]; if (typeof v === 'number') return v; } return lookup(n); });
243
+ if (!own) {
244
+ const [r, named] = String(it.object).split(':'),
245
+ [objName, pin] = r.split('@'),
246
+ d = locateIn(project, objName, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`);
247
+ own = (
248
+ await build(
249
+ { ...(pin ? materialise(d, pin) : d), ...(named || it.variant ? { variant: named || it.variant } : {}) },
250
+ base,
251
+ opts,
252
+ )
253
+ ).values;
254
+ }
255
+ return evaluate(x, (n) => {
256
+ if (n.startsWith(`${it.id}.`)) {
257
+ const v = own[n.slice(it.id.length + 1)];
258
+ if (typeof v === 'number') return v;
259
+ }
260
+ return lookup(n);
261
+ });
167
262
  };
168
263
  const posed = {};
169
264
  for (const [k, x] of Object.entries(ownSets[it.id] || {})) posed[k] = await ownValue(x);
170
265
  const set = { ...(it.set || {}), ...from, ...posed, ...(overrides[it.id] || {}), ...(it.assembly ? {} : extra) };
171
266
  // Built for the mirror, an object's mirror settings win (no legends), so copies that differ only there are one shape
172
- if (opts.mirror && it.object) for (const k of Object.keys(readObject(locateIn(project, String(it.object).split(/[:@]/)[0], `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`)).mirror || {})) delete set[k];
267
+ if (opts.mirror && it.object)
268
+ for (const k of Object.keys(
269
+ readObject(
270
+ locateIn(
271
+ project,
272
+ String(it.object).split(/[:@]/)[0],
273
+ `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`,
274
+ ),
275
+ ).mirror || {},
276
+ ))
277
+ delete set[k];
173
278
  const sub = it.assembly ? extra : {}; // a component's values go to its items: { cap: { units: 1.5 } }
174
279
  const key = JSON.stringify([it.object, it.variant, it.assembly, set, sub]);
175
280
  if (!built.has(key)) {
176
- if (it.assembly) built.set(key, { key, sub: await buildAssembly(`${project}/${it.assembly}`, [...stack, ref], sub, { ...opts, pose: undefined }) }); // a pose names the outer assembly's joints
281
+ if (it.assembly)
282
+ built.set(key, {
283
+ key,
284
+ sub: await buildAssembly(`${project}/${it.assembly}`, [...stack, ref], sub, {
285
+ ...opts,
286
+ pose: undefined,
287
+ assembly: undefined,
288
+ }),
289
+ }); // a pose names the outer assembly's joints; an assembly given in place of a file is this one, not its items'
177
290
  else {
178
- const [ref, named] = String(it.object).split(':'), [objName, pin] = ref.split('@'), variant = named || it.variant;
179
- const d = locateIn(project, objName, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`), at = { ...(pin ? materialise(d, pin) : d), ...(variant ? { variant } : {}) };
291
+ const [ref, named] = String(it.object).split(':'),
292
+ [objName, pin] = ref.split('@'),
293
+ variant = named || it.variant;
294
+ const d = locateIn(project, objName, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`),
295
+ at = { ...(pin ? materialise(d, pin) : d), ...(variant ? { variant } : {}) };
180
296
  const b = await build(at, set, opts);
181
- built.set(key, { key, objName, b, version: pin || b.object.version, variant, role: ['reference', 'board'].includes(b.object.role) ? 'reference' : 'part', set: base }); // a board is made by a fab: checked, never printed. set: what it's made with, as printed (not bent by a pose)
297
+ built.set(key, {
298
+ key,
299
+ objName,
300
+ b,
301
+ version: pin || b.object.version,
302
+ variant,
303
+ role: ['reference', 'board'].includes(b.object.role) ? 'reference' : 'part',
304
+ set: base,
305
+ }); // a board is made by a fab: checked, never printed. set: what it's made with, as printed (not bent by a pose)
182
306
  }
183
307
  }
184
308
  return built.get(key);
@@ -186,46 +310,87 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
186
310
  const placing = [];
187
311
  let builtCount = 0;
188
312
  for (const it of a.items || []) {
189
- if (!/^[a-z][\w-]*$/.test(it.id || '')) throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
190
- if ([it.object, it.assembly, it.motor, it.bought, it.beam, it.fitting, it.panel].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly", "motor", "bought", "beam", "fitting" or "panel"`);
191
- if (!it.beam && (it.to != null || it.roll != null)) throw new Error(`item ${it.id}: to and roll place a beam by its ends: place ${it.object || it.assembly || it.motor?.model || it.bought} with at and rotate`);
313
+ if (!/^[a-z][\w-]*$/.test(it.id || ''))
314
+ throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
315
+ if ([it.object, it.assembly, it.motor, it.bought, it.beam, it.fitting, it.panel].filter(Boolean).length !== 1)
316
+ throw new Error(
317
+ `item ${it.id}: give one of "object", "assembly", "motor", "bought", "beam", "fitting" or "panel"`,
318
+ );
319
+ if (!it.beam && (it.to != null || it.roll != null))
320
+ throw new Error(
321
+ `item ${it.id}: to and roll place a beam by its ends: place ${it.object || it.assembly || it.motor?.model || it.bought} with at and rotate`,
322
+ );
192
323
  // Copies: one, a grid from repeat x/y, or a layout's keys. Each: { id, offset (from at), extra (values to set) }
193
- const rx = it.repeat?.x, ry = it.repeat?.y, rl = it.repeat?.layout, copies = [];
324
+ const rx = it.repeat?.x,
325
+ ry = it.repeat?.y,
326
+ rl = it.repeat?.layout,
327
+ copies = [];
194
328
  if (rl) {
195
329
  // A layout file in the project's layouts/, or (older assemblies) object/name: a layout kept in an object's .json
196
330
  const [lp, ln] = String(rl).includes('/') ? String(rl).split('/') : [null, rl];
197
- const data = lp ? readObject(locateIn(project, lp, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "repeat" layout`)).layouts?.[ln] : readLayout(project, ln);
331
+ const data = lp
332
+ ? readObject(
333
+ locateIn(project, lp, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "repeat" layout`),
334
+ ).layouts?.[ln]
335
+ : readLayout(project, ln);
198
336
  if (!data) throw new Error(`item ${it.id}: no layout "${ln}" in ${lp}.json`);
199
337
  const step = num(it.repeat.step);
200
338
  // Values each copy sets: its width, a value for its row (rows: { "cap.row": ["R1", …] }) and constants (each)
201
339
  // per: { "cap.legend": "legend" } sets an input from each key's own property (skipped where the key has none)
202
- const per = (k) => Object.fromEntries(Object.entries(it.repeat.per || {}).filter(([, f]) => k[f] != null).map(([n, f]) => [n, k[f]]));
203
- const values = (k) => ({ ...(it.repeat.width ? { [it.repeat.width]: k.units } : {}), ...(it.repeat.each || {}), ...per(k),
204
- ...Object.fromEntries(Object.entries(it.repeat.rows || {}).map(([n, list]) => {
205
- if (k.index >= list.length) throw new Error(`item ${it.id}: repeat.rows ${n} has ${list.length} values, the layout ${rows(data)} rows`);
206
- return [n, list[k.index]];
207
- })) });
340
+ const per = (k) =>
341
+ Object.fromEntries(
342
+ Object.entries(it.repeat.per || {})
343
+ .filter(([, f]) => k[f] != null)
344
+ .map(([n, f]) => [n, k[f]]),
345
+ );
346
+ const values = (k) => ({
347
+ ...(it.repeat.width ? { [it.repeat.width]: k.units } : {}),
348
+ ...(it.repeat.each || {}),
349
+ ...per(k),
350
+ ...Object.fromEntries(
351
+ Object.entries(it.repeat.rows || {}).map(([n, list]) => {
352
+ if (k.index >= list.length)
353
+ throw new Error(
354
+ `item ${it.id}: repeat.rows ${n} has ${list.length} values, the layout ${rows(data)} rows`,
355
+ );
356
+ return [n, list[k.index]];
357
+ }),
358
+ ),
359
+ });
208
360
  const rows = (l) => (l.rows || []).length;
209
361
  for (const k of keyCentres(data)) {
210
362
  const extra = {};
211
363
  for (const [n, val] of Object.entries(values(k))) {
212
- if (!it.assembly) { extra[n] = val; continue; }
364
+ if (!it.assembly) {
365
+ extra[n] = val;
366
+ continue;
367
+ }
213
368
  const [item, name] = n.split('.'); // in a component: <item>.<variable>
214
- if (!name) throw new Error(`item ${it.id}: name a component's variable as <item>.<variable>, e.g. cap.units (got ${n})`);
369
+ if (!name)
370
+ throw new Error(
371
+ `item ${it.id}: name a component's variable as <item>.<variable>, e.g. cap.units (got ${n})`,
372
+ );
215
373
  (extra[item] ||= {})[name] = val;
216
374
  }
217
375
  copies.push({ id: `${it.id}-${k.index}-${k.col}`, offset: [k.x * step, k.y * step], extra, label: k.label });
218
376
  }
219
377
  } else {
220
- const nx = rx ? Math.round(num(rx.count)) : 1, ny = ry ? Math.round(num(ry.count)) : 1;
221
- for (let i = 0; i < nx; i++) for (let j = 0; j < ny; j++) {
222
- copies.push({ id: it.repeat ? `${it.id}-${i}${ry ? `-${j}` : ''}` : it.id, offset: [rx ? i * num(rx.step) : 0, ry ? j * num(ry.step) : 0], extra: {} });
223
- }
378
+ const nx = rx ? Math.round(num(rx.count)) : 1,
379
+ ny = ry ? Math.round(num(ry.count)) : 1;
380
+ for (let i = 0; i < nx; i++)
381
+ for (let j = 0; j < ny; j++) {
382
+ copies.push({
383
+ id: it.repeat ? `${it.id}-${i}${ry ? `-${j}` : ''}` : it.id,
384
+ offset: [rx ? i * num(rx.step) : 0, ry ? j * num(ry.step) : 0],
385
+ extra: {},
386
+ });
387
+ }
224
388
  }
225
389
  const first = await source(it, copies[0].extra);
226
390
  values[it.id] = first.sub ? first.sub.values : first.b.values; // a repeated item's own name works too: cap.base, not only cap-0-0
227
391
  for (const c of copies) {
228
- c.src = await source(it, c.extra); values[c.id] = c.src.sub ? c.src.sub.values : c.src.b.values;
392
+ c.src = await source(it, c.extra);
393
+ values[c.id] = c.src.sub ? c.src.sub.values : c.src.b.values;
229
394
  opts.progress?.({ stage: 'build', assembly: ref, item: c.id, done: ++builtCount }); // progress: for a caller to show (cad --progress)
230
395
  }
231
396
  placing.push([it, copies]);
@@ -235,29 +400,80 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
235
400
  // placed by at and rotate, or by the joint whose child it is.
236
401
  const placed = []; // [it, copy], each a motion item, in order
237
402
  for (const [it, copies] of placing) {
238
- if (it.have != null && !it.bought && !it.motor) throw new Error(`item ${it.id}: "have" marks a bought part or a motor as in hand, and ${it.id} is ${it.object ? `printed (object ${it.object})` : it.beam ? 'a beam, cut from the bar on the cut list' : 'neither'}`);
239
- if (it.place === false) { // built only for its values ("place": false): a board a print plate's case is sized from
240
- for (const c of copies) if (!c.src.sub) objects.push({ id: c.id, objName: c.src.objName, version: c.src.version, built: c.src.b, role: c.src.role, unplaced: true });
403
+ if (it.have != null && !it.bought && !it.motor)
404
+ throw new Error(
405
+ `item ${it.id}: "have" marks a bought part or a motor as in hand, and ${it.id} is ${it.object ? `printed (object ${it.object})` : it.beam ? 'a beam, cut from the bar on the cut list' : 'neither'}`,
406
+ );
407
+ if (it.place === false) {
408
+ // built only for its values ("place": false): a board a print plate's case is sized from
409
+ for (const c of copies)
410
+ if (!c.src.sub)
411
+ objects.push({
412
+ id: c.id,
413
+ objName: c.src.objName,
414
+ version: c.src.version,
415
+ built: c.src.b,
416
+ role: c.src.role,
417
+ unplaced: true,
418
+ });
241
419
  continue;
242
420
  }
243
- for (const c of copies) { placed.push([it, c]); ids.push(c.id); }
421
+ for (const c of copies) {
422
+ placed.push([it, c]);
423
+ ids.push(c.id);
424
+ }
244
425
  }
245
- const motion = motionOf(a, placed, num, ref), wires = wiresOf(a, placed, motion.joints), task = taskOf(a, motion, num), gait = gaitOf(a, motion, num);
426
+ const motion = motionOf(a, placed, num, ref),
427
+ wires = wiresOf(a, placed, motion.joints),
428
+ task = taskOf(a, motion, num),
429
+ gait = gaitOf(a, motion, num);
246
430
  // (items printed together in place, which the assembly order never takes apart: each by its id)
247
- for (const id of a.printInPlace || []) if (!motion.items.some((x) => x[0] === id)) throw new Error(`printInPlace names "${id}", which isn't an item (${motion.items.map((x) => x[0]).join(', ')})`);
248
- fits.push(...shaftFits(motion.drives, motion.joints, placed.map(([, c]) => c.id)).map((x) => ({ ...x, num })));
431
+ for (const id of a.printInPlace || [])
432
+ if (!motion.items.some((x) => x[0] === id))
433
+ throw new Error(`printInPlace names "${id}", which isn't an item (${motion.items.map((x) => x[0]).join(', ')})`);
434
+ fits.push(
435
+ ...shaftFits(
436
+ motion.drives,
437
+ motion.joints,
438
+ placed.map(([, c]) => c.id),
439
+ ).map((x) => ({ ...x, num })),
440
+ );
249
441
  for (const [it, c] of placed) {
250
- const src = c.src, id = c.id;
442
+ const src = c.src,
443
+ id = c.id;
251
444
  if (src.sub) {
252
445
  const sub = src.sub;
253
446
  for (const o of sub.objects) objects.push({ ...o, id: `${id}.${o.id}` });
254
- for (const x of sub.fits) fits.push({ ...x, a: `${id}.${x.a}`, b: `${id}.${x.b}`, label: x.label && `${x.label} (${id})` });
447
+ for (const x of sub.fits)
448
+ fits.push({ ...x, a: `${id}.${x.a}`, b: `${id}.${x.b}`, label: x.label && `${x.label} (${id})` });
255
449
  requires.push(...sub.requires);
256
450
  for (const n of sub.seen) seen.add(n);
257
451
  items.push({ ...it, id, sub, role: 'part' });
258
452
  } else {
259
- objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role, ...(src.set ? { set: src.set } : {}), ...(src.variant ? { variant: src.variant } : {}), ...(src.bought ? { bought: src.bought } : {}), ...(src.motor ? { motor: src.motor } : {}), ...(src.beam ? { beam: src.beam } : {}), ...(src.fitting ? { fitting: src.fitting } : {}), ...(src.panel ? { panel: src.panel } : {}), ...(it.have === true ? { have: true } : {}) }); // ("have" on the object: a repeat's copies and a component's parts keep it)
260
- items.push({ ...it, id, objName: src.objName, built: src.b, version: src.version, role: src.role, ...(src.beam ? { beam: src.beam } : {}) });
453
+ objects.push({
454
+ id,
455
+ objName: src.objName,
456
+ version: src.version,
457
+ built: src.b,
458
+ role: src.role,
459
+ ...(src.set ? { set: src.set } : {}),
460
+ ...(src.variant ? { variant: src.variant } : {}),
461
+ ...(src.bought ? { bought: src.bought } : {}),
462
+ ...(src.motor ? { motor: src.motor } : {}),
463
+ ...(src.beam ? { beam: src.beam } : {}),
464
+ ...(src.fitting ? { fitting: src.fitting } : {}),
465
+ ...(src.panel ? { panel: src.panel } : {}),
466
+ ...(it.have === true ? { have: true } : {}),
467
+ }); // ("have" on the object: a repeat's copies and a component's parts keep it)
468
+ items.push({
469
+ ...it,
470
+ id,
471
+ objName: src.objName,
472
+ built: src.b,
473
+ version: src.version,
474
+ role: src.role,
475
+ ...(src.beam ? { beam: src.beam } : {}),
476
+ });
261
477
  }
262
478
  }
263
479
  // Every part, with its item where the joints put it at these values (jointValues); then the hardware of its fasten
@@ -266,31 +482,72 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
266
482
  const partsAt = (worlds) => {
267
483
  const out = [];
268
484
  placed.forEach(([, c], k) => {
269
- const src = c.src, id = c.id, key = src.key, m = toMat4(worlds[k]);
485
+ const src = c.src,
486
+ id = c.id,
487
+ key = src.key,
488
+ m = toMat4(worlds[k]);
270
489
  items[k].m = m;
271
490
  // Faces are moved as they are, not re-triangulated in place: triangulating again after a move rounds differently
272
491
  const move = (polys) => polys.map((poly) => poly.map((v) => jscad.maths.vec3.transform([0, 0, 0], v, m)));
273
492
  if (src.sub) {
274
493
  for (const p of src.sub.parts) {
275
494
  if (p.role === 'support' && a.kind !== 'plate') continue;
276
- out.push({ ...p, name: `${id}.${p.name}`, item: id, leaf: `${id}.${p.leaf}`, label: `${id} ${p.label}`,
277
- geometry: transform(m, p.geometry), polygons: move(p.polygons), triangles: move(p.triangles), ...(p.collide ? { collide: transform(m, p.collide) } : {}), m: jscad.maths.mat4.multiply(jscad.maths.mat4.create(), m, p.m),
278
- ...(p.hardware ? { moves: id, allow: p.allow.map((l) => `${id}.${l}`), lift: jscad.maths.vec3.transform([0, 0, 0], p.lift, [...m.slice(0, 12), 0, 0, 0, 1]) } : {}) }); // (a component's screws move with it)
495
+ out.push({
496
+ ...p,
497
+ name: `${id}.${p.name}`,
498
+ item: id,
499
+ leaf: `${id}.${p.leaf}`,
500
+ label: `${id} ${p.label}`,
501
+ geometry: transform(m, p.geometry),
502
+ polygons: move(p.polygons),
503
+ triangles: move(p.triangles),
504
+ ...(p.collide ? { collide: transform(m, p.collide) } : {}),
505
+ m: jscad.maths.mat4.multiply(jscad.maths.mat4.create(), m, p.m),
506
+ ...(p.hardware
507
+ ? {
508
+ moves: id,
509
+ allow: p.allow.map((l) => `${id}.${l}`),
510
+ lift: jscad.maths.vec3.transform([0, 0, 0], p.lift, [...m.slice(0, 12), 0, 0, 0, 1]),
511
+ }
512
+ : {}),
513
+ }); // (a component's screws move with it)
279
514
  }
280
515
  } else {
281
516
  for (const p of src.b.parts) {
282
517
  if (p.role === 'support' && a.kind !== 'plate') continue; // supports are snipped off before parts go together
283
- out.push({ name: `${id}.${p.name}`, item: id, leaf: id, object: src.objName, role: src.role === 'reference' ? 'reference' : p.role, label: `${id}: ${marks.has(id) ? `mark ${marks.get(id)}, ` : ''}${p.label}`,
284
- ...(p.filament ? { filament: p.filament } : {}), ...(p.mirror === false ? { mirror: false } : {}), ...(p.fill != null ? { fill: p.fill } : {}), part: p.name,
285
- geometry: transform(m, p.geometry), ...(p.collide ? { collide: transform(m, p.collide) } : {}), polygons: move(p.polygons), triangles: move(p.triangles),
286
- shape: `${key}:${p.name}`, hash: `${src.b.hash}:${p.name}`, local: p.polygons, localTriangles: p.triangles, m });
518
+ out.push({
519
+ name: `${id}.${p.name}`,
520
+ item: id,
521
+ leaf: id,
522
+ object: src.objName,
523
+ role: src.role === 'reference' ? 'reference' : p.role,
524
+ label: `${id}: ${marks.has(id) ? `mark ${marks.get(id)}, ` : ''}${p.label}`,
525
+ ...(p.filament ? { filament: p.filament } : {}),
526
+ ...(p.mirror === false ? { mirror: false } : {}),
527
+ ...(p.fill != null ? { fill: p.fill } : {}),
528
+ part: p.name,
529
+ geometry: transform(m, p.geometry),
530
+ ...(p.collide ? { collide: transform(m, p.collide) } : {}),
531
+ polygons: move(p.polygons),
532
+ triangles: move(p.triangles),
533
+ shape: `${key}:${p.name}`,
534
+ hash: `${src.b.hash}:${p.name}`,
535
+ local: p.polygons,
536
+ localTriangles: p.triangles,
537
+ m,
538
+ });
287
539
  }
288
540
  }
289
541
  });
290
542
  for (const h of hardware) out.push(fastening.hardwarePart(h, toMat4(worlds[h.host])));
291
543
  return out;
292
544
  };
293
- for (const x of a.fits || []) for (const p of x.poses || []) if (!motion.poses[p]) throw new Error(`fit ${x.note || x.label || `${x.a} / ${x.b}`}: no pose "${p}" (poses: ${Object.keys(motion.poses).join(', ') || 'none'})`);
545
+ for (const x of a.fits || [])
546
+ for (const p of x.poses || [])
547
+ if (!motion.poses[p])
548
+ throw new Error(
549
+ `fit ${x.note || x.label || `${x.a} / ${x.b}`}: no pose "${p}" (poses: ${Object.keys(motion.poses).join(', ') || 'none'})`,
550
+ );
294
551
  // each beam's mark on the cut list and its sheet (beams that are the same share one), shown in its label
295
552
  const marks = marksOf(objects);
296
553
  for (const o of objects) if (marks.has(o.id)) o.mark = marks.get(o.id);
@@ -304,7 +561,9 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
304
561
  if (a.fits?.some((x) => x.holes)) fastening ||= await import('./fasten.mjs'); // (a holes fit with a fit that fastens: the fasten that says both is suggested)
305
562
  if (a.fasten?.length && a.kind !== 'plate') {
306
563
  fastening ||= await import('./fasten.mjs');
307
- fastened = fastening.fastenOf({ a, project, parts, objects, motion, num }, worlds0, { access: pose === motion.pose });
564
+ fastened = fastening.fastenOf({ a, project, parts, objects, motion, num }, worlds0, {
565
+ access: pose === motion.pose,
566
+ });
308
567
  hardware = fastened.hardware;
309
568
  parts.push(...hardware.map((h) => fastening.hardwarePart(h, toMat4(worlds0[h.host]))));
310
569
  fits.push(...fastened.fits.map((x) => ({ ...x, num })));
@@ -313,41 +572,94 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
313
572
  // With * on both sides, each copy is checked against all the others: { "a": "key-*.cap", "b": "key-*.cap" }
314
573
  // A beam's address in a fit or an access is read now, so one past the beam's end is refused by name when it is built
315
574
  const beamIds = new Set(placed.filter(([it]) => it.beam).map(([, c]) => c.id));
316
- for (const x of a.fits || []) for (const n of [x.a, x.b, x.access].flat()) {
317
- if (typeof n === 'string' && beamIds.has(n.split('.')[0]) && n.includes('.') && !/\.body$/.test(n)) motion.address(n, `fit ${x.note || x.label || `${x.a} / ${x.b}`}`);
318
- }
575
+ for (const x of a.fits || [])
576
+ for (const n of [x.a, x.b, x.access].flat()) {
577
+ if (typeof n === 'string' && beamIds.has(n.split('.')[0]) && n.includes('.') && !/\.body$/.test(n))
578
+ motion.address(n, `fit ${x.note || x.label || `${x.a} / ${x.b}`}`);
579
+ }
319
580
  if (a.fits?.some((x) => x.fastener && typeof x.fastener === 'object')) pinning ||= await import('./pins.mjs');
320
581
  for (let x of a.fits || []) {
321
582
  if (x.fastener && typeof x.fastener === 'object') x = pinning.pinOfFit(x, project); // (pins or magnets by the schema's form: the fit's pin or magnet, and the fastener's name)
322
583
  if (x.seat != null && x.min == null) x = { ...x, min: -1000 }; // a seat presses, so the pair may overlap
323
584
  if (x.holes) x = { ...x, a: x.holes, b: x.into }; // a holes fit: a board's holes (a) over what its screws go into (b)
324
585
  const star = [x.a, x.b].find((n) => n.includes('*'));
325
- if (!star) { fits.push({ ...x, num }); continue; }
326
- const match = (n) => { const re = new RegExp(`^${n.split('.')[0].replace(/[-]/g, '\\-').replace('*', '([\\w-]+)')}$`); return ids.filter((id) => re.test(id)); };
327
- const copies = match(star), at = (id, n) => [id, ...n.split('.').slice(1)].join('.');
586
+ if (!star) {
587
+ fits.push({ ...x, num });
588
+ continue;
589
+ }
590
+ const match = (n) => {
591
+ const re = new RegExp(`^${n.split('.')[0].replace(/[-]/g, '\\-').replace('*', '([\\w-]+)')}$`);
592
+ return ids.filter((id) => re.test(id));
593
+ };
594
+ const copies = match(star),
595
+ at = (id, n) => [id, ...n.split('.').slice(1)].join('.');
328
596
  if (!copies.length) throw new Error(`fit ${x.a} / ${x.b}: nothing matches ${star}`);
329
597
  if (x.a.includes('*') && x.b.includes('*')) {
330
598
  const others = match(x.b);
331
- for (const id of copies) fits.push({ ...x, a: at(id, x.a), b: others.filter((o) => o !== id).map((o) => at(o, x.b)), num });
599
+ for (const id of copies)
600
+ fits.push({ ...x, a: at(id, x.a), b: others.filter((o) => o !== id).map((o) => at(o, x.b)), num });
332
601
  continue;
333
602
  }
334
- for (const id of copies) { const swap = (n) => (n === star ? at(id, n) : n); fits.push({ ...x, a: swap(x.a), b: swap(x.b), num }); }
603
+ for (const id of copies) {
604
+ const swap = (n) => (n === star ? at(id, n) : n);
605
+ fits.push({ ...x, a: swap(x.a), b: swap(x.b), num });
606
+ }
335
607
  }
336
608
  // at(pose): the same assembly in another pose (a name, or { joint: values }), nothing built again
337
609
  const same = (x, y) => JSON.stringify(x) === JSON.stringify(y);
338
610
  const others = {};
339
- if (!opts.onePose) for (const n of Object.keys(a.poses || {})) if (n !== builtPose && !same(itemSets(n), ownSets)) others[n] = await buildAssembly(ref, stack, outer, { ...opts, pose: n, onePose: true });
611
+ if (!opts.onePose)
612
+ for (const n of Object.keys(a.poses || {}))
613
+ if (n !== builtPose && !same(itemSets(n), ownSets))
614
+ others[n] = await buildAssembly(ref, stack, outer, { ...opts, pose: n, onePose: true });
340
615
  const at = (p) => {
341
616
  if (typeof p === 'string' && others[p]) return others[p];
342
- const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
343
- return { ...s, parts: moved, fastened: null, pose: typeof p === 'string' ? p : null, jointValues: v, polygons: moved.flatMap((x) => x.polygons), triangles: moved.flatMap((x) => x.triangles) };
617
+ const v = jointValues(motion, p),
618
+ moved = partsAt(placeItems(motion, v));
619
+ return {
620
+ ...s,
621
+ parts: moved,
622
+ fastened: null,
623
+ pose: typeof p === 'string' ? p : null,
624
+ jointValues: v,
625
+ polygons: moved.flatMap((x) => x.polygons),
626
+ triangles: moved.flatMap((x) => x.triangles),
627
+ };
344
628
  };
345
629
  // A stepper's torque at speed follows its driver's supply: the bought supply's volts, where the assembly has one
346
630
  // (power.mjs holds the same supply against the draw); with none, @rulecad/motors' default
347
631
  const psu = objects.find((o) => o.bought?.part === 'supply' && !o.unplaced)?.built.values.output_voltage;
348
632
  if (psu > 0) for (const d of motion?.drives ?? []) if (d.model?.type === 'stepper') d.supply = psu;
349
- const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, wires, task, gait, fastened, hardware, joins, generated, panels, mounts, runs, guides, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
350
- polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
633
+ const s = {
634
+ a,
635
+ project,
636
+ name,
637
+ items,
638
+ parts,
639
+ objects,
640
+ fits,
641
+ requires,
642
+ values,
643
+ num,
644
+ seen,
645
+ motion,
646
+ wires,
647
+ task,
648
+ gait,
649
+ fastened,
650
+ hardware,
651
+ joins,
652
+ generated,
653
+ panels,
654
+ mounts,
655
+ runs,
656
+ guides,
657
+ pose: typeof pose === 'string' ? pose : null,
658
+ jointValues: jv,
659
+ at,
660
+ polygons: parts.flatMap((p) => p.polygons),
661
+ triangles: parts.flatMap((p) => p.triangles),
662
+ };
351
663
  return s;
352
664
  }
353
665
 
@@ -376,117 +688,268 @@ const rows = (m) => [m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6
376
688
  const toMat4 = (r) => [r[0], r[4], r[8], 0, r[1], r[5], r[9], 0, r[2], r[6], r[10], 0, r[3], r[7], r[11], 1];
377
689
  export const LIMITS = { angle: [-180, 180] };
378
690
  function motionOf(a, placed, num, ref) {
379
- const { translate, rotate } = jscad.transforms, deg = Math.PI / 180;
691
+ const { translate, rotate } = jscad.transforms,
692
+ deg = Math.PI / 180;
380
693
  const index = new Map(placed.map(([, c], k) => [c.id, k]));
381
- const where = (n, what) => { if (!index.has(n)) throw new Error(`${what}: no item "${n}" (items: ${[...index.keys()].join(', ')})`); return index.get(n); };
382
- const evalIn = (values, label) => (x) => evaluate(x, (n) => {
383
- let v = values;
384
- for (const k of n.split('.')) v = v?.[k];
385
- if (typeof v !== 'number') throw new Error(`${label}: "${n}" isn't one of its numbers`);
386
- return v;
387
- });
694
+ const where = (n, what) => {
695
+ if (!index.has(n)) throw new Error(`${what}: no item "${n}" (items: ${[...index.keys()].join(', ')})`);
696
+ return index.get(n);
697
+ };
698
+ const evalIn = (values, label) => (x) =>
699
+ evaluate(x, (n) => {
700
+ let v = values;
701
+ for (const k of n.split('.')) v = v?.[k];
702
+ if (typeof v !== 'number') throw new Error(`${label}: "${n}" isn't one of its numbers`);
703
+ return v;
704
+ });
388
705
  const frameOf = (spec, ev) => {
389
706
  const at = (spec.at || [0, 0, 0]).map(ev);
390
- if (spec.rotate) { const m = turn(spec.rotate.map(ev)); m[3] = at[0]; m[7] = at[1]; m[11] = at[2]; return m; }
707
+ if (spec.rotate) {
708
+ const m = turn(spec.rotate.map(ev));
709
+ m[3] = at[0];
710
+ m[7] = at[1];
711
+ m[11] = at[2];
712
+ return m;
713
+ }
391
714
  return frame(at, (spec.axis || [0, 0, 1]).map(ev), spec.ref && spec.ref.map(ev));
392
715
  };
393
716
  // An anchor: { item (index, -1 the world), frame (12 numbers, in the item's own frame) }
394
717
  const anchor = (spec, what) => {
395
- if (spec && typeof spec === 'object') return { item: spec.item ? where(spec.item, what) : -1, frame: frameOf(spec, num) };
396
- const bits = String(spec).split('.'), id = bits[0];
397
- if (bits.length < 2 || !id || !bits.at(-1)) throw new Error(`${what}: name an anchor as <item>.<anchor> (got "${spec}")`);
718
+ if (spec && typeof spec === 'object')
719
+ return { item: spec.item ? where(spec.item, what) : -1, frame: frameOf(spec, num) };
720
+ const bits = String(spec).split('.'),
721
+ id = bits[0];
722
+ if (bits.length < 2 || !id || !bits.at(-1))
723
+ throw new Error(`${what}: name an anchor as <item>.<anchor> (got "${spec}")`);
398
724
  const k = where(id, what);
399
- let src = placed[k][1].src, pre = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], i = 1;
400
- for (; i < bits.length - 1 && !src.beam; i++) { // into a component: its item's place there
401
- const n = bits[i], sub = src.sub?.items.find((x) => x.id === n);
725
+ let src = placed[k][1].src,
726
+ pre = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0],
727
+ i = 1;
728
+ for (; i < bits.length - 1 && !src.beam; i++) {
729
+ // into a component: its item's place there
730
+ const n = bits[i],
731
+ sub = src.sub?.items.find((x) => x.id === n);
402
732
  if (!sub) throw new Error(`${what}: ${bits.slice(0, i).join('.')} has no item "${n}"`);
403
733
  pre = mul(pre, rows(sub.m));
404
734
  src = sub.sub ? { sub: sub.sub } : { b: sub.built, objName: sub.objName, beam: sub.beam };
405
735
  }
406
736
  // A beam's address, the rest of the name: an end (a, b), an end's bore (a.1), a face with a distance (top.2@120)
407
- if (src.beam) return { item: k, frame: mul(pre, beamAddress(src.beam, bits.slice(i).join('.'), `${what}: ${bits.slice(0, i).join('.')}`)) };
737
+ if (src.beam)
738
+ return {
739
+ item: k,
740
+ frame: mul(pre, beamAddress(src.beam, bits.slice(i).join('.'), `${what}: ${bits.slice(0, i).join('.')}`)),
741
+ };
408
742
  const name = bits[i];
409
743
  const anchors = src.b?.object.anchors || {};
410
- if (!anchors[name]) throw new Error(`${what}: ${src.objName || id} has no anchor "${name}" (anchors: ${Object.keys(anchors).join(', ') || 'none'})`);
744
+ if (!anchors[name])
745
+ throw new Error(
746
+ `${what}: ${src.objName || id} has no anchor "${name}" (anchors: ${Object.keys(anchors).join(', ') || 'none'})`,
747
+ );
411
748
  return { item: k, frame: mul(pre, frameOf(anchors[name], evalIn(src.b.values, `${src.objName} anchor ${name}`))) };
412
749
  };
413
- const joints = [], children = new Set();
750
+ const joints = [],
751
+ children = new Set();
414
752
  // An item at an address ("at": "x1.top@50%") is held there as by a fixed joint: its own origin on the anchor, its z
415
753
  // out of the face and its x along the beam toward end b, turned by its rotate in that frame; it moves with the beam
416
- const atAddress = placed.map(([it]) => it).filter((it, k, all) => typeof it.at === 'string' && all.indexOf(it) === k).map((it) => {
417
- if (it.repeat) throw new Error(`item ${it.id}: an item at an address ("${it.at}") is one copy: place a repeat with at [x, y, z]`);
418
- if (it.beam) throw new Error(`item ${it.id}: a beam is placed by its ends (from, to) or at a point [x, y, z], not at an address`);
419
- return { id: `${it.id}@`, type: 'fixed', parent: it.at, child: { item: it.id, at: [0, 0, 0], ...(it.rotate ? { rotate: it.rotate } : {}) }, at: true };
420
- });
754
+ const atAddress = placed
755
+ .map(([it]) => it)
756
+ .filter((it, k, all) => typeof it.at === 'string' && all.indexOf(it) === k)
757
+ .map((it) => {
758
+ if (it.repeat)
759
+ throw new Error(
760
+ `item ${it.id}: an item at an address ("${it.at}") is one copy: place a repeat with at [x, y, z]`,
761
+ );
762
+ if (it.beam)
763
+ throw new Error(
764
+ `item ${it.id}: a beam is placed by its ends (from, to) or at a point [x, y, z], not at an address`,
765
+ );
766
+ return {
767
+ id: `${it.id}@`,
768
+ type: 'fixed',
769
+ parent: it.at,
770
+ child: { item: it.id, at: [0, 0, 0], ...(it.rotate ? { rotate: it.rotate } : {}) },
771
+ at: true,
772
+ };
773
+ });
421
774
  for (const j of [...atAddress, ...(a.joints || [])]) {
422
775
  const what = `joint ${j.id}`;
423
- if (!j.at && !/^[a-z][\w-]*$/.test(j.id || '')) throw new Error(`each joint needs an id (letters, digits, - or _): got ${JSON.stringify(j.id)}`);
424
- if (!Object.hasOwn(DOFS, j.type)) throw new Error(`${what}: type is one of ${Object.keys(DOFS).join(', ')} (got ${JSON.stringify(j.type)})`);
425
- const p = j.parent == null ? { item: -1, frame: frame([0, 0, 0]) } : anchor(j.parent, j.at ? `item ${j.child.item}: at` : what), c = anchor(j.child, what);
776
+ if (!j.at && !/^[a-z][\w-]*$/.test(j.id || ''))
777
+ throw new Error(`each joint needs an id (letters, digits, - or _): got ${JSON.stringify(j.id)}`);
778
+ if (!Object.hasOwn(DOFS, j.type))
779
+ throw new Error(`${what}: type is one of ${Object.keys(DOFS).join(', ')} (got ${JSON.stringify(j.type)})`);
780
+ const p =
781
+ j.parent == null
782
+ ? { item: -1, frame: frame([0, 0, 0]) }
783
+ : anchor(j.parent, j.at ? `item ${j.child.item}: at` : what),
784
+ c = anchor(j.child, what);
426
785
  if (j.at) c.frame = inv(c.frame); // (the item turned by its rotate in the anchor's frame: the joint's child anchor is that turn undone)
427
786
  if (c.item < 0) throw new Error(`${what}: its child must be an item`);
428
787
  if (j.at && p.item === c.item) throw new Error(`item ${j.child.item}: at "${j.parent}" is on the item itself`);
429
- if (children.has(c.item)) throw new Error(`${what}: ${placed[c.item][1].id} is already placed by ${joints.find((x) => x.child === c.item)?.at ? `its at (${placed[c.item][0].at})` : 'another joint'} (two joints to one item make a ring: use loops)`);
788
+ if (children.has(c.item))
789
+ throw new Error(
790
+ `${what}: ${placed[c.item][1].id} is already placed by ${joints.find((x) => x.child === c.item)?.at ? `its at (${placed[c.item][0].at})` : 'another joint'} (two joints to one item make a ring: use loops)`,
791
+ );
430
792
  const [it] = placed[c.item];
431
- if (!j.at && (it.at || it.rotate || it.repeat || it.from != null && it.beam)) throw new Error(`${what}: ${it.id} is placed by the joint, so it can't have at, rotate, repeat${it.beam ? ', or from and to' : ''}`);
793
+ if (!j.at && (it.at || it.rotate || it.repeat || (it.from != null && it.beam)))
794
+ throw new Error(
795
+ `${what}: ${it.id} is placed by the joint, so it can't have at, rotate, repeat${it.beam ? ', or from and to' : ''}`,
796
+ );
432
797
  children.add(c.item);
433
798
  const path = j.type === 'path' ? (j.path || []).map((pt) => pt.map(num)) : undefined;
434
799
  if (path && path.length < 2) throw new Error(`${what}: a path joint needs "path": two points or more`);
435
- const kinds = DOFS[j.type], list = (x) => (x == null ? [] : [].concat(x));
436
- const lo = list(j.min), hi = list(j.max), val = list(j.value);
800
+ const kinds = DOFS[j.type],
801
+ list = (x) => (x == null ? [] : [].concat(x));
802
+ const lo = list(j.min),
803
+ hi = list(j.max),
804
+ val = list(j.value);
437
805
  const dofs = kinds.map((kind, i) => {
438
806
  const range = j.type === 'path' ? [0, pathLength(path)] : kind === 'angle' ? LIMITS.angle : null;
439
- const mn = lo[i] != null ? num(lo[i]) : range?.[0], mx = hi[i] != null ? num(hi[i]) : range?.[1];
807
+ const mn = lo[i] != null ? num(lo[i]) : range?.[0],
808
+ mx = hi[i] != null ? num(hi[i]) : range?.[1];
440
809
  if (mn == null || mx == null) throw new Error(`${what}: give its ${kind} a min and max`);
441
810
  if (mn > mx) throw new Error(`${what}: min ${mn} is above max ${mx}`);
442
811
  return [mn, mx, val[i] != null ? num(val[i]) : Math.min(mx, Math.max(mn, 0))];
443
812
  });
444
- joints.push({ id: j.id, type: j.type, parent: p.item, child: c.item, a: p.frame, b: c.frame, dofs, ...(j.at ? { at: true } : {}),
445
- ...(j.label ? { label: j.label } : {}), ...(path ? { path } : {}), ...(j.cone != null ? { cone: num(j.cone) } : {}),
446
- ...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}),
447
- ...(j.mesh ? { meshSpec: j.mesh } : {}), ...(j.brake ? { brake: j.brake } : {}) });
448
- }
449
- for (const j of joints) if (j.follow) {
450
- const l = joints.find((x) => x.id === j.follow[0]);
451
- if (!l) throw new Error(`joint ${j.id}: follows "${j.follow[0]}", which isn't a joint (${joints.map((x) => x.id).join(', ')})`);
452
- if (l.dofs.length !== j.dofs.length) throw new Error(`joint ${j.id} (${j.type}) takes ${j.dofs.length} values, but follows ${l.id} (${l.type}), which takes ${l.dofs.length}`);
813
+ joints.push({
814
+ id: j.id,
815
+ type: j.type,
816
+ parent: p.item,
817
+ child: c.item,
818
+ a: p.frame,
819
+ b: c.frame,
820
+ dofs,
821
+ ...(j.at ? { at: true } : {}),
822
+ ...(j.label ? { label: j.label } : {}),
823
+ ...(path ? { path } : {}),
824
+ ...(j.cone != null ? { cone: num(j.cone) } : {}),
825
+ ...(j.follow
826
+ ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] }
827
+ : {}),
828
+ ...(j.mesh ? { meshSpec: j.mesh } : {}),
829
+ ...(j.brake ? { brake: j.brake } : {}),
830
+ });
453
831
  }
832
+ for (const j of joints)
833
+ if (j.follow) {
834
+ const l = joints.find((x) => x.id === j.follow[0]);
835
+ if (!l)
836
+ throw new Error(
837
+ `joint ${j.id}: follows "${j.follow[0]}", which isn't a joint (${joints.map((x) => x.id).join(', ')})`,
838
+ );
839
+ if (l.dofs.length !== j.dofs.length)
840
+ throw new Error(
841
+ `joint ${j.id} (${j.type}) takes ${j.dofs.length} values, but follows ${l.id} (${l.type}), which takes ${l.dofs.length}`,
842
+ );
843
+ }
454
844
  const items = placed.map(([it, c], k) => {
455
845
  if (children.has(k)) return [c.id];
456
846
  const ends = it.beam ? beamPlace(it, num) : null; // a beam by its ends (lib/beams.mjs)
457
847
  if (ends) return [c.id, ...ends];
458
- const base = (it.at || [0, 0, 0]).map(num), rot = (it.rotate || [0, 0, 0]).map((r) => num(r) * deg);
848
+ const base = (it.at || [0, 0, 0]).map(num),
849
+ rot = (it.rotate || [0, 0, 0]).map((r) => num(r) * deg);
459
850
  // A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
460
- return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
851
+ return [
852
+ c.id,
853
+ ...rows(
854
+ translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create())))
855
+ .transforms,
856
+ ),
857
+ ];
461
858
  });
462
859
  const meshes = [...gearMeshes(joints, items, num), ...planetaries(a.planetary || [], joints, items, num)];
463
- const drives = motorDrives(a, placed, joints, num), loads = loadsOf(a, anchor, num, joints);
464
- const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).filter(([id]) => !id.includes('.')).map(([id, v]) => {
465
- if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
466
- return [id, Array.isArray(v) ? v.map(num) : num(v)];
467
- }))]));
468
- if (a.pose && !poses[a.pose]) throw new Error(`pose "${a.pose}" isn't one of the poses (${Object.keys(poses).join(', ') || 'none'})`);
469
- const loops = (a.loops || []).map((l, i) => ({ label: l.label || `${typeof l.a === 'string' ? l.a : 'anchor'} meets ${typeof l.b === 'string' ? l.b : 'anchor'}`,
470
- a: anchor(l.a, `loop ${i + 1}`), b: anchor(l.b, `loop ${i + 1}`), tolerance: l.tolerance != null ? num(l.tolerance) : 0.01 }));
860
+ const drives = motorDrives(a, placed, joints, num),
861
+ loads = loadsOf(a, anchor, num, joints);
862
+ const poses = Object.fromEntries(
863
+ Object.entries(a.poses || {}).map(([n, set]) => [
864
+ n,
865
+ Object.fromEntries(
866
+ Object.entries(set)
867
+ .filter(([id]) => !id.includes('.'))
868
+ .map(([id, v]) => {
869
+ if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
870
+ return [id, Array.isArray(v) ? v.map(num) : num(v)];
871
+ }),
872
+ ),
873
+ ]),
874
+ );
875
+ if (a.pose && !poses[a.pose])
876
+ throw new Error(`pose "${a.pose}" isn't one of the poses (${Object.keys(poses).join(', ') || 'none'})`);
877
+ const loops = (a.loops || []).map((l, i) => ({
878
+ label: l.label || `${typeof l.a === 'string' ? l.a : 'anchor'} meets ${typeof l.b === 'string' ? l.b : 'anchor'}`,
879
+ a: anchor(l.a, `loop ${i + 1}`),
880
+ b: anchor(l.b, `loop ${i + 1}`),
881
+ tolerance: l.tolerance != null ? num(l.tolerance) : 0.01,
882
+ }));
471
883
  // Every object item's anchors, to say where things are: a finding near one names it (keyboard@pivot)
472
- const marks = placed.flatMap(([, c], k) => Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
473
- try { return { item: k, id: c.id, name, frame: frameOf(spec, evalIn(c.src.b.values, `${c.src.objName} anchor ${name}`)) }; } catch { return null; }
474
- })).filter(Boolean);
884
+ const marks = placed
885
+ .flatMap(([, c], k) =>
886
+ Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
887
+ try {
888
+ return {
889
+ item: k,
890
+ id: c.id,
891
+ name,
892
+ frame: frameOf(spec, evalIn(c.src.b.values, `${c.src.objName} anchor ${name}`)),
893
+ };
894
+ } catch {
895
+ return null;
896
+ }
897
+ }),
898
+ )
899
+ .filter(Boolean);
475
900
  // address(name): any anchor by name, a beam's addresses too (x1.top@120), as { item, frame }: for fits and the build order
476
901
  // Where each screw of a fasten goes, where it says so with anchors: a point on its axis, the anchor's z along it
477
- const fasten = (a.fasten || []).map((x, i) => (Array.isArray(x.at) ? x.at : []).map((n) => ({ ...anchor(n, `fasten ${i + 1}`), name: typeof n === 'string' ? n : null })));
478
- return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes, drives, loads, fasten, gravity: (a.gravity || [0, 0, -1]).map(num), address: (n, what = 'address') => anchor(n, what) };
902
+ const fasten = (a.fasten || []).map((x, i) =>
903
+ (Array.isArray(x.at) ? x.at : []).map((n) => ({
904
+ ...anchor(n, `fasten ${i + 1}`),
905
+ name: typeof n === 'string' ? n : null,
906
+ })),
907
+ );
908
+ return {
909
+ items,
910
+ joints,
911
+ poses,
912
+ pose: a.pose || Object.keys(poses)[0],
913
+ loops,
914
+ ref,
915
+ marks,
916
+ meshes,
917
+ drives,
918
+ loads,
919
+ fasten,
920
+ gravity: (a.gravity || [0, 0, -1]).map(num),
921
+ address: (n, what = 'address') => anchor(n, what),
922
+ };
479
923
  }
480
924
 
481
925
  // A pair measured from its drawn teeth (@rulecad/gears contact: backlash, transmission error, interference), kept in
482
926
  // .cache/gears/ by the pair, the centre distance and the gears package's code, as it takes half a second
483
927
  let gearsCode = null;
484
928
  function measured(a, b, centre) {
485
- gearsCode ||= (() => { const dir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))); return fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs' && !f.startsWith('.')).sort().map((f) => fs.readFileSync(path.join(dir, f), 'utf8')).join(''); })();
486
- const file = paths.cache('gears', `${crypto.createHash('sha256').update(JSON.stringify([gearsCode, a, b, +centre.toFixed(6)])).digest('hex')}.json`);
487
- if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
488
- const r = contact(a, b, { centre, steps: 12 }), keep = { findings: r.findings, backlash: r.backlash, error: r.error };
489
- try { host.writeText(file, JSON.stringify(keep)); } catch {} // (only slower without it)
929
+ gearsCode ||= (() => {
930
+ const dir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears')));
931
+ return fs
932
+ .readdirSync(dir)
933
+ .filter((f) => f.endsWith('.mjs') && f !== 'test.mjs' && !f.startsWith('.'))
934
+ .sort()
935
+ .map((f) => fs.readFileSync(path.join(dir, f), 'utf8'))
936
+ .join('');
937
+ })();
938
+ const file = paths.cache(
939
+ 'gears',
940
+ `${crypto
941
+ .createHash('sha256')
942
+ .update(JSON.stringify([gearsCode, a, b, +centre.toFixed(6)]))
943
+ .digest('hex')}.json`,
944
+ );
945
+ if (!process.env.CAD_NO_CACHE && cached(file)) return JSON.parse(host.readText(file));
946
+ const r = contact(a, b, { centre, steps: 12 }),
947
+ keep = { findings: r.findings, backlash: r.backlash, error: r.error };
948
+ try {
949
+ host.writeText(file, JSON.stringify(keep));
950
+ } catch {
951
+ // (a cache that can't be written is only slower)
952
+ }
490
953
  return keep;
491
954
  }
492
955
 
@@ -496,100 +959,278 @@ function measured(a, b, centre) {
496
959
  // follows it. With one held, each turns in proportion to the driver (Willis), so each is a follow: its ratio from the
497
960
  // teeth, its offset from where the parts are with their joints at 0, so a tooth sits in a gap everywhere.
498
961
  function planetaries(list, joints, items, num) {
499
- const out = [], DEG = Math.PI / 180;
500
- const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
501
- const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
962
+ const out = [],
963
+ DEG = Math.PI / 180;
964
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]],
965
+ org = (W) => [W[3], W[7], W[11]];
966
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
967
+ sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
502
968
  const crossP = (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]];
503
- const flat = (v, z) => sub(v, z.map((x) => x * dot(v, z))), len = (v) => Math.hypot(...v);
969
+ const flat = (v, z) =>
970
+ sub(
971
+ v,
972
+ z.map((x) => x * dot(v, z)),
973
+ ),
974
+ len = (v) => Math.hypot(...v);
504
975
  const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v)); // radians
505
976
  list.forEach((g, n) => {
506
- const what = `planetary ${n + 1}`, index = (id, role) => { const k = items.findIndex((x) => x[0] === id); if (k < 0) throw new Error(`${what}: ${role} "${id}" isn't an item (${items.map((x) => x[0]).join(', ')})`); return k; };
977
+ const what = `planetary ${n + 1}`,
978
+ index = (id, role) => {
979
+ const k = items.findIndex((x) => x[0] === id);
980
+ if (k < 0) throw new Error(`${what}: ${role} "${id}" isn't an item (${items.map((x) => x[0]).join(', ')})`);
981
+ return k;
982
+ };
507
983
  const idx = { sun: index(g.sun, 'sun'), carrier: index(g.carrier, 'carrier'), ring: index(g.ring, 'ring') };
508
984
  const planets = [].concat(g.planets || []).map((id) => index(id, 'planet'));
509
985
  if (!planets.length) throw new Error(`${what}: planets names the planet items`);
510
- const jointOf = (k) => joints.find((j) => j.child === k), moving = (k) => { const j = jointOf(k); return j && j.type !== 'fixed' ? j : null; };
986
+ const jointOf = (k) => joints.find((j) => j.child === k),
987
+ moving = (k) => {
988
+ const j = jointOf(k);
989
+ return j && j.type !== 'fixed' ? j : null;
990
+ };
511
991
  const held = ['sun', 'carrier', 'ring'].filter((m) => !moving(idx[m]));
512
- if (held.length !== 1) throw new Error(`${what}: hold one of the sun, carrier and ring (no joint, or a fixed one), and turn the other two on revolutes (held now: ${held.join(', ') || 'none'})`);
992
+ if (held.length !== 1)
993
+ throw new Error(
994
+ `${what}: hold one of the sun, carrier and ring (no joint, or a fixed one), and turn the other two on revolutes (held now: ${held.join(', ') || 'none'})`,
995
+ );
513
996
  const drive = g.drive ?? ['carrier', 'sun', 'ring'].find((m) => m !== held[0]);
514
- if (!['sun', 'carrier', 'ring'].includes(drive) || drive === held[0]) throw new Error(`${what}: drive is the sun, the carrier or the ring, and not the one held (${held[0]})`);
515
- const third = ['sun', 'carrier', 'ring'].find((m) => m !== held[0] && m !== drive), lead = moving(idx[drive]), follower = moving(idx[third]);
516
- for (const [m, j] of [[drive, lead], [third, follower]]) if (j.type !== 'revolute') throw new Error(`${what}: the ${m} turns on a revolute (its joint ${j.id} is a ${j.type})`);
517
- if (follower.follow || follower.meshSpec) throw new Error(`${what}: ${follower.id} turns the ${third}, which follows the ${drive} here: give it no follow or mesh of its own`);
518
- const planetJoints = planets.map((k) => { const j = jointOf(k); if (!j || j.type !== 'revolute' || j.parent !== idx.carrier) throw new Error(`${what}: planet ${items[k][0]} turns on a revolute on the carrier (${items[idx.carrier][0]})`); return j; });
997
+ if (!['sun', 'carrier', 'ring'].includes(drive) || drive === held[0])
998
+ throw new Error(`${what}: drive is the sun, the carrier or the ring, and not the one held (${held[0]})`);
999
+ const third = ['sun', 'carrier', 'ring'].find((m) => m !== held[0] && m !== drive),
1000
+ lead = moving(idx[drive]),
1001
+ follower = moving(idx[third]);
1002
+ for (const [m, j] of [
1003
+ [drive, lead],
1004
+ [third, follower],
1005
+ ])
1006
+ if (j.type !== 'revolute')
1007
+ throw new Error(`${what}: the ${m} turns on a revolute (its joint ${j.id} is a ${j.type})`);
1008
+ if (follower.follow || follower.meshSpec)
1009
+ throw new Error(
1010
+ `${what}: ${follower.id} turns the ${third}, which follows the ${drive} here: give it no follow or mesh of its own`,
1011
+ );
1012
+ const planetJoints = planets.map((k) => {
1013
+ const j = jointOf(k);
1014
+ if (!j || j.type !== 'revolute' || j.parent !== idx.carrier)
1015
+ throw new Error(`${what}: planet ${items[k][0]} turns on a revolute on the carrier (${items[idx.carrier][0]})`);
1016
+ return j;
1017
+ });
519
1018
  const teeth = [].concat(g.teeth || []).map(num);
520
1019
  if (teeth.length !== 3) throw new Error(`${what}: teeth is [sun, planet, ring] (got ${JSON.stringify(g.teeth)})`);
521
- const [S, P, R] = teeth, common = { module: num(g.module), ...(g.pressureAngle != null ? { pressureAngle: num(g.pressureAngle) } : {}), ...(g.backlash != null ? { backlash: num(g.backlash) } : {}) };
522
- let sun, planet, ring;
523
- try { sun = gearModel({ ...common, teeth: S }); planet = gearModel({ ...common, teeth: P }); ring = internalModel({ ...common, teeth: R }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
524
- if (R !== S + 2 * P) throw new Error(`${what}: a ring of ${R} isn't the sun and two planets across (${S} + 2 × ${P} = ${S + 2 * P})`);
1020
+ const [S, P, R] = teeth,
1021
+ common = {
1022
+ module: num(g.module),
1023
+ ...(g.pressureAngle != null ? { pressureAngle: num(g.pressureAngle) } : {}),
1024
+ ...(g.backlash != null ? { backlash: num(g.backlash) } : {}),
1025
+ };
1026
+ let sun, planet;
1027
+ try {
1028
+ sun = gearModel({ ...common, teeth: S });
1029
+ planet = gearModel({ ...common, teeth: P });
1030
+ internalModel({ ...common, teeth: R }); // (made only to refuse a ring that can't be cut: its figures aren't needed here)
1031
+ } catch (e) {
1032
+ throw new Error(`${what}: ${e.message}`);
1033
+ }
1034
+ if (R !== S + 2 * P)
1035
+ throw new Error(`${what}: a ring of ${R} isn't the sun and two planets across (${S} + 2 × ${P} = ${S + 2 * P})`);
525
1036
  // Every part where it is with these joints at 0
526
1037
  const v = jointValues({ joints, poses: {} }, {});
527
1038
  for (const j of [lead, follower, ...planetJoints]) v[j.id] = [0];
528
- if (g.output) { const j2 = moving(index(g.output.ring, 'output ring')); if (j2) v[j2.id] = [0]; } // (a range that leaves out 0 would put the ring where the phase isn't reckoned)
529
- const worlds = placeItems({ items, joints }, v), W = (k) => worlds[k];
530
- const O = org(W(idx.sun)), Z = col(W(idx.sun), 2), X0 = col(W(idx.sun), 0);
531
- const sign = (j) => Math.sign(dot(mul(j.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[j.parent], j.a).filter((_, i) => [2, 6, 10].includes(i)), Z));
532
- for (const m of ['carrier', 'ring']) { const c = org(W(idx[m])), z = col(W(idx[m]), 2); if (len(flat(sub(c, O), Z)) > 1e-4 || Math.abs(Math.abs(dot(z, Z)) - 1) > 1e-6) throw new Error(`${what}: the ${m} turns about the sun's axis: centre it there`); }
1039
+ if (g.output) {
1040
+ const j2 = moving(index(g.output.ring, 'output ring'));
1041
+ if (j2) v[j2.id] = [0];
1042
+ } // (a range that leaves out 0 would put the ring where the phase isn't reckoned)
1043
+ const worlds = placeItems({ items, joints }, v),
1044
+ W = (k) => worlds[k];
1045
+ const O = org(W(idx.sun)),
1046
+ Z = col(W(idx.sun), 2),
1047
+ X0 = col(W(idx.sun), 0);
1048
+ const sign = (j) =>
1049
+ Math.sign(
1050
+ dot(
1051
+ mul(j.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[j.parent], j.a).filter((_, i) =>
1052
+ [2, 6, 10].includes(i),
1053
+ ),
1054
+ Z,
1055
+ ),
1056
+ );
1057
+ for (const m of ['carrier', 'ring']) {
1058
+ const c = org(W(idx[m])),
1059
+ z = col(W(idx[m]), 2);
1060
+ if (len(flat(sub(c, O), Z)) > 1e-4 || Math.abs(Math.abs(dot(z, Z)) - 1) > 1e-6)
1061
+ throw new Error(`${what}: the ${m} turns about the sun's axis: centre it there`);
1062
+ }
533
1063
  const gr = ang(flat(col(W(idx.ring), 0), Z), X0, Z) * (dot(col(W(idx.ring), 2), Z) > 0 ? 1 : -1);
534
1064
  // planet k: where it sits (its centre's angle round the sun) and which way its first tooth points
535
- const pl = planets.map((k, i) => { const c = flat(sub(org(W(k)), O), Z); return { id: items[k][0], joint: planetJoints[i], r: len(c), beta: ang(c, X0, Z), gamma: ang(flat(col(W(k), 0), Z), X0, Z), s: sign(planetJoints[i]) }; });
1065
+ const pl = planets.map((k, i) => {
1066
+ const c = flat(sub(org(W(k)), O), Z);
1067
+ return {
1068
+ id: items[k][0],
1069
+ joint: planetJoints[i],
1070
+ r: len(c),
1071
+ beta: ang(c, X0, Z),
1072
+ gamma: ang(flat(col(W(k), 0), Z), X0, Z),
1073
+ s: sign(planetJoints[i]),
1074
+ };
1075
+ });
536
1076
  // One configuration that meshes, everything at its zero: planet 0 in phase with the ring, the sun with planet 0
537
- const b0 = pl[0].beta, pi0 = (R / P) * (gr - b0 * (1 - P / R) + Math.PI / R), sigma0 = (P / S) * (b0 * (1 + S / P) + Math.PI - Math.PI / P - pi0);
1077
+ const b0 = pl[0].beta,
1078
+ pi0 = (R / P) * (gr - b0 * (1 - P / R) + Math.PI / R),
1079
+ sigma0 = (P / S) * (b0 * (1 + S / P) + Math.PI - Math.PI / P - pi0);
538
1080
  // Willis on rotations from the zero (sun σ, carrier κ, ring ρ): σ − κ + (R/S)(ρ − κ) = σ0
539
1081
  const coef = { sun: 1, carrier: -(1 + R / S), ring: R / S };
540
1082
  const sg = { [drive]: sign(lead), [third]: sign(follower) };
541
1083
  // the third's rotation for the driver's: from the relation, with the held one still
542
- const rot = (d) => { const r = { [held[0]]: 0, [drive]: sg[drive] * d }; r[third] = (sigma0 - coef[drive] * r[drive]) / coef[third]; return r; };
1084
+ const rot = (d) => {
1085
+ const r = { [held[0]]: 0, [drive]: sg[drive] * d };
1086
+ r[third] = (sigma0 - coef[drive] * r[drive]) / coef[third];
1087
+ return r;
1088
+ };
543
1089
  // a straight line in the driver's value (f: degrees in, radians out): [ratio, offset in degrees]
544
- const lin = (f) => { const a = f(0), b = f(1), o = a / DEG; return [(b - a) / DEG, ((o + 180) % 360 + 360) % 360 - 180]; }; // (the offset a part-turn: a whole turn is the same place)
545
- const free = (j) => { j.limits = j.dofs[0].slice(0, 2); j.dofs[0] = [-1e6, 1e6, j.dofs[0][2]]; }; // what follows a sun can turn past a turn
1090
+ const lin = (f) => {
1091
+ const a = f(0),
1092
+ b = f(1),
1093
+ o = a / DEG;
1094
+ return [(b - a) / DEG, ((((o + 180) % 360) + 360) % 360) - 180];
1095
+ }; // (the offset a part-turn: a whole turn is the same place)
1096
+ const free = (j) => {
1097
+ j.limits = j.dofs[0].slice(0, 2);
1098
+ j.dofs[0] = [-1e6, 1e6, j.dofs[0][2]];
1099
+ }; // what follows a sun can turn past a turn
546
1100
  const [k3, o3] = lin((d) => sg[third] * rot(d * DEG)[third]);
547
- follower.follow = [lead.id, k3, o3]; free(follower);
548
- const findings = [], f = (level, text, code, between) => findings.push({ level, text, code, ...(between ? { between } : {}) });
1101
+ follower.follow = [lead.id, k3, o3];
1102
+ free(follower);
1103
+ const findings = [],
1104
+ f = (level, text, code, between) => findings.push({ level, text, code, ...(between ? { between } : {}) });
549
1105
  pl.forEach((p, i) => {
550
1106
  // the planet's first tooth from the sun's mesh: π = −(S/P) σ + β (1 + S/P) + π − π/P, β the planet's place
551
- const tooth = (d) => { const r = rot(d * DEG), beta = p.beta + r.carrier; return -(S / P) * r.sun + beta * (1 + S / P) + Math.PI - Math.PI / P; };
1107
+ const tooth = (d) => {
1108
+ const r = rot(d * DEG),
1109
+ beta = p.beta + r.carrier;
1110
+ return -(S / P) * r.sun + beta * (1 + S / P) + Math.PI - Math.PI / P;
1111
+ };
552
1112
  const [kp, op] = lin((d) => p.s * (tooth(d) - p.gamma - rot(d * DEG).carrier));
553
- p.joint.follow = [lead.id, kp, op]; free(p.joint);
1113
+ p.joint.follow = [lead.id, kp, op];
1114
+ free(p.joint);
554
1115
  // and with the ring: in phase with it too, or it can't go there
555
- const ringTooth = (P / R) * tooth(0) + p.beta * (1 - P / R) - Math.PI / R, pitch = (2 * Math.PI) / R;
556
- const miss = (((ringTooth - gr) % pitch) + pitch * 1.5) % pitch - pitch / 2;
1116
+ const ringTooth = (P / R) * tooth(0) + p.beta * (1 - P / R) - Math.PI / R,
1117
+ pitch = (2 * Math.PI) / R;
1118
+ const miss = ((((ringTooth - gr) % pitch) + pitch * 1.5) % pitch) - pitch / 2;
557
1119
  const centre = org(W(planets[i]));
558
- if (Math.abs(miss) > 1e-6) f('fail', `planet ${p.id} can't mesh with the sun and the ring at once where it is (${(p.beta / DEG).toFixed(2)}° round the sun): planets go every ${(360 / planets.length).toFixed(2)}°, and (S + R) / planets must be whole (${S + R} / ${planets.length})`, 'planetary.phase', [O, centre]);
1120
+ if (Math.abs(miss) > 1e-6)
1121
+ f(
1122
+ 'fail',
1123
+ `planet ${p.id} can't mesh with the sun and the ring at once where it is (${(p.beta / DEG).toFixed(2)}° round the sun): planets go every ${(360 / planets.length).toFixed(2)}°, and (S + R) / planets must be whole (${S + R} / ${planets.length})`,
1124
+ 'planetary.phase',
1125
+ [O, centre],
1126
+ );
559
1127
  const m = meshOf(sun, planet, { centre: p.r });
560
1128
  for (const x of m.findings) f(x.level, `sun and ${p.id}: ${x.text}`, x.code, [O, centre]);
561
1129
  if (i === 0) {
562
- for (const x of measured({ ...common, teeth: S }, { ...common, teeth: P }, p.r).findings) f(x.level, `sun and ${p.id}: ${x.text}`, x.code, [O, centre]);
563
- for (const x of measured({ ...common, teeth: P }, { ...common, teeth: R, kind: 'internal' }, p.r).findings) f(x.level, `${p.id} and the ring: ${x.text}`, x.code, [O, centre]);
1130
+ for (const x of measured({ ...common, teeth: S }, { ...common, teeth: P }, p.r).findings)
1131
+ f(x.level, `sun and ${p.id}: ${x.text}`, x.code, [O, centre]);
1132
+ for (const x of measured({ ...common, teeth: P }, { ...common, teeth: R, kind: 'internal' }, p.r).findings)
1133
+ f(x.level, `${p.id} and the ring: ${x.text}`, x.code, [O, centre]);
564
1134
  }
565
1135
  });
566
1136
  const ratioText = `the ${drive} drives the ${third}${held[0] === 'carrier' ? '' : ' and the planets'} (the ${held[0]} held): ${Number(Math.abs(k3).toFixed(4))} turns of the ${third} for each turn of the ${drive}, ${k3 * sg[drive] * sg[third] < 0 ? 'opposite ways' : 'the same way'}`;
567
- out.push({ joint: follower.id, with: lead.id, kind: 'planetary', text: ratioText, findings, between: [O, O], planetary: true, members: [follower.id, ...planetJoints.map((j) => j.id)] });
1137
+ out.push({
1138
+ joint: follower.id,
1139
+ with: lead.id,
1140
+ kind: 'planetary',
1141
+ text: ratioText,
1142
+ findings,
1143
+ between: [O, O],
1144
+ planetary: true,
1145
+ members: [follower.id, ...planetJoints.map((j) => j.id)],
1146
+ });
568
1147
  // A second ring, on the planets' second step: it follows the planets' turning as the first ring would
569
1148
  if (g.output) {
570
- const k2 = index(g.output.ring, 'output ring'), j2 = moving(k2), P2 = num(g.output.planet), R2 = num(g.output.teeth), oc = { ...common };
571
- if (!j2 || j2.type !== 'revolute') throw new Error(`${what}: the output ring ${g.output.ring} turns on a revolute`);
572
- if (j2.follow || j2.meshSpec) throw new Error(`${what}: ${j2.id} follows the planets here: give it no follow or mesh of its own`);
573
- if (R2 - P2 !== R - P) throw new Error(`${what}: the output ring and the planets' second step must differ as the first do: ${R2} - ${P2} isn't ${R} - ${P}, so one centre distance can't serve both`);
1149
+ const k2 = index(g.output.ring, 'output ring'),
1150
+ j2 = moving(k2),
1151
+ P2 = num(g.output.planet),
1152
+ R2 = num(g.output.teeth),
1153
+ oc = { ...common };
1154
+ if (!j2 || j2.type !== 'revolute')
1155
+ throw new Error(`${what}: the output ring ${g.output.ring} turns on a revolute`);
1156
+ if (j2.follow || j2.meshSpec)
1157
+ throw new Error(`${what}: ${j2.id} follows the planets here: give it no follow or mesh of its own`);
1158
+ if (R2 - P2 !== R - P)
1159
+ throw new Error(
1160
+ `${what}: the output ring and the planets' second step must differ as the first do: ${R2} - ${P2} isn't ${R} - ${P}, so one centre distance can't serve both`,
1161
+ );
574
1162
  let p2, r2;
575
- try { p2 = gearModel({ ...oc, teeth: P2 }); r2 = internalModel({ ...oc, teeth: R2 }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
576
- const g2 = ang(flat(col(W(k2), 0), Z), X0, Z), s2 = sign(j2), p0 = pl[0], ps = Math.PI / R2;
577
- const toothAt = (d) => { const r = rot(d * DEG); return -(S / P) * r.sun + (p0.beta + r.carrier) * (1 + S / P) + Math.PI - Math.PI / P; };
578
- const ring2 = (d) => { const r = rot(d * DEG); return (P2 / R2) * toothAt(d) + (p0.beta + r.carrier) * (1 - P2 / R2) - ps - g2; };
1163
+ try {
1164
+ p2 = gearModel({ ...oc, teeth: P2 });
1165
+ r2 = internalModel({ ...oc, teeth: R2 });
1166
+ } catch (e) {
1167
+ throw new Error(`${what}: ${e.message}`);
1168
+ }
1169
+ const g2 = ang(flat(col(W(k2), 0), Z), X0, Z),
1170
+ s2 = sign(j2),
1171
+ p0 = pl[0],
1172
+ ps = Math.PI / R2;
1173
+ const toothAt = (d) => {
1174
+ const r = rot(d * DEG);
1175
+ return -(S / P) * r.sun + (p0.beta + r.carrier) * (1 + S / P) + Math.PI - Math.PI / P;
1176
+ };
1177
+ const ring2 = (d) => {
1178
+ const r = rot(d * DEG);
1179
+ return (P2 / R2) * toothAt(d) + (p0.beta + r.carrier) * (1 - P2 / R2) - ps - g2;
1180
+ };
579
1181
  const [k, o] = lin((d) => s2 * ring2(d));
580
- j2.follow = [lead.id, k, o]; free(j2);
581
- const eff = compoundEfficiency({ planet: P, planet2: P2, ring: R, ring2: R2 }), fails = [], ff = (level, text, code) => fails.push({ level, text, code, between: [O, O] });
582
- for (const x of meshOf(p2, r2, { centre: pl[0].r }).findings) ff(x.level, `${pl[0].id} and the output ring: ${x.text}`, x.code);
1182
+ j2.follow = [lead.id, k, o];
1183
+ free(j2);
1184
+ const eff = compoundEfficiency({ planet: P, planet2: P2, ring: R, ring2: R2 }),
1185
+ fails = [],
1186
+ ff = (level, text, code) => fails.push({ level, text, code, between: [O, O] });
1187
+ for (const x of meshOf(p2, r2, { centre: pl[0].r }).findings)
1188
+ ff(x.level, `${pl[0].id} and the output ring: ${x.text}`, x.code);
583
1189
  // Each planet's second step in phase with the output ring. A planet meshes the sun as well a whole tooth of its
584
1190
  // first step on (2π/P), and that turns its second step too: the first of those turns that puts it in phase with
585
1191
  // the ring is the one it takes (none, where every planet is in phase as it stands, as chapter 11's are)
586
1192
  pl.forEach((p, i) => {
587
- const pitch2 = (2 * Math.PI) / R2, missAt = (m) => { const t2 = (P2 / R2) * ((-(S / P) * sigma0 + p.beta * (1 + S / P) + Math.PI - Math.PI / P + (2 * Math.PI * m) / P)) + p.beta * (1 - P2 / R2) - ps; return (((t2 - (P2 / R2) * ((-(S / P) * sigma0 + p0.beta * (1 + S / P) + Math.PI - Math.PI / P)) - p0.beta * (1 - P2 / R2) + ps) % pitch2) + pitch2 * 1.5) % pitch2 - pitch2 / 2; };
1193
+ const pitch2 = (2 * Math.PI) / R2,
1194
+ missAt = (m) => {
1195
+ const t2 =
1196
+ (P2 / R2) * (-(S / P) * sigma0 + p.beta * (1 + S / P) + Math.PI - Math.PI / P + (2 * Math.PI * m) / P) +
1197
+ p.beta * (1 - P2 / R2) -
1198
+ ps;
1199
+ return (
1200
+ ((((t2 -
1201
+ (P2 / R2) * (-(S / P) * sigma0 + p0.beta * (1 + S / P) + Math.PI - Math.PI / P) -
1202
+ p0.beta * (1 - P2 / R2) +
1203
+ ps) %
1204
+ pitch2) +
1205
+ pitch2 * 1.5) %
1206
+ pitch2) -
1207
+ pitch2 / 2
1208
+ );
1209
+ };
588
1210
  const m = i === 0 ? 0 : Array.from({ length: P }, (_, k) => k).find((k) => Math.abs(missAt(k)) <= 1e-6);
589
- if (m == null) ff('fail', `planet ${p.id} can't mesh with the output ring where it is, whichever tooth of its first step meets the sun: every tooth count a multiple of the planets puts them all in phase`, 'planetary.phase');
590
- else if (m) p.joint.follow = [p.joint.follow[0], p.joint.follow[1], (((p.joint.follow[2] + (p.s * 360 * m) / P + 180) % 360) + 360) % 360 - 180];
1211
+ if (m == null)
1212
+ ff(
1213
+ 'fail',
1214
+ `planet ${p.id} can't mesh with the output ring where it is, whichever tooth of its first step meets the sun: every tooth count a multiple of the planets puts them all in phase`,
1215
+ 'planetary.phase',
1216
+ );
1217
+ else if (m)
1218
+ p.joint.follow = [
1219
+ p.joint.follow[0],
1220
+ p.joint.follow[1],
1221
+ ((((p.joint.follow[2] + (p.s * 360 * m) / P + 180) % 360) + 360) % 360) - 180,
1222
+ ];
1223
+ });
1224
+ out.push({
1225
+ joint: j2.id,
1226
+ with: lead.id,
1227
+ kind: 'planetary',
1228
+ efficiency: eff,
1229
+ text: `the second ring turns ${Number(Math.abs(k).toFixed(5))} of the ${drive}'s turn, ${k * s2 * sg[drive] < 0 ? 'the other way' : 'the same way'} (${Number((1 / Math.abs(k)).toFixed(2))}:1, about ${Math.round(eff * 100)}% efficient, an estimate)`,
1230
+ findings: fails,
1231
+ between: [O, O],
1232
+ planetary: true,
591
1233
  });
592
- out.push({ joint: j2.id, with: lead.id, kind: 'planetary', efficiency: eff, text: `the second ring turns ${Number(Math.abs(k).toFixed(5))} of the ${drive}'s turn, ${k * s2 * sg[drive] < 0 ? 'the other way' : 'the same way'} (${Number((1 / Math.abs(k)).toFixed(2))}:1, about ${Math.round(eff * 100)}% efficient, an estimate)`, findings: fails, between: [O, O], planetary: true });
593
1234
  }
594
1235
  });
595
1236
  return out;
@@ -599,37 +1240,85 @@ function planetaries(list, joints, items, num) {
599
1240
  // whose axes meet at the shaft angle, each gear drawn as @rulecad/gears draws one (back end at z = 0, apex up z). The
600
1241
  // cones must share their apex. The ratio is the surface speeds' where the pitch cones touch; the phase puts a tooth
601
1242
  // of one against a space of the other along that line.
602
- function bevelDrive(j, lead, spec, teeth, common, joints, items, num) {
603
- const what = `joint ${j.id}: mesh`, DEG = Math.PI / 180;
604
- const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
605
- const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], add = (a, b) => a.map((x, i) => x + b[i]), times = (a, k) => a.map((x) => x * k);
606
- const crossP = (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]], len = (v) => Math.hypot(...v), unit = (v) => times(v, 1 / len(v));
1243
+ function bevelDrive(j, lead, spec, teeth, common, joints, items) {
1244
+ const what = `joint ${j.id}: mesh`,
1245
+ DEG = Math.PI / 180;
1246
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]],
1247
+ org = (W) => [W[3], W[7], W[11]];
1248
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
1249
+ sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]],
1250
+ add = (a, b) => a.map((x, i) => x + b[i]),
1251
+ times = (a, k) => a.map((x) => x * k);
1252
+ const crossP = (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]],
1253
+ len = (v) => Math.hypot(...v),
1254
+ unit = (v) => times(v, 1 / len(v));
607
1255
  const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v));
608
- const v = jointValues({ joints, poses: {} }, {}); v[lead.id] = [0]; v[j.id] = [0];
609
- const worlds = placeItems({ items, joints }, v), W1 = worlds[lead.child], W2 = worlds[j.child];
610
- const O1 = org(W1), Z1 = col(W1, 2), X1 = col(W1, 0), O2 = org(W2), Z2 = col(W2, 2), X2 = col(W2, 0);
1256
+ const v = jointValues({ joints, poses: {} }, {});
1257
+ v[lead.id] = [0];
1258
+ v[j.id] = [0];
1259
+ const worlds = placeItems({ items, joints }, v),
1260
+ W1 = worlds[lead.child],
1261
+ W2 = worlds[j.child];
1262
+ const O1 = org(W1),
1263
+ Z1 = col(W1, 2),
1264
+ X1 = col(W1, 0),
1265
+ O2 = org(W2),
1266
+ Z2 = col(W2, 2),
1267
+ X2 = col(W2, 0);
611
1268
  const shaft = Math.acos(Math.max(-1, Math.min(1, dot(Z1, Z2)))) / DEG;
612
1269
  let g1, g2;
613
- try { g1 = bevelModel({ ...common, teeth: teeth[0], mate: teeth[1], shaftAngle: shaft }); g2 = bevelModel({ ...common, teeth: teeth[1], mate: teeth[0], shaftAngle: shaft }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
1270
+ try {
1271
+ g1 = bevelModel({ ...common, teeth: teeth[0], mate: teeth[1], shaftAngle: shaft });
1272
+ g2 = bevelModel({ ...common, teeth: teeth[1], mate: teeth[0], shaftAngle: shaft });
1273
+ } catch (e) {
1274
+ throw new Error(`${what}: ${e.message}`);
1275
+ }
614
1276
  // each cone's apex: along its axis, its cone distance × cos δ from its back end
615
- const A1 = add(O1, times(Z1, g1.coneDistance * Math.cos(g1.pitchAngle * DEG))), A2 = add(O2, times(Z2, g2.coneDistance * Math.cos(g2.pitchAngle * DEG)));
1277
+ const A1 = add(O1, times(Z1, g1.coneDistance * Math.cos(g1.pitchAngle * DEG))),
1278
+ A2 = add(O2, times(Z2, g2.coneDistance * Math.cos(g2.pitchAngle * DEG)));
616
1279
  const findings = [];
617
1280
  const apart = len(sub(A1, A2));
618
- if (apart > 0.01) findings.push({ level: 'fail', text: `the cones' apexes are ${Number(apart.toFixed(3))} mm apart: bevel gears mesh only when their cones meet at one point (move one along its axis)`, code: 'mesh.bevel' });
1281
+ if (apart > 0.01)
1282
+ findings.push({
1283
+ level: 'fail',
1284
+ text: `the cones' apexes are ${Number(apart.toFixed(3))} mm apart: bevel gears mesh only when their cones meet at one point (move one along its axis)`,
1285
+ code: 'mesh.bevel',
1286
+ });
619
1287
  // where the pitch cones touch: from the apex, δ1 from the first's axis toward the second's (both pointing away)
620
- const out1 = times(Z1, -1), out2 = times(Z2, -1), across = unit(sub(out2, times(out1, dot(out1, out2))));
621
- const g = add(times(out1, Math.cos(g1.pitchAngle * DEG)), times(across, Math.sin(g1.pitchAngle * DEG))), P = add(A1, times(g, g1.coneDistance));
622
- const radial = (Z, X) => { const r = sub(g, times(Z, dot(g, Z))); return ang(r, X, Z); };
623
- const b1 = radial(Z1, X1), b2 = radial(Z2, X2);
1288
+ const out1 = times(Z1, -1),
1289
+ out2 = times(Z2, -1),
1290
+ across = unit(sub(out2, times(out1, dot(out1, out2))));
1291
+ const g = add(times(out1, Math.cos(g1.pitchAngle * DEG)), times(across, Math.sin(g1.pitchAngle * DEG))),
1292
+ P = add(A1, times(g, g1.coneDistance));
1293
+ const radial = (Z, X) => {
1294
+ const r = sub(g, times(Z, dot(g, Z)));
1295
+ return ang(r, X, Z);
1296
+ };
1297
+ const b1 = radial(Z1, X1),
1298
+ b2 = radial(Z2, X2);
624
1299
  // the second turns so the surface speeds match where they touch: ω2 = ω1 (Z1 × P)·(Z2 × P) / |Z2 × P|², P from the apex
625
- const p = sub(P, A1), r = dot(crossP(Z1, p), crossP(Z2, p)) / dot(crossP(Z2, p), crossP(Z2, p));
626
- const sgn = (jt, Z) => Math.sign(dot(col(mul(jt.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[jt.parent], jt.a), 2), Z));
627
- const s1 = sgn(lead, Z1), s2 = sgn(j, Z2), z2 = teeth[1];
1300
+ const p = sub(P, A1),
1301
+ r = dot(crossP(Z1, p), crossP(Z2, p)) / dot(crossP(Z2, p), crossP(Z2, p));
1302
+ const sgn = (jt, Z) =>
1303
+ Math.sign(dot(col(mul(jt.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[jt.parent], jt.a), 2), Z));
1304
+ const s1 = sgn(lead, Z1),
1305
+ s2 = sgn(j, Z2),
1306
+ z2 = teeth[1];
628
1307
  const phi = b2 - Math.PI / z2 - r * b1;
629
1308
  j.follow = [lead.id, s2 * r * s1, (s2 * phi) / DEG];
630
- const m = bevelMesh({ ...common, teeth: teeth[0], shaftAngle: shaft }, { ...common, teeth: teeth[1], shaftAngle: shaft });
1309
+ const m = bevelMesh(
1310
+ { ...common, teeth: teeth[0], shaftAngle: shaft },
1311
+ { ...common, teeth: teeth[1], shaftAngle: shaft },
1312
+ );
631
1313
  findings.push(...m.findings);
632
- return { joint: j.id, with: lead.id, kind: 'bevel', findings, between: [O1, O2], text: `bevel gears at ${Number(shaft.toFixed(2))}°, ${Number((teeth[0] / teeth[1]).toFixed(4))} turns of the second for each of the first (cones of ${Number(g1.pitchAngle.toFixed(2))}° and ${Number(g2.pitchAngle.toFixed(2))}°)` };
1314
+ return {
1315
+ joint: j.id,
1316
+ with: lead.id,
1317
+ kind: 'bevel',
1318
+ findings,
1319
+ between: [O1, O2],
1320
+ text: `bevel gears at ${Number(shaft.toFixed(2))}°, ${Number((teeth[0] / teeth[1]).toFixed(4))} turns of the second for each of the first (cones of ${Number(g1.pitchAngle.toFixed(2))}° and ${Number(g2.pitchAngle.toFixed(2))}°)`,
1321
+ };
633
1322
  }
634
1323
 
635
1324
  // A worm and its wheel: "mesh": { "with": <the worm's joint>, "module", "teeth": [starts, wheel's teeth], "worm": {
@@ -637,36 +1326,103 @@ function bevelDrive(j, lead, spec, teeth, common, joints, items, num) {
637
1326
  // rack along the worm's axis, moving a lead a turn: the wheel follows it as a pinion does a rack, its helix's turn at
638
1327
  // that plane taken into account. The worm is drawn as @rulecad/gears draws it (axis up its z, from z = 0).
639
1328
  function wormDrive(j, lead, spec, teeth, common, joints, items, num) {
640
- const what = `joint ${j.id}: mesh`, DEG = Math.PI / 180;
641
- const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
642
- const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
643
- const crossP = (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]], len = (v) => Math.hypot(...v);
1329
+ const what = `joint ${j.id}: mesh`,
1330
+ DEG = Math.PI / 180;
1331
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]],
1332
+ org = (W) => [W[3], W[7], W[11]];
1333
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
1334
+ sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
1335
+ const crossP = (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]],
1336
+ len = (v) => Math.hypot(...v);
644
1337
  const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v));
645
1338
  const ws = spec.worm === true ? {} : spec.worm;
646
1339
  let w, wheel;
647
1340
  try {
648
- w = wormModel({ ...common, starts: teeth[0], ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}), ...(ws.hand ? { hand: ws.hand } : {}) });
1341
+ w = wormModel({
1342
+ ...common,
1343
+ starts: teeth[0],
1344
+ ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}),
1345
+ ...(ws.hand ? { hand: ws.hand } : {}),
1346
+ });
649
1347
  wheel = gearModel({ ...common, teeth: teeth[1], helix: w.leadAngle, hand: w.hand });
650
- } catch (e) { throw new Error(`${what}: ${e.message}`); }
651
- const v = jointValues({ joints, poses: {} }, {}); v[lead.id] = [0]; v[j.id] = [0];
652
- const worlds = placeItems({ items, joints }, v), Ww = worlds[lead.child], W2 = worlds[j.child];
653
- const Ow = org(Ww), U = col(Ww, 2), Xw = col(Ww, 0), O2 = org(W2), Z2 = col(W2, 2), X2 = col(W2, 0);
1348
+ } catch (e) {
1349
+ throw new Error(`${what}: ${e.message}`);
1350
+ }
1351
+ const v = jointValues({ joints, poses: {} }, {});
1352
+ v[lead.id] = [0];
1353
+ v[j.id] = [0];
1354
+ const worlds = placeItems({ items, joints }, v),
1355
+ Ww = worlds[lead.child],
1356
+ W2 = worlds[j.child];
1357
+ const Ow = org(Ww),
1358
+ U = col(Ww, 2),
1359
+ Xw = col(Ww, 0),
1360
+ O2 = org(W2),
1361
+ Z2 = col(W2, 2),
1362
+ X2 = col(W2, 0);
654
1363
  if (Math.abs(dot(U, Z2)) > 1e-6) throw new Error(`${what}: a worm's axis and its wheel's cross at right angles`);
655
1364
  // the line between the axes: across both (the worm's along U, the wheel's along Z2)
656
- const rel = sub(O2, Ow), at = dot(rel, U), toWheel = sub(sub(rel, U.map((x) => x * at)), Z2.map((x) => x * dot(rel, Z2))), dist = len(toWheel), Y = toWheel.map((x) => x / dist), Zr = crossP(U, Y);
657
- const sense = w.hand === 'left' ? -1 : 1, sw = Math.sign(dot(col(mul(lead.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[lead.parent], lead.a), 2), U));
658
- const s2 = Math.sign(dot(Z2, Zr)), tw = ang(Y, Xw, U), g2 = ang(X2, U, Zr) * 1, r2 = wheel.pitch / 2;
1365
+ const rel = sub(O2, Ow),
1366
+ at = dot(rel, U),
1367
+ toWheel = sub(
1368
+ sub(
1369
+ rel,
1370
+ U.map((x) => x * at),
1371
+ ),
1372
+ Z2.map((x) => x * dot(rel, Z2)),
1373
+ ),
1374
+ dist = len(toWheel),
1375
+ Y = toWheel.map((x) => x / dist),
1376
+ Zr = crossP(U, Y);
1377
+ const sense = w.hand === 'left' ? -1 : 1,
1378
+ sw = Math.sign(
1379
+ dot(col(mul(lead.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[lead.parent], lead.a), 2), U),
1380
+ );
1381
+ const s2 = Math.sign(dot(Z2, Zr)),
1382
+ tw = ang(Y, Xw, U),
1383
+ g2 = ang(X2, U, Zr) * 1,
1384
+ r2 = wheel.pitch / 2;
659
1385
  // the wheel's helix: its tooth 0 at the worm's plane is turned by k z there
660
- const zMid = dot(sub(Ow, O2), Z2), k = (sense * Math.tan(w.leadAngle * DEG)) / r2;
661
- const phr = rackPhase(wheel, at), L = w.lead;
1386
+ const zMid = dot(sub(Ow, O2), Z2),
1387
+ k = (sense * Math.tan(w.leadAngle * DEG)) / r2;
1388
+ const phr = rackPhase(wheel, at),
1389
+ L = w.lead;
662
1390
  // space centres of the thread, at the wheel, sit at z0 = sense L (tw − θw) / 2π along the worm; the wheel turns as on a rack
663
- const theta = (dw) => { const z0 = (sense * L * (tw - sw * dw * DEG)) / (2 * Math.PI); return s2 * ((z0 - phr) / r2 - g2) - k * zMid; };
664
- const a0 = theta(0), a1 = theta(1);
1391
+ const theta = (dw) => {
1392
+ const z0 = (sense * L * (tw - sw * dw * DEG)) / (2 * Math.PI);
1393
+ return s2 * ((z0 - phr) / r2 - g2) - k * zMid;
1394
+ };
1395
+ const a0 = theta(0),
1396
+ a1 = theta(1);
665
1397
  j.follow = [lead.id, (a1 - a0) / DEG, a0 / DEG];
666
- const m = wormMesh({ ...common, starts: teeth[0], ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}), ...(ws.hand ? { hand: ws.hand } : {}) }, { teeth: teeth[1] });
1398
+ const m = wormMesh(
1399
+ {
1400
+ ...common,
1401
+ starts: teeth[0],
1402
+ ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}),
1403
+ ...(ws.hand ? { hand: ws.hand } : {}),
1404
+ },
1405
+ { teeth: teeth[1] },
1406
+ );
667
1407
  const c = meshOf(wheel, rackModel({ ...common, teeth: 4 }), { centre: dist - w.pitch / 2 });
668
- const findings = [...m.findings, ...c.findings.filter((x) => x.code === 'mesh.centre').map((x) => ({ ...x, text: x.text.replace("centre to the rack's pitch line", "the wheel's centre to the worm's pitch cylinder") }))];
669
- return { joint: j.id, with: lead.id, kind: 'worm', worm: m, findings, between: [Ow.map((x, i) => x + U[i] * at), O2], text: `a worm of ${teeth[0]} start${teeth[0] > 1 ? 's' : ''}, ${Number((teeth[1] / teeth[0]).toFixed(3))} turns of the worm for one of the wheel` };
1408
+ const findings = [
1409
+ ...m.findings,
1410
+ ...c.findings
1411
+ .filter((x) => x.code === 'mesh.centre')
1412
+ .map((x) => ({
1413
+ ...x,
1414
+ text: x.text.replace("centre to the rack's pitch line", "the wheel's centre to the worm's pitch cylinder"),
1415
+ })),
1416
+ ];
1417
+ return {
1418
+ joint: j.id,
1419
+ with: lead.id,
1420
+ kind: 'worm',
1421
+ worm: m,
1422
+ findings,
1423
+ between: [Ow.map((x, i) => x + U[i] * at), O2],
1424
+ text: `a worm of ${teeth[0]} start${teeth[0] > 1 ? 's' : ''}, ${Number((teeth[1] / teeth[0]).toFixed(3))} turns of the worm for one of the wheel`,
1425
+ };
670
1426
  }
671
1427
 
672
1428
  // Gears that mesh: "mesh": { "with": <the driving joint>, "module", "teeth": [its, this one's], "shift"?, "ring"? } on
@@ -674,85 +1430,252 @@ function wormDrive(j, lead, spec, teeth, common, joints, items, num) {
674
1430
  // teeth, and the offset that puts a tooth in a gap, read from where the two gears are with their joints at 0. Each
675
1431
  // gear is drawn as @rulecad/gears draws it (its axis up its own z, its first tooth on +x; a rack along its x, teeth up
676
1432
  // +y, its first space at x = 0), and its joint turns it about its own axis. The centre distance is checked here, the
677
- // rest of the meshing by --sweep.
1433
+ // rest of the meshing by --sweep. Each spur, internal and rack mesh also keeps its gears' items and tip circles (a rack's
1434
+ // tip line) in faces, for checkAssembly to find their teeth in the drawn parts and measure how much of the faces meet.
678
1435
  function gearMeshes(joints, items, num) {
679
- const out = [], list = (x) => (x == null ? [] : [].concat(x));
680
- const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
681
- const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
1436
+ const out = [],
1437
+ list = (x) => (x == null ? [] : [].concat(x));
1438
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]],
1439
+ org = (W) => [W[3], W[7], W[11]];
1440
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
1441
+ sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
682
1442
  const crossP = (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]];
683
- const along = (v, axis) => sub(v, axis.map((x) => x * dot(v, axis))), len = (v) => Math.hypot(...v);
1443
+ const along = (v, axis) =>
1444
+ sub(
1445
+ v,
1446
+ axis.map((x) => x * dot(v, axis)),
1447
+ ),
1448
+ len = (v) => Math.hypot(...v);
684
1449
  const angleIn = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v)) / (Math.PI / 180); // v's angle from x0 about z, degrees
685
1450
  // Is an item held still relative to another: every joint between it and the world fixed (or no joint at all)?
686
1451
  const byChild = new Map(joints.map((j) => [j.child, j]));
687
- const still = (i) => { for (let k = i, n = 0; k >= 0 && n < 99; n++) { const j = byChild.get(k); if (!j) return true; if (j.type !== 'fixed') return false; k = j.parent; } return true; };
1452
+ const still = (i) => {
1453
+ for (let k = i, n = 0; k >= 0 && n < 99; n++) {
1454
+ const j = byChild.get(k);
1455
+ if (!j) return true;
1456
+ if (j.type !== 'fixed') return false;
1457
+ k = j.parent;
1458
+ }
1459
+ return true;
1460
+ };
688
1461
  for (const j of joints) {
689
1462
  if (!j.meshSpec) continue;
690
- const spec = j.meshSpec, what = `joint ${j.id}: mesh`;
1463
+ const spec = j.meshSpec,
1464
+ what = `joint ${j.id}: mesh`;
691
1465
  delete j.meshSpec;
692
1466
  if (j.follow) throw new Error(`${what}: a meshed joint follows its mate already: give mesh or follow, not both`);
693
1467
  const lead = joints.find((x) => x.id === spec.with);
694
- if (!lead) throw new Error(`${what}: "with" names the driving joint (${joints.filter((x) => x !== j).map((x) => x.id).join(', ')}; got ${JSON.stringify(spec.with)})`);
695
- if (lead.type !== 'revolute') throw new Error(`${what}: ${lead.id} is a ${lead.type}; the driver is a gear turning on a revolute`);
696
- if (j.type !== 'revolute' && j.type !== 'prismatic') throw new Error(`${what}: a gear turns on a revolute, a rack slides on a prismatic (this is a ${j.type})`);
697
- const kind = spec.bevel ? 'bevel' : spec.worm ? 'worm' : j.type === 'prismatic' ? 'rack' : spec.ring ? 'internal' : 'external';
698
- if (!(lead.parent === j.parent || (still(lead.parent) && still(j.parent)))) throw new Error(`${what}: ${lead.id} and ${j.id} turn on parts that move apart (a planet on a carrier): a mesh needs both on one part, or both on parts held still`);
699
- const teeth = list(spec.teeth).map(num), shift = list(spec.shift ?? [0, 0]).map(num);
700
- if (teeth.length !== 2) throw new Error(`${what}: teeth is [the driver's, this one's] (got ${JSON.stringify(spec.teeth)})`);
701
- const common = { module: num(spec.module), ...(spec.pressureAngle != null ? { pressureAngle: num(spec.pressureAngle) } : {}), ...(spec.backlash != null ? { backlash: num(spec.backlash) } : {}) };
702
- if (kind === 'worm') { out.push(wormDrive(j, lead, spec, teeth, common, joints, items, num)); continue; }
703
- if (kind === 'bevel') { out.push(bevelDrive(j, lead, spec, teeth, common, joints, items, num)); continue; }
1468
+ if (!lead)
1469
+ throw new Error(
1470
+ `${what}: "with" names the driving joint (${joints
1471
+ .filter((x) => x !== j)
1472
+ .map((x) => x.id)
1473
+ .join(', ')}; got ${JSON.stringify(spec.with)})`,
1474
+ );
1475
+ if (lead.type !== 'revolute')
1476
+ throw new Error(`${what}: ${lead.id} is a ${lead.type}; the driver is a gear turning on a revolute`);
1477
+ if (j.type !== 'revolute' && j.type !== 'prismatic')
1478
+ throw new Error(`${what}: a gear turns on a revolute, a rack slides on a prismatic (this is a ${j.type})`);
1479
+ const kind = spec.bevel
1480
+ ? 'bevel'
1481
+ : spec.worm
1482
+ ? 'worm'
1483
+ : j.type === 'prismatic'
1484
+ ? 'rack'
1485
+ : spec.ring
1486
+ ? 'internal'
1487
+ : 'external';
1488
+ if (!(lead.parent === j.parent || (still(lead.parent) && still(j.parent))))
1489
+ throw new Error(
1490
+ `${what}: ${lead.id} and ${j.id} turn on parts that move apart (a planet on a carrier): a mesh needs both on one part, or both on parts held still`,
1491
+ );
1492
+ const teeth = list(spec.teeth).map(num),
1493
+ shift = list(spec.shift ?? [0, 0]).map(num);
1494
+ if (teeth.length !== 2)
1495
+ throw new Error(`${what}: teeth is [the driver's, this one's] (got ${JSON.stringify(spec.teeth)})`);
1496
+ const common = {
1497
+ module: num(spec.module),
1498
+ ...(spec.pressureAngle != null ? { pressureAngle: num(spec.pressureAngle) } : {}),
1499
+ ...(spec.backlash != null ? { backlash: num(spec.backlash) } : {}),
1500
+ };
1501
+ if (kind === 'worm') {
1502
+ out.push(wormDrive(j, lead, spec, teeth, common, joints, items, num));
1503
+ continue;
1504
+ }
1505
+ if (kind === 'bevel') {
1506
+ out.push(bevelDrive(j, lead, spec, teeth, common, joints, items));
1507
+ continue;
1508
+ }
704
1509
  let A, B;
705
1510
  try {
706
1511
  A = gearModel({ ...common, teeth: teeth[0], shift: shift[0] });
707
- B = kind === 'rack' ? rackModel({ ...common, teeth: teeth[1] }) : (kind === 'internal' ? internalModel : gearModel)({ ...common, teeth: teeth[1], shift: shift[1] ?? 0 });
708
- } catch (e) { throw new Error(`${what}: ${e.message}`); }
1512
+ B =
1513
+ kind === 'rack'
1514
+ ? rackModel({ ...common, teeth: teeth[1] })
1515
+ : (kind === 'internal' ? internalModel : gearModel)({ ...common, teeth: teeth[1], shift: shift[1] ?? 0 });
1516
+ } catch (e) {
1517
+ throw new Error(`${what}: ${e.message}`);
1518
+ }
709
1519
  // Where the two gears are with their own joints at 0 (everything else as it stands by default)
710
- const v = jointValues({ joints: joints.map((x) => (x.meshSpec ? { ...x, meshSpec: undefined } : x)), poses: {} }, {});
711
- v[lead.id] = [0]; v[j.id] = [0];
712
- const worlds = placeItems({ items, joints }, v), W1 = worlds[lead.child], W2 = worlds[j.child];
713
- const axisOf = (jt) => { const P = mul(jt.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[jt.parent], jt.a); return { at: org(P), dir: col(P, 2) }; };
714
- const O1 = org(W1), X1 = col(W1, 0), Z1 = col(W1, 2), ax1 = axisOf(lead);
1520
+ const v = jointValues(
1521
+ { joints: joints.map((x) => (x.meshSpec ? { ...x, meshSpec: undefined } : x)), poses: {} },
1522
+ {},
1523
+ );
1524
+ v[lead.id] = [0];
1525
+ v[j.id] = [0];
1526
+ const worlds = placeItems({ items, joints }, v),
1527
+ W1 = worlds[lead.child],
1528
+ W2 = worlds[j.child];
1529
+ const axisOf = (jt) => {
1530
+ const P = mul(jt.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[jt.parent], jt.a);
1531
+ return { at: org(P), dir: col(P, 2) };
1532
+ };
1533
+ const O1 = org(W1),
1534
+ X1 = col(W1, 0),
1535
+ Z1 = col(W1, 2),
1536
+ ax1 = axisOf(lead);
715
1537
  // the driver turns about its own centre and axis, or its teeth wander
716
- if (Math.abs(Math.abs(dot(ax1.dir, Z1)) - 1) > 1e-6 || len(along(sub(O1, ax1.at), ax1.dir)) > 1e-4) throw new Error(`${what}: ${lead.id} doesn't turn its gear about the gear's own centre and axis: anchor the gear's joint at its centre, along its axis`);
1538
+ if (Math.abs(Math.abs(dot(ax1.dir, Z1)) - 1) > 1e-6 || len(along(sub(O1, ax1.at), ax1.dir)) > 1e-4)
1539
+ throw new Error(
1540
+ `${what}: ${lead.id} doesn't turn its gear about the gear's own centre and axis: anchor the gear's joint at its centre, along its axis`,
1541
+ );
717
1542
  const result = { joint: j.id, with: lead.id, kind, findings: [], between: null };
718
1543
  if (kind === 'rack') {
719
- const R0 = org(W2), U = col(W2, 0), Y = col(W2, 1), Zr = col(W2, 2), ax2 = axisOf(j);
1544
+ const R0 = org(W2),
1545
+ U = col(W2, 0),
1546
+ Y = col(W2, 1),
1547
+ Zr = col(W2, 2),
1548
+ ax2 = axisOf(j);
720
1549
  const sTravel = Math.sign(dot(ax2.dir, U));
721
- if (Math.abs(Math.abs(dot(ax2.dir, U)) - 1) > 1e-6) throw new Error(`${what}: ${j.id} doesn't slide the rack along its length (the rack's x)`);
722
- if (Math.abs(Math.abs(dot(Z1, Zr)) - 1) > 1e-6) throw new Error(`${what}: the pinion's axis isn't across the rack (along the rack's z)`);
723
- const s1 = Math.sign(dot(Z1, Zr)), rel = sub(O1, R0), at = dot(rel, U), height = dot(rel, Y);
724
- const k = (Math.PI * A.pitch) / 360, g1 = angleIn(along(X1, Zr), U, Zr);
1550
+ if (Math.abs(Math.abs(dot(ax2.dir, U)) - 1) > 1e-6)
1551
+ throw new Error(`${what}: ${j.id} doesn't slide the rack along its length (the rack's x)`);
1552
+ if (Math.abs(Math.abs(dot(Z1, Zr)) - 1) > 1e-6)
1553
+ throw new Error(`${what}: the pinion's axis isn't across the rack (along the rack's z)`);
1554
+ const s1 = Math.sign(dot(Z1, Zr)),
1555
+ rel = sub(O1, R0),
1556
+ at = dot(rel, U),
1557
+ height = dot(rel, Y);
1558
+ const k = (Math.PI * A.pitch) / 360,
1559
+ g1 = angleIn(along(X1, Zr), U, Zr);
725
1560
  j.follow = [lead.id, sTravel * s1 * k, sTravel * (k * g1 + rackPhase(A, at))];
726
1561
  const m = meshOf(A, B, { centre: height });
727
- result.findings = [...m.findings, ...measured({ ...common, teeth: teeth[0], shift: shift[0] }, { ...common, teeth: teeth[1], kind: 'rack' }, height).findings]; result.between = [O1, [R0[0] + at * U[0], R0[1] + at * U[1], R0[2] + at * U[2]]]; result.text = m.text;
1562
+ result.findings = [
1563
+ ...m.findings,
1564
+ ...measured(
1565
+ { ...common, teeth: teeth[0], shift: shift[0] },
1566
+ { ...common, teeth: teeth[1], kind: 'rack' },
1567
+ height,
1568
+ ).findings,
1569
+ ];
1570
+ result.between = [O1, [R0[0] + at * U[0], R0[1] + at * U[1], R0[2] + at * U[2]]];
1571
+ result.text = m.text;
1572
+ result.faces = {
1573
+ module: A.module,
1574
+ a: { item: lead.child, tip: A.tip / 2 },
1575
+ b: { item: j.child, tipLine: B.tipLine },
1576
+ };
728
1577
  } else {
729
- const O2 = org(W2), X2 = col(W2, 0), Z2 = col(W2, 2), ax2 = axisOf(j);
730
- if (Math.abs(Math.abs(dot(ax2.dir, Z2)) - 1) > 1e-6 || len(along(sub(O2, ax2.at), ax2.dir)) > 1e-4) throw new Error(`${what}: ${j.id} doesn't turn its gear about the gear's own centre and axis: anchor the gear's joint at its centre, along its axis`);
731
- if (Math.abs(Math.abs(dot(Z1, Z2)) - 1) > 1e-6) throw new Error(`${what}: ${lead.id} and ${j.id} turn about axes that aren't parallel (spur gears need parallel axes)`);
732
- const s = Math.sign(dot(Z1, Z2)), d = along(sub(O2, O1), Z1), beta = angleIn(d, X1, Z1), g2 = angleIn(along(X2, Z1), X1, Z1);
1578
+ const O2 = org(W2),
1579
+ X2 = col(W2, 0),
1580
+ Z2 = col(W2, 2),
1581
+ ax2 = axisOf(j);
1582
+ if (Math.abs(Math.abs(dot(ax2.dir, Z2)) - 1) > 1e-6 || len(along(sub(O2, ax2.at), ax2.dir)) > 1e-4)
1583
+ throw new Error(
1584
+ `${what}: ${j.id} doesn't turn its gear about the gear's own centre and axis: anchor the gear's joint at its centre, along its axis`,
1585
+ );
1586
+ if (Math.abs(Math.abs(dot(Z1, Z2)) - 1) > 1e-6)
1587
+ throw new Error(
1588
+ `${what}: ${lead.id} and ${j.id} turn about axes that aren't parallel (spur gears need parallel axes)`,
1589
+ );
1590
+ const s = Math.sign(dot(Z1, Z2)),
1591
+ d = along(sub(O2, O1), Z1),
1592
+ beta = angleIn(d, X1, Z1),
1593
+ g2 = angleIn(along(X2, Z1), X1, Z1);
733
1594
  const m = meshOf(A, B, { centre: len(d) });
734
- m.findings.push(...measured({ ...common, teeth: teeth[0], shift: shift[0] }, { ...common, teeth: teeth[1], shift: shift[1] ?? 0, kind }, len(d)).findings);
1595
+ m.findings.push(
1596
+ ...measured(
1597
+ { ...common, teeth: teeth[0], shift: shift[0] },
1598
+ { ...common, teeth: teeth[1], shift: shift[1] ?? 0, kind },
1599
+ len(d),
1600
+ ).findings,
1601
+ );
735
1602
  // b's angle in the driver's frame is ratio × a's + phase; its joint measures about its own z (the other way when flipped)
736
1603
  j.follow = [lead.id, s * m.ratio, s * (phase(A, B, beta) - g2)];
737
- result.findings = m.findings; result.between = [O1, O2]; result.text = m.text;
1604
+ result.findings = m.findings;
1605
+ result.between = [O1, O2];
1606
+ result.text = m.text;
1607
+ result.faces = {
1608
+ module: A.module,
1609
+ a: { item: lead.child, tip: A.tip / 2 },
1610
+ b: { item: j.child, tip: B.tip / 2 },
1611
+ };
738
1612
  }
739
1613
  out.push(result);
740
1614
  }
741
1615
  return out;
742
1616
  }
743
1617
 
1618
+ /**
1619
+ * How much of two meshed gears' faces meet along an axis (the driver's). Each gear's teeth are found in its drawn
1620
+ * triangles as the corners on its tip circle, within a quarter of a module (a rack's on its tip line, y = tipLine in its
1621
+ * frame), and their stretch along the axis measured: the two stretches should share most of the narrower face. A
1622
+ * gear's frame is its origin and axes in the world (its own axis up Z; a rack along X, teeth up Y). The share of the
1623
+ * narrower face passes from 80 %, warns from 50 % and fails below; a gear with no corners found has no stretch (null).
1624
+ * @param {{ module: number, along: { O: number[], Z: number[] }, a: FaceGear, b: FaceGear }} o
1625
+ * @returns {{ a: number[] | null, b: number[] | null, overlap: number, narrower: number, share: number, level: 'pass' | 'warn' | 'fail' }}
1626
+ * @typedef {{ triangles: number[][][], frame: { O: number[], X: number[], Y: number[] }, tip?: number, tipLine?: number }} FaceGear
1627
+ */
1628
+ export function meshFaces({ module, along, a, b }) {
1629
+ const dot = (u, v) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2],
1630
+ tol = module / 4;
1631
+ const span = (gear) => {
1632
+ const F = gear.frame;
1633
+ let lo = Infinity,
1634
+ hi = -Infinity;
1635
+ for (const t of gear.triangles)
1636
+ for (const v of t) {
1637
+ const d = [v[0] - F.O[0], v[1] - F.O[1], v[2] - F.O[2]];
1638
+ const off = gear.tipLine != null ? dot(d, F.Y) - gear.tipLine : Math.hypot(dot(d, F.X), dot(d, F.Y)) - gear.tip;
1639
+ if (Math.abs(off) > tol) continue;
1640
+ const at = dot([v[0] - along.O[0], v[1] - along.O[1], v[2] - along.O[2]], along.Z);
1641
+ lo = Math.min(lo, at);
1642
+ hi = Math.max(hi, at);
1643
+ }
1644
+ return hi >= lo ? [lo, hi] : null;
1645
+ };
1646
+ const sa = span(a),
1647
+ sb = span(b);
1648
+ if (!sa || !sb) return { a: sa, b: sb, overlap: 0, narrower: 0, share: 0, level: 'fail' };
1649
+ const narrower = Math.min(sa[1] - sa[0], sb[1] - sb[0]),
1650
+ shared = Math.max(0, Math.min(sa[1], sb[1]) - Math.max(sa[0], sb[0])),
1651
+ share = narrower > 0 ? shared / narrower : 0;
1652
+ return {
1653
+ a: sa,
1654
+ b: sb,
1655
+ overlap: shared,
1656
+ narrower,
1657
+ share,
1658
+ level: share >= 0.8 - 1e-9 ? 'pass' : share >= 0.5 - 1e-9 ? 'warn' : 'fail',
1659
+ };
1660
+ }
1661
+
744
1662
  // Where each item's anchors are in a pose: [{ id: 'keyboard@pivot', item, at: [x, y, z] }]
745
1663
  // Where an address is in the world, at these joint values: { id (its item), at, frame }, or null where it is not an
746
1664
  // address on a beam (x1.top@120, x1.a.1). A beam's address it does not have is refused by name.
747
1665
  export function addressAt(s, n, values = s.jointValues) {
748
- const id = String(n).split('.')[0], it = s.items.find((x) => x.id === id);
1666
+ const id = String(n).split('.')[0],
1667
+ it = s.items.find((x) => x.id === id);
749
1668
  if (!it?.beam || !String(n).includes('.') || !s.motion?.address) return null;
750
- const r = s.motion.address(n), W = mul(placeItems(s.motion, values)[r.item], r.frame);
1669
+ const r = s.motion.address(n),
1670
+ W = mul(placeItems(s.motion, values)[r.item], r.frame);
751
1671
  return { id, at: [W[3], W[7], W[11]], frame: W };
752
1672
  }
753
1673
  export function anchorsAt(s, values = s.jointValues) {
754
1674
  const worlds = placeItems(s.motion, values);
755
- return (s.motion.marks || []).map((m) => { const w = mul(worlds[m.item], m.frame); return { id: `${m.id}@${m.name}`, item: m.id, at: [w[3], w[7], w[11]] }; });
1675
+ return (s.motion.marks || []).map((m) => {
1676
+ const w = mul(worlds[m.item], m.frame);
1677
+ return { id: `${m.id}@${m.name}`, item: m.id, at: [w[3], w[7], w[11]] };
1678
+ });
756
1679
  }
757
1680
 
758
1681
  // keyCentres(layout): each key's centre, from lib/layout.mjs (kept under this name for older callers)
@@ -770,37 +1693,68 @@ export function overlap(ga, gb) {
770
1693
  // JSCAD's answer (no Manifold, or a shape Manifold couldn't read): only if fit says they really run into each other
771
1694
  // (their surfaces cross, one is inside the other, or they share volume beside a face plane they share: slower, so
772
1695
  // only here)
773
- if (!solid || solid.stats.fallbacks > fell) { const faces = (g) => jscad.geometries.geom3.toPolygons(g).map((q) => q.vertices); if (!overlapAt(faces(ga), faces(gb))) return 0; }
1696
+ if (!solid || solid.stats.fallbacks > fell) {
1697
+ const faces = (g) => jscad.geometries.geom3.toPolygons(g).map((q) => q.vertices);
1698
+ if (!overlapAt(faces(ga), faces(gb))) return 0;
1699
+ }
774
1700
  return v;
775
1701
  }
776
1702
  // How overlaps are measured: whether the surfaces cross, exactly (fit), and then how much, with Manifold where it's
777
1703
  // installed. JSCAD's intersection misreads faces that come near without touching: two gears 0.07 mm apart (their
778
1704
  // backlash) read as 2.7 mm³ into each other at one angle in twenty, and a planet 0.4 mm over a case as 1.3 mm³.
779
1705
  // Manifold is exact; a shape it can't read as a closed solid falls back to JSCAD's for that pair.
780
- let solid = null, tried = false;
1706
+ let solid = null,
1707
+ tried = false;
781
1708
  async function measurer() {
782
- if (tried) return; tried = true;
783
- try { solid = await booleans('manifold'); } catch { solid = null; } // (without manifold-3d, JSCAD's, as before)
1709
+ if (tried) return;
1710
+ tried = true;
1711
+ try {
1712
+ solid = await booleans('manifold');
1713
+ } catch {
1714
+ solid = null;
1715
+ } // (without manifold-3d, JSCAD's, as before)
784
1716
  }
785
1717
 
786
1718
  // Overlaps between placed parts, remembered across runs (.cache/overlaps.json): a part is its build (the build cache's
787
1719
  // hash: everything it's made from) and where it's placed, so after an edit only the pairs it touches are measured again
788
1720
  const OVERLAPS = paths.cache('overlaps.json');
789
- let remembered = null, fresh = 0;
1721
+ let remembered = null,
1722
+ fresh = 0;
790
1723
  function pairOverlap(pa, pb) {
791
1724
  const solidOf = (p) => p.collide ?? p.geometry; // (a beam by its envelope: lib/beams.mjs)
792
1725
  if (!pa.hash || !pb.hash) return overlap(solidOf(pa), solidOf(pb));
793
- remembered ||= (() => { try { return JSON.parse(host.readText(OVERLAPS)); } catch { return {}; } })();
794
- const at = (p) => `${p.hash}@${Array.from(p.m || []).map((x) => Math.round(x * 1e6) / 1e6).join(',')}`;
1726
+ remembered ||= (() => {
1727
+ try {
1728
+ return cached(OVERLAPS) ? JSON.parse(host.readText(OVERLAPS)) : {};
1729
+ } catch {
1730
+ return {};
1731
+ }
1732
+ })();
1733
+ const at = (p) =>
1734
+ `${p.hash}@${Array.from(p.m || [])
1735
+ .map((x) => Math.round(x * 1e6) / 1e6)
1736
+ .join(',')}`;
795
1737
  // (the words in front change whenever the measure does, so an answer remembered from before is measured again: flush
796
1738
  // overlaps, which fit once read as touching and were remembered as 0, came with #371)
797
- const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`flush+crossing+tracks+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
798
- if (!(k in remembered)) { remembered[k] = overlap(solidOf(pa), solidOf(pb)); fresh++; }
1739
+ const [x, y] = [at(pa), at(pb)].sort(),
1740
+ k = crypto
1741
+ .createHash('sha1')
1742
+ .update(`flush+crossing+tracks+${solid ? 'manifold' : 'jscad'}|${x}|${y}`)
1743
+ .digest('hex');
1744
+ if (!(k in remembered)) {
1745
+ remembered[k] = overlap(solidOf(pa), solidOf(pb));
1746
+ fresh++;
1747
+ }
799
1748
  return remembered[k];
800
1749
  }
801
1750
  function saveOverlaps() {
802
1751
  if (!fresh) return;
803
- try { host.writeText(OVERLAPS, JSON.stringify(remembered)); fresh = 0; } catch {} // only slower without it
1752
+ try {
1753
+ host.writeText(OVERLAPS, JSON.stringify(remembered));
1754
+ fresh = 0;
1755
+ } catch {
1756
+ // (a cache that can't be written is only slower)
1757
+ }
804
1758
  }
805
1759
 
806
1760
  // A screw and what it is threaded into (its part, its nut, its insert) share space by design: fasten's hardware says which
@@ -808,81 +1762,182 @@ const threaded = (a, b) => !!(a.allow?.includes(b.leaf) || b.allow?.includes(a.l
808
1762
 
809
1763
  // checkAssembly(built) -> findings, as @rulecad/printcheck: { level, text, card? } (card: a short line for the mirror)
810
1764
  // What a project prints in, for the motors' heat and press-fit checks
811
- const materialOf = (project) => { try { return readJson(path.join(paths.project(project), 'project.json')).material; } catch { return null; } };
1765
+ const materialOf = (project) => {
1766
+ try {
1767
+ return readJson(path.join(paths.project(project), 'project.json')).material;
1768
+ } catch {
1769
+ return null;
1770
+ }
1771
+ };
812
1772
 
813
1773
  // What's printed and how much it weighs, so "design small" is seen on every change
814
1774
  function massFinding(s, f) {
815
1775
  if (!s.parts.some((p) => p.role === 'reference') && !s.motion?.joints.length) return; // a machine, not a keyboard plate
816
- const parts = printedParts(s); if (!parts.length) return;
817
- const sorted = [...parts].sort((a, b) => b.grams - a.grams), total = sorted.reduce((t, p) => t + p.grams, 0);
818
- f('info', `${Number(total.toFixed(1))} g printed in ${sorted.length} parts; heaviest ${sorted.slice(0, 3).map((p) => `${p.id} ${p.grams} g`).join(', ')}`, null, { code: 'mass.parts', values: { grams: total, parts: Object.fromEntries(sorted.map((p) => [p.id, p.grams])) } });
1776
+ const parts = printedParts(s);
1777
+ if (!parts.length) return;
1778
+ const sorted = [...parts].sort((a, b) => b.grams - a.grams),
1779
+ total = sorted.reduce((t, p) => t + p.grams, 0);
1780
+ f(
1781
+ 'info',
1782
+ `${Number(total.toFixed(1))} g printed in ${sorted.length} parts; heaviest ${sorted
1783
+ .slice(0, 3)
1784
+ .map((p) => `${p.id} ${p.grams} g`)
1785
+ .join(', ')}`,
1786
+ null,
1787
+ { code: 'mass.parts', values: { grams: total, parts: Object.fromEntries(sorted.map((p) => [p.id, p.grams])) } },
1788
+ );
819
1789
  }
820
1790
 
821
1791
  export function checkAssembly(s) {
822
1792
  // the screws found in this pose (at(pose) leaves them to be found again): the fasten and slot nut checks read the same
823
- if (!s.fastened && s.a.fasten?.length && fastening) s = { ...s, fastened: fastening.fastenOf(s, placeItems(s.motion, s.jointValues)) };
824
- const out = [], f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }), mm = (n) => `${Number(n.toFixed(3))}`;
1793
+ if (!s.fastened && s.a.fasten?.length && fastening)
1794
+ s = { ...s, fastened: fastening.fastenOf(s, placeItems(s.motion, s.jointValues)) };
1795
+ const out = [],
1796
+ f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }),
1797
+ mm = (n) => `${Number(n.toFixed(3))}`;
825
1798
  // Versions: every pin, from this assembly and its components, against every copy of that object
826
1799
  const pins = new Map();
827
1800
  for (const r of s.requires) pins.set(`${r.object} ${r.range}`, r);
828
1801
  for (const { object, range } of pins.values()) {
829
1802
  const copies = s.objects.filter((o) => o.objName === object);
830
- if (!copies.length) { f('fail', `requires ${object} ${range}, but nothing uses it`, null, { code: 'requires.unused', refs: { object, range } }); continue; }
1803
+ if (!copies.length) {
1804
+ f('fail', `requires ${object} ${range}, but nothing uses it`, null, {
1805
+ code: 'requires.unused',
1806
+ refs: { object, range },
1807
+ });
1808
+ continue;
1809
+ }
831
1810
  const bad = copies.filter((o) => !satisfies(o.version, range));
832
- f(bad.length ? 'fail' : 'pass', bad.length ? `${object} ${bad[0].version} doesn't meet ${range} (${bad.map((o) => o.id).join(', ')})`
833
- : `${object} ${copies[0].version} meets ${range}${copies.length > 1 ? ` (${copies.length} copies)` : ''}`, null, { code: 'requires.version', refs: { object, range, items: bad.map((o) => o.id) } });
1811
+ f(
1812
+ bad.length ? 'fail' : 'pass',
1813
+ bad.length
1814
+ ? `${object} ${bad[0].version} doesn't meet ${range} (${bad.map((o) => o.id).join(', ')})`
1815
+ : `${object} ${copies[0].version} meets ${range}${copies.length > 1 ? ` (${copies.length} copies)` : ''}`,
1816
+ null,
1817
+ { code: 'requires.version', refs: { object, range, items: bad.map((o) => o.id) } },
1818
+ );
834
1819
  }
835
1820
  // Overlaps between object instances, inside components too. Bounding boxes first: most pairs can't touch.
836
1821
  const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`);
837
- const allowed = (a, b) => threaded(a, b) || s.fits.some((x) => x.min != null && x.num(x.min) < 0 && ((named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a))));
838
- const box = new Map(), bx = (p) => box.get(p) || (box.set(p, bounds(p.triangles)), box.get(p));
839
- const touch = (a, b) => [0, 1, 2].every((k) => bx(a).lo[k] <= bx(b).hi[k] + 1e-6 && bx(b).lo[k] <= bx(a).hi[k] + 1e-6);
1822
+ const allowed = (a, b) =>
1823
+ threaded(a, b) ||
1824
+ s.fits.some(
1825
+ (x) =>
1826
+ x.min != null && x.num(x.min) < 0 && ((named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a))),
1827
+ );
1828
+ const box = new Map(),
1829
+ bx = (p) => box.get(p) || (box.set(p, bounds(p.triangles)), box.get(p));
1830
+ const touch = (a, b) =>
1831
+ [0, 1, 2].every((k) => bx(a).lo[k] <= bx(b).hi[k] + 1e-6 && bx(b).lo[k] <= bx(a).hi[k] + 1e-6);
840
1832
  const clashes = [];
841
- for (let i = 0; i < s.parts.length; i++) for (let j = i + 1; j < s.parts.length; j++) {
842
- const pa = s.parts[i], pb = s.parts[j];
843
- if (pa.leaf === pb.leaf || !touch(pa, pb) || allowed(pa, pb)) continue;
844
- const v = pairOverlap(pa, pb);
845
- if (v > 0.01) clashes.push({ text: `${pa.name} and ${pb.name} overlap by ${mm(v)} mm³`, a: pa.name, b: pb.name, volume: v });
846
- }
847
- if (clashes.length) f('fail', clashes.slice(0, 5).map((c) => c.text).join('; ') + (clashes.length > 5 ? `; and ${clashes.length - 5} more` : ''), `${clashes.length} overlaps`,
848
- { code: 'overlap', values: { count: clashes.length }, refs: { overlaps: clashes.map(({ a, b, volume }) => ({ a, b, volume })) } });
849
- else f('pass', `no parts overlap (${new Set(s.parts.map((p) => p.leaf)).size} object instances)`, 'No parts overlap', { code: 'overlap', values: { count: 0 } });
1833
+ for (let i = 0; i < s.parts.length; i++)
1834
+ for (let j = i + 1; j < s.parts.length; j++) {
1835
+ const pa = s.parts[i],
1836
+ pb = s.parts[j];
1837
+ if (pa.leaf === pb.leaf || !touch(pa, pb) || allowed(pa, pb)) continue;
1838
+ const v = pairOverlap(pa, pb);
1839
+ if (v > 0.01)
1840
+ clashes.push({ text: `${pa.name} and ${pb.name} overlap by ${mm(v)} mm³`, a: pa.name, b: pb.name, volume: v });
1841
+ }
1842
+ if (clashes.length)
1843
+ f(
1844
+ 'fail',
1845
+ clashes
1846
+ .slice(0, 5)
1847
+ .map((c) => c.text)
1848
+ .join('; ') + (clashes.length > 5 ? `; and ${clashes.length - 5} more` : ''),
1849
+ `${clashes.length} overlaps`,
1850
+ {
1851
+ code: 'overlap',
1852
+ values: { count: clashes.length },
1853
+ refs: { overlaps: clashes.map(({ a, b, volume }) => ({ a, b, volume })) },
1854
+ },
1855
+ );
1856
+ else
1857
+ f('pass', `no parts overlap (${new Set(s.parts.map((p) => p.leaf)).size} object instances)`, 'No parts overlap', {
1858
+ code: 'overlap',
1859
+ values: { count: 0 },
1860
+ });
850
1861
  // Fits: the closest gap between two named things, against a range. Copies of one fit are reported together, worst first.
851
1862
  // A fit names parts (keyboard, key-0-0.cap), or the faces of an item near one of its anchors (keyboard@pivot, within
852
1863
  // "within" mm, 10 by default): the pocket round a pivot, not the whole case
853
- const marks = anchorsAt(s), within = (x) => (x.within != null ? x.num(x.within) : 10);
1864
+ const marks = anchorsAt(s),
1865
+ within = (x) => (x.within != null ? x.num(x.within) : 10);
854
1866
  // A beam's address in a fit (x1.top@120): the faces near that point, as near an anchor
855
- const addressMark = (n) => { const r = addressAt(s, n); return r && { id: n, item: r.id, at: r.at }; };
1867
+ const addressMark = (n) => {
1868
+ const r = addressAt(s, n);
1869
+ return r && { id: n, item: r.id, at: r.at };
1870
+ };
856
1871
  const near = (p, mark, r) => ({ ...p, polygons: p.polygons.filter((f) => distanceToFace(mark.at, f) <= r) });
857
1872
  const pickIn = (n, x) => {
858
1873
  if (Array.isArray(n)) return n.flatMap((m) => pickIn(m, x));
859
- if (!n.includes('@')) { const ps = s.parts.filter((p) => named(p, n)); if (ps.length) return ps; } // (else a beam's end or face: x1.a, x1.top)
1874
+ if (!n.includes('@')) {
1875
+ const ps = s.parts.filter((p) => named(p, n));
1876
+ if (ps.length) return ps;
1877
+ } // (else a beam's end or face: x1.a, x1.top)
860
1878
  const mark = marks.find((m) => m.id === n) ?? addressMark(n);
861
1879
  if (!mark) return [];
862
- return s.parts.filter((p) => named(p, mark.item)).map((p) => near(p, mark, within(x))).filter((p) => p.polygons.length);
1880
+ return s.parts
1881
+ .filter((p) => named(p, mark.item))
1882
+ .map((p) => near(p, mark, within(x)))
1883
+ .filter((p) => p.polygons.length);
863
1884
  };
864
1885
  const pick = (n) => pickIn(n, {});
865
1886
  const groups = new Map();
866
1887
  for (const x of s.fits) {
867
1888
  if (x.poses && !x.poses.includes(s.pose)) continue; // a fit for some poses only: the folded screen over the keys
868
- if (x.holes) { holesFit(x); continue; }
1889
+ if (x.holes) {
1890
+ holesFit(x);
1891
+ continue;
1892
+ }
869
1893
  if (x.silent) continue; // lets a pair overlap, and has nothing to report
870
- if (x.engage != null) { engageFit(x); continue; }
871
- if (x.seat != null) { seatFit(x, s, f, { placeItems, jointValues, mul, seatSize }); continue; }
1894
+ if (x.engage != null) {
1895
+ engageFit(x);
1896
+ continue;
1897
+ }
1898
+ if (x.seat != null) {
1899
+ seatFit(x, s, f, { placeItems, jointValues, seatSize });
1900
+ continue;
1901
+ }
872
1902
  if (x.pin && pinning) pinFit(x); // (and its gap, as any fit's)
873
1903
  if (x.magnet && pinning) magnetFit(x);
874
- if (x.shaft != null) { shaftFit(x, s, f, { placeItems, jointValues, mul, materialName: materialOf(s.project), holeComp: printerRules(s).hole_comp ?? 0.1 }); continue; }
875
- const A = pickIn(x.a, x), key = x.note || `${x.a} / ${x.b}`;
876
- const lo = x.min != null ? x.num(x.min) : -Infinity, hi = x.max != null ? x.num(x.max) : Infinity;
1904
+ if (x.shaft != null) {
1905
+ shaftFit(x, s, f, {
1906
+ placeItems,
1907
+ jointValues,
1908
+ materialName: materialOf(s.project),
1909
+ holeComp: printerRules(s).hole_comp ?? 0.1,
1910
+ });
1911
+ continue;
1912
+ }
1913
+ const A = pickIn(x.a, x),
1914
+ key = x.note || `${x.a} / ${x.b}`;
1915
+ const lo = x.min != null ? x.num(x.min) : -Infinity,
1916
+ hi = x.max != null ? x.num(x.max) : Infinity;
877
1917
  const reach = Math.max(2, ...[lo, hi].filter(Number.isFinite)) + 1; // look past the range, so a gap near it is measured
878
1918
  let B = pickIn(x.b, x);
879
- if (Array.isArray(x.b) && A.length) { // against many others: only those within reach
880
- const lo3 = [0, 1, 2].map((k) => Math.min(...A.map((p) => bx(p).lo[k]))), hi3 = [0, 1, 2].map((k) => Math.max(...A.map((p) => bx(p).hi[k])));
1919
+ if (Array.isArray(x.b) && A.length) {
1920
+ // against many others: only those within reach
1921
+ const lo3 = [0, 1, 2].map((k) => Math.min(...A.map((p) => bx(p).lo[k]))),
1922
+ hi3 = [0, 1, 2].map((k) => Math.max(...A.map((p) => bx(p).hi[k])));
881
1923
  B = B.filter((p) => [0, 1, 2].every((k) => bx(p).lo[k] <= hi3[k] + reach && lo3[k] <= bx(p).hi[k] + reach));
882
1924
  }
883
- if (!A.length || (!B.length && !Array.isArray(x.b))) { f('fail', `fit ${x.a} / ${x.b}: no such ${A.length ? x.b : x.a}`, null, { code: 'fit.missing', refs: { a: x.a, b: x.b, missing: A.length ? x.b : x.a } }); continue; }
1925
+ if (!A.length || (!B.length && !Array.isArray(x.b))) {
1926
+ f('fail', `fit ${x.a} / ${x.b}: no such ${A.length ? x.b : x.a}`, null, {
1927
+ code: 'fit.missing',
1928
+ refs: { a: x.a, b: x.b, missing: A.length ? x.b : x.a },
1929
+ });
1930
+ continue;
1931
+ }
884
1932
  const vol = A.reduce((t, pa) => t + B.reduce((u, pb) => u + (touch(pa, pb) ? pairOverlap(pa, pb) : 0), 0), 0);
885
- const near = !B.length || vol > 0.01 ? null : closestAt(A.flatMap((p) => p.polygons), B.flatMap((p) => p.polygons), reach);
1933
+ const near =
1934
+ !B.length || vol > 0.01
1935
+ ? null
1936
+ : closestAt(
1937
+ A.flatMap((p) => p.polygons),
1938
+ B.flatMap((p) => p.polygons),
1939
+ reach,
1940
+ );
886
1941
  const gap = !B.length ? Infinity : vol > 0.01 ? -vol : near.gap; // negative: overlap, mm³
887
1942
  const ok = vol > 0.01 ? lo < 0 : gap >= lo && gap <= hi;
888
1943
  if (!groups.has(key)) groups.set(key, { x, lo, hi, results: [] });
@@ -891,124 +1946,356 @@ export function checkAssembly(s) {
891
1946
  // The anchor nearest a point, if one is within 20 mm: where to look
892
1947
  const nearest = (pt) => {
893
1948
  if (!pt || !marks.length) return {};
894
- const m = marks.map((k) => ({ k, d: Math.hypot(k.at[0] - pt[0], k.at[1] - pt[1], k.at[2] - pt[2]) })).sort((a, b) => a.d - b.d)[0];
1949
+ const m = marks
1950
+ .map((k) => ({ k, d: Math.hypot(k.at[0] - pt[0], k.at[1] - pt[1], k.at[2] - pt[2]) }))
1951
+ .sort((a, b) => a.d - b.d)[0];
895
1952
  return m.d <= 20 ? { near: m.k.id, distance: Number(m.d.toFixed(2)) } : {};
896
1953
  };
897
1954
  for (const [key, { x, lo, hi, results }] of groups) {
898
1955
  const worst = results.reduce((w, r) => (!r.ok && w.ok ? r : r.ok === w.ok && r.gap < w.gap ? r : w), results[0]);
899
- const say = (g) => (g < 0 ? `press fit, ${mm(-g)} mm³ overlap` : g === Infinity ? 'not near each other' : `closest gap ${mm(g)} mm`);
1956
+ const say = (g) =>
1957
+ g < 0 ? `press fit, ${mm(-g)} mm³ overlap` : g === Infinity ? 'not near each other' : `closest gap ${mm(g)} mm`;
900
1958
  const n = results.length > 1 ? ` (${results.filter((r) => r.ok).length} of ${results.length} in range)` : '';
901
1959
  const label = (x.label || x.a).replace(/ \(.*\)$/, '');
902
1960
  const where = nearest(worst.at);
903
- f(worst.ok ? 'pass' : 'warn', `${key}: ${say(worst.gap)}${n}${worst.ok ? '' : `, wanted ${lo === -Infinity ? '' : `${mm(lo)} `}to ${hi === Infinity ? 'any' : mm(hi)} mm (${results.filter((r) => !r.ok).map((r) => r.id).join(', ')})${where.near ? `, ${where.distance} mm from ${where.near}` : ''}`}`,
1961
+ f(
1962
+ worst.ok ? 'pass' : 'warn',
1963
+ `${key}: ${say(worst.gap)}${n}${
1964
+ worst.ok
1965
+ ? ''
1966
+ : `, wanted ${lo === -Infinity ? '' : `${mm(lo)} `}to ${hi === Infinity ? 'any' : mm(hi)} mm (${results
1967
+ .filter((r) => !r.ok)
1968
+ .map((r) => r.id)
1969
+ .join(', ')})${where.near ? `, ${where.distance} mm from ${where.near}` : ''}`
1970
+ }`,
904
1971
  `${label}: ${worst.gap < 0 ? `press fit ${mm(-worst.gap)} mm³` : worst.gap === Infinity ? 'apart' : `gap ${Number(worst.gap.toFixed(2))} mm`}${worst.ok ? '' : ' (out of range)'}`,
905
- { code: 'fit', values: { ...(worst.gap < 0 ? { overlap: -worst.gap } : { gap: worst.gap }), min: lo, max: hi, inRange: results.filter((r) => r.ok).length, copies: results.length },
906
- refs: { a: x.a, b: x.b, label: x.label, ...(s.pose ? { pose: s.pose } : {}), outOfRange: results.filter((r) => !r.ok).map((r) => r.id), ...where }, ...(worst.at ? { at: { lo: worst.at, hi: worst.at } } : {}) });
1972
+ {
1973
+ code: 'fit',
1974
+ values: {
1975
+ ...(worst.gap < 0 ? { overlap: -worst.gap } : { gap: worst.gap }),
1976
+ min: lo,
1977
+ max: hi,
1978
+ inRange: results.filter((r) => r.ok).length,
1979
+ copies: results.length,
1980
+ },
1981
+ refs: {
1982
+ a: x.a,
1983
+ b: x.b,
1984
+ label: x.label,
1985
+ ...(s.pose ? { pose: s.pose } : {}),
1986
+ outOfRange: results.filter((r) => !r.ok).map((r) => r.id),
1987
+ ...where,
1988
+ },
1989
+ ...(worst.at ? { at: { lo: worst.at, hi: worst.at } } : {}),
1990
+ },
1991
+ );
907
1992
  }
908
1993
  // Engage fits: a part slid onto a shaft, a pin or a peg goes onto it, not just against its end. Along the axis of the
909
1994
  // joint between them, each part's material near the axis (within radius, 10 mm) spans a stretch; how far the two
910
1995
  // stretches overlap is how far one is on the other. An arm resting on a shaft's end touches it face to face, as a
911
1996
  // seated one does, and nothing overlaps either way: only this tells them apart.
912
1997
  function engageFit(x) {
913
- const top = (n) => String(n).split(/[.@]/)[0], ids = s.motion?.items.map((i) => i[0]) || [], a = top(x.a), b = top(x.b), label = x.note || `${x.a} onto ${x.b}`;
914
- const j = (s.motion?.joints || []).find((jt) => { const pair = [ids[jt.child], jt.parent < 0 ? null : ids[jt.parent]]; return pair.includes(a) && pair.includes(b); });
915
- if (!j) return f('fail', `${label}: no joint between ${a} and ${b} to measure along (engage measures along the joint that holds one on the other)`, null, { code: 'fit.engage', refs: { a: x.a, b: x.b } });
916
- const worlds = placeItems(s.motion, s.jointValues), P = mul(j.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[j.parent], j.a);
917
- const O = [P[3], P[7], P[11]], Z = [P[2], P[6], P[10]], r = x.radius != null ? x.num(x.radius) : 10, need = x.num(x.engage);
1998
+ const top = (n) => String(n).split(/[.@]/)[0],
1999
+ ids = s.motion?.items.map((i) => i[0]) || [],
2000
+ a = top(x.a),
2001
+ b = top(x.b),
2002
+ label = x.note || `${x.a} onto ${x.b}`;
2003
+ const j = (s.motion?.joints || []).find((jt) => {
2004
+ const pair = [ids[jt.child], jt.parent < 0 ? null : ids[jt.parent]];
2005
+ return pair.includes(a) && pair.includes(b);
2006
+ });
2007
+ if (!j)
2008
+ return f(
2009
+ 'fail',
2010
+ `${label}: no joint between ${a} and ${b} to measure along (engage measures along the joint that holds one on the other)`,
2011
+ null,
2012
+ { code: 'fit.engage', refs: { a: x.a, b: x.b } },
2013
+ );
2014
+ const worlds = placeItems(s.motion, s.jointValues),
2015
+ P = mul(j.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[j.parent], j.a);
2016
+ const O = [P[3], P[7], P[11]],
2017
+ Z = [P[2], P[6], P[10]],
2018
+ r = x.radius != null ? x.num(x.radius) : 10,
2019
+ need = x.num(x.engage);
918
2020
  const span = (parts) => {
919
- let lo = Infinity, hi = -Infinity;
920
- for (const p of parts) for (const t of p.triangles) for (const v of t) {
921
- const d = [v[0] - O[0], v[1] - O[1], v[2] - O[2]], along = d[0] * Z[0] + d[1] * Z[1] + d[2] * Z[2];
922
- if (Math.hypot(d[0] - along * Z[0], d[1] - along * Z[1], d[2] - along * Z[2]) <= r) { lo = Math.min(lo, along); hi = Math.max(hi, along); }
923
- }
2021
+ let lo = Infinity,
2022
+ hi = -Infinity;
2023
+ for (const p of parts)
2024
+ for (const t of p.triangles)
2025
+ for (const v of t) {
2026
+ const d = [v[0] - O[0], v[1] - O[1], v[2] - O[2]],
2027
+ along = d[0] * Z[0] + d[1] * Z[1] + d[2] * Z[2];
2028
+ if (Math.hypot(d[0] - along * Z[0], d[1] - along * Z[1], d[2] - along * Z[2]) <= r) {
2029
+ lo = Math.min(lo, along);
2030
+ hi = Math.max(hi, along);
2031
+ }
2032
+ }
924
2033
  return [lo, hi];
925
2034
  };
926
- const [la, ha] = span(pickIn(x.a, x)), [lb, hb] = span(pickIn(x.b, x)), on = Math.max(0, Math.min(ha, hb) - Math.max(la, lb));
2035
+ const [la, ha] = span(pickIn(x.a, x)),
2036
+ [lb, hb] = span(pickIn(x.b, x)),
2037
+ on = Math.max(0, Math.min(ha, hb) - Math.max(la, lb));
927
2038
  const ok = on >= need - 1e-3; // (flush is on: a hair under, in the floating point, is not short)
928
- f(ok ? 'pass' : 'fail', `${label}: ${on > 1e-3 ? `${mm(on)} mm on` : `not on at all (${Math.max(la, lb) - Math.min(ha, hb) < 1e-3 ? 'end to end' : 'apart'})`} along their joint${ok ? '' : `, where it should go ${mm(need)} mm on: its anchor is on the wrong face, or the shaft too short`}`, ok ? null : `${a}: not on ${b}`, { code: 'fit.engage', values: { engaged: on, need }, refs: { a: x.a, b: x.b, joint: j.id } });
2039
+ f(
2040
+ ok ? 'pass' : 'fail',
2041
+ `${label}: ${on > 1e-3 ? `${mm(on)} mm on` : `not on at all (${Math.max(la, lb) - Math.min(ha, hb) < 1e-3 ? 'end to end' : 'apart'})`} along their joint${ok ? '' : `, where it should go ${mm(need)} mm on: its anchor is on the wrong face, or the shaft too short`}`,
2042
+ ok ? null : `${a}: not on ${b}`,
2043
+ { code: 'fit.engage', values: { engaged: on, need }, refs: { a: x.a, b: x.b, joint: j.id } },
2044
+ );
2045
+ }
2046
+
2047
+ // A mesh's faces: the centre distance is said across the axes, so a gear anchored at the wrong height (the wrong face,
2048
+ // a missing spacer, the wrong step of a compound gear) would mesh with nothing and still pass (meshFaces, below).
2049
+ // Spur, internal and rack meshes; worms, bevels and planetaries are placed by their own checks.
2050
+ function faceOverlap(g) {
2051
+ const ids = s.motion.items.map((i) => i[0]),
2052
+ worlds = placeItems(s.motion, s.jointValues);
2053
+ const gear = (x) => {
2054
+ const W = worlds[x.item];
2055
+ return {
2056
+ ...x,
2057
+ triangles: s.parts.filter((p) => named(p, ids[x.item])).flatMap((p) => p.triangles),
2058
+ frame: { O: [W[3], W[7], W[11]], X: [W[0], W[4], W[8]], Y: [W[1], W[5], W[9]], Z: [W[2], W[6], W[10]] },
2059
+ };
2060
+ };
2061
+ const A = gear(g.faces.a),
2062
+ r = meshFaces({ module: g.faces.module, a: A, b: gear(g.faces.b), along: A.frame }),
2063
+ [a, b] = [g.faces.a, g.faces.b].map((x) => ids[x.item]),
2064
+ label = g.with === a && g.joint === b ? `${a} and ${b}` : `${g.with} and ${g.joint} (${a} and ${b})`,
2065
+ extra = {
2066
+ code: 'mesh.face',
2067
+ at: g.between[0],
2068
+ between: g.between,
2069
+ refs: { joints: [g.with, g.joint], items: [a, b] },
2070
+ };
2071
+ if (!r.a || !r.b) {
2072
+ const lost = r.a ? b : a;
2073
+ return f(
2074
+ 'warn',
2075
+ `${label}: no teeth found on ${lost}'s ${g.faces.b.tipLine != null && lost === b ? 'tip line' : 'tip circle'} as the mesh describes it, so how far the faces overlap is unchecked: draw it with the module, teeth and shift its mesh gives`,
2076
+ `${g.joint}: face`,
2077
+ extra,
2078
+ );
2079
+ }
2080
+ f(
2081
+ r.level,
2082
+ `${label}: faces overlap ${mm(r.overlap)} of ${mm(r.narrower)} mm${r.level === 'pass' ? '' : ` (${Math.round(r.share * 100)} % of the narrower face; ${a}'s teeth from ${mm(r.a[0])} to ${mm(r.a[1])} mm along ${g.with}'s axis, ${b}'s from ${mm(r.b[0])} to ${mm(r.b[1])}): ${r.level === 'fail' ? 'too little of the teeth meet to drive' : 'the shared part of the faces carries all the load'}, so move one along its axis (its anchor's height, a spacer) until the faces line up`}`,
2083
+ r.level === 'pass' ? null : `${g.joint}: face`,
2084
+ { ...extra, values: { overlap: r.overlap, narrower: r.narrower } },
2085
+ );
929
2086
  }
930
2087
 
931
2088
  // Pin fits: the pins a fit names, their holes found in the parts and held to the pins' models (lib/pins.mjs)
932
- function pinFit(x) { try { pinning.pinFit(x, s, f); } catch (e) { f('fail', `${x.note || `${x.a} to ${x.b}`}: ${e.message}`, null, { code: 'fit.pin', refs: { a: x.a, b: x.b, pin: x.fastener } }); } }
2089
+ function pinFit(x) {
2090
+ try {
2091
+ pinning.pinFit(x, s, f);
2092
+ } catch (e) {
2093
+ f('fail', `${x.note || `${x.a} to ${x.b}`}: ${e.message}`, null, {
2094
+ code: 'fit.pin',
2095
+ refs: { a: x.a, b: x.b, pin: x.fastener },
2096
+ });
2097
+ }
2098
+ }
933
2099
  // Magnet fits: the magnets a fit names, their pockets found in the parts and held to the magnet's seat (lib/magnets.mjs)
934
- function magnetFit(x) { try { pinning.magnetFit(x, s, f); } catch (e) { f('fail', `${x.note || `${x.a} to ${x.b}`}: ${e.message}`, null, { code: 'fit.magnet', refs: { a: x.a, b: x.b, magnet: x.fastener } }); } }
2100
+ function magnetFit(x) {
2101
+ try {
2102
+ pinning.magnetFit(x, s, f);
2103
+ } catch (e) {
2104
+ f('fail', `${x.note || `${x.a} to ${x.b}`}: ${e.message}`, null, {
2105
+ code: 'fit.magnet',
2106
+ refs: { a: x.a, b: x.b, magnet: x.fastener },
2107
+ });
2108
+ }
2109
+ }
935
2110
  // Holes fits: each mounting hole's screw path, clear into a hole, with material round it
936
2111
  function holesFit(x) {
937
- const A = pick(x.a), B = pick(x.b), label = x.label || `${x.a} into ${x.b}`;
2112
+ const A = pick(x.a),
2113
+ B = pick(x.b),
2114
+ label = x.label || `${x.a} into ${x.b}`;
938
2115
  const board = A.length && s.objects.find((o) => o.id === A[0].leaf)?.built;
939
- if (!board?.circuit) return f('fail', `${label}: ${x.a} isn't a circuit board, so it has no mounting holes to follow`);
2116
+ if (!board?.circuit)
2117
+ return f('fail', `${label}: ${x.a} isn't a circuit board, so it has no mounting holes to follow`);
940
2118
  if (!B.length) return f('fail', `${label}: no such ${x.b}`);
941
2119
  const holes = board.circuit.filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id);
942
2120
  if (!holes.length) return f('fail', `${label}: ${x.a} has no mounting holes`);
943
- const depth = x.num(x.depth), down = x.direction === 'up' ? 1 : -1, faces = B.flatMap((p) => p.triangles);
944
- const base = down < 0 ? 0 : board.values.thickness ?? 0, at = (h, dx, dy, t) => jscad.maths.vec3.transform([0, 0, 0], [h.x + dx, h.y + dy, base + down * t], A[0].m);
945
- const steps = 8, misses = [];
2121
+ const depth = x.num(x.depth),
2122
+ down = x.direction === 'up' ? 1 : -1,
2123
+ faces = B.flatMap((p) => p.triangles);
2124
+ const base = down < 0 ? 0 : (board.values.thickness ?? 0),
2125
+ at = (h, dx, dy, t) => jscad.maths.vec3.transform([0, 0, 0], [h.x + dx, h.y + dy, base + down * t], A[0].m);
2126
+ const steps = 8,
2127
+ misses = [];
946
2128
  for (const h of holes) {
947
- const ring = x.ring != null ? x.num(x.ring) : h.hole_diameter, where = `hole at ${mm(h.x)}, ${mm(h.y)} mm`;
948
- const blocked = Array.from({ length: steps }, (_, i) => (depth * (i + 0.5)) / steps).find((t) => inside(at(h, 0, 0, t), faces));
949
- if (blocked != null) { misses.push(`${where}: solid ${mm(blocked)} mm along the screw's path`); continue; }
950
- const round = Array.from({ length: steps }, (_, i) => (2 * Math.PI * i) / steps).filter((a) => !inside(at(h, ring * Math.cos(a), ring * Math.sin(a), depth / 2), faces));
951
- if (round.length) misses.push(`${where}: no material ${mm(ring)} mm from the screw on ${round.length} of ${steps} sides`);
2129
+ const ring = x.ring != null ? x.num(x.ring) : h.hole_diameter,
2130
+ where = `hole at ${mm(h.x)}, ${mm(h.y)} mm`;
2131
+ const blocked = Array.from({ length: steps }, (_, i) => (depth * (i + 0.5)) / steps).find((t) =>
2132
+ inside(at(h, 0, 0, t), faces),
2133
+ );
2134
+ if (blocked != null) {
2135
+ misses.push(`${where}: solid ${mm(blocked)} mm along the screw's path`);
2136
+ continue;
2137
+ }
2138
+ const round = Array.from({ length: steps }, (_, i) => (2 * Math.PI * i) / steps).filter(
2139
+ (a) => !inside(at(h, ring * Math.cos(a), ring * Math.sin(a), depth / 2), faces),
2140
+ );
2141
+ if (round.length)
2142
+ misses.push(`${where}: no material ${mm(ring)} mm from the screw on ${round.length} of ${steps} sides`);
952
2143
  }
953
- f(misses.length ? 'fail' : 'pass', misses.length ? `${label}: ${misses.join('; ')}` : `${label}: ${holes.length} of ${holes.length} holes clear for ${mm(depth)} mm, with material around each`,
2144
+ f(
2145
+ misses.length ? 'fail' : 'pass',
2146
+ misses.length
2147
+ ? `${label}: ${misses.join('; ')}`
2148
+ : `${label}: ${holes.length} of ${holes.length} holes clear for ${mm(depth)} mm, with material around each`,
954
2149
  `${label}: ${misses.length ? `${misses.length} of ${holes.length} miss` : `${holes.length} of ${holes.length} line up`}`,
955
- { code: 'fit.holes', values: { holes: holes.length, missed: misses.length }, refs: { a: x.a, b: x.b, misses } });
2150
+ { code: 'fit.holes', values: { holes: holes.length, missed: misses.length }, refs: { a: x.a, b: x.b, misses } },
2151
+ );
956
2152
  }
957
2153
  // Joints: every value in its range (a ball's tip within its cone), and every loop closed
958
2154
  if (s.motion?.joints.length) {
959
2155
  const outside = [];
960
2156
  for (const j of s.motion.joints) {
961
2157
  const v = s.jointValues[j.id];
962
- j.dofs.forEach(([lo, hi], i) => { if (v[i] < lo - 1e-9 || v[i] > hi + 1e-9) outside.push(`${j.id} ${mm(v[i])} (${mm(lo)} to ${mm(hi)})`); });
963
- if (j.cone != null) { const tip = Math.acos(Math.min(1, jointMatrix(j, v)[10])) / (Math.PI / 180); if (tip > j.cone + 1e-9) outside.push(`${j.id} tips ${mm(tip)}° (cone ${mm(j.cone)}°)`); }
2158
+ j.dofs.forEach(([lo, hi], i) => {
2159
+ if (v[i] < lo - 1e-9 || v[i] > hi + 1e-9) outside.push(`${j.id} ${mm(v[i])} (${mm(lo)} to ${mm(hi)})`);
2160
+ });
2161
+ if (j.cone != null) {
2162
+ const tip = Math.acos(Math.min(1, jointMatrix(j, v)[10])) / (Math.PI / 180);
2163
+ if (tip > j.cone + 1e-9) outside.push(`${j.id} tips ${mm(tip)}° (cone ${mm(j.cone)}°)`);
2164
+ }
964
2165
  }
965
- if (outside.length) f('fail', `joints out of range: ${outside.join(', ')}`, `${outside.length} joints out of range`, { code: 'joint.range', refs: { joints: outside } });
966
- for (const l of loopGaps(s)) f(l.ok ? 'pass' : 'fail', `${l.label}: ${l.ok ? 'closed' : 'apart'} (${mm(l.gap)} mm, axes ${mm(l.angle)}° apart)`, `${l.label}: ${l.ok ? 'closed' : 'apart'}`, { code: 'loop', values: { gap: l.gap, angle: l.angle }, refs: { label: l.label } });
2166
+ if (outside.length)
2167
+ f('fail', `joints out of range: ${outside.join(', ')}`, `${outside.length} joints out of range`, {
2168
+ code: 'joint.range',
2169
+ refs: { joints: outside },
2170
+ });
2171
+ for (const l of loopGaps(s))
2172
+ f(
2173
+ l.ok ? 'pass' : 'fail',
2174
+ `${l.label}: ${l.ok ? 'closed' : 'apart'} (${mm(l.gap)} mm, axes ${mm(l.angle)}° apart)`,
2175
+ `${l.label}: ${l.ok ? 'closed' : 'apart'}`,
2176
+ { code: 'loop', values: { gap: l.gap, angle: l.angle }, refs: { label: l.label } },
2177
+ );
967
2178
  // Held by something: in a mechanism, every part but the first either turns or slides on a joint, or is fastened,
968
2179
  // through a chain of fits with "fastens", to the first. A part only placed somewhere stays there in the model and
969
2180
  // nowhere else: a ring gear resting on its case turns with the planets; a pawl resting on its post walks off it.
970
2181
  if (s.motion.joints.some((j) => j.type !== 'fixed')) {
971
- const ids = s.motion.items.map((x) => x[0]), top = (n) => String(n).split(/[.@]/)[0];
2182
+ const ids = s.motion.items.map((x) => x[0]),
2183
+ top = (n) => String(n).split(/[.@]/)[0];
972
2184
  // (a beam placed by its ends is the frame, held where it is drawn: what is screwed to it is held by it)
973
- const held = new Set([ids[0], ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]), ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id)]), links = s.fits.filter((x) => x.fastens).map((x) => [top(x.a), top(x.b)]);
2185
+ const held = new Set([
2186
+ ids[0],
2187
+ ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]),
2188
+ ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id),
2189
+ ]),
2190
+ links = s.fits.filter((x) => x.fastens).map((x) => [top(x.a), top(x.b)]);
974
2191
  // (a fitting at a beam's end, an end cap pressed into it or a foot screwed into its bore, is held by that beam)
975
- for (const it of s.a.items || []) { const m = typeof it.at === 'string' && (it.fitting || it.bought) ? /^([\w-]+)\.[ab]$/.exec(it.at.trim()) : null; if (m && s.items.some((x) => x.id === m[1] && x.beam)) links.push([it.id, m[1]]); }
976
- for (let grew = true; grew;) { grew = false; for (const [a, b] of links) { if (held.has(a) && !held.has(b)) { held.add(b); grew = true; } if (held.has(b) && !held.has(a)) { held.add(a); grew = true; } } }
2192
+ for (const it of s.a.items || []) {
2193
+ const m = typeof it.at === 'string' && (it.fitting || it.bought) ? /^([\w-]+)\.[ab]$/.exec(it.at.trim()) : null;
2194
+ if (m && s.items.some((x) => x.id === m[1] && x.beam)) links.push([it.id, m[1]]);
2195
+ }
2196
+ for (let grew = true; grew;) {
2197
+ grew = false;
2198
+ for (const [a, b] of links) {
2199
+ if (held.has(a) && !held.has(b)) {
2200
+ held.add(b);
2201
+ grew = true;
2202
+ }
2203
+ if (held.has(b) && !held.has(a)) {
2204
+ held.add(a);
2205
+ grew = true;
2206
+ }
2207
+ }
2208
+ }
977
2209
  const placed = new Set(s.objects.filter((o) => !o.unplaced && o.role !== 'reference').map((o) => top(o.id)));
978
2210
  const loose = ids.filter((id) => !held.has(id) && placed.has(id));
979
- if (loose.length) f('warn', `${loose.join(', ')} ${loose.length > 1 ? 'are' : 'is'} placed, but nothing holds ${loose.length > 1 ? 'them' : 'it'}: give ${loose.length > 1 ? 'each' : 'it'} a joint, or fasten it to what it sits on (pins, screws, a press) and say so with a fit that "fastens"`, `${loose.length} loose`, { code: 'assembly.loose', refs: { items: loose } });
980
- else f('pass', `every part turns or slides on a joint, or is fastened to the ${ids[0]}`, null, { code: 'assembly.held' });
2211
+ if (loose.length)
2212
+ f(
2213
+ 'warn',
2214
+ `${loose.join(', ')} ${loose.length > 1 ? 'are' : 'is'} placed, but nothing holds ${loose.length > 1 ? 'them' : 'it'}: give ${loose.length > 1 ? 'each' : 'it'} a joint, or fasten it to what it sits on (pins, screws, a press) and say so with a fit that "fastens"`,
2215
+ `${loose.length} loose`,
2216
+ { code: 'assembly.loose', refs: { items: loose } },
2217
+ );
2218
+ else
2219
+ f('pass', `every part turns or slides on a joint, or is fastened to the ${ids[0]}`, null, {
2220
+ code: 'assembly.held',
2221
+ });
981
2222
  // A fit that fastens holds two items as one, but only a joint or an anchor moves them: one fastened to a part a
982
2223
  // joint moves, and placed where it stands, stays behind in every pose and is left out of what that joint carries
983
2224
  // (one also fastened to what stays, as a servo to its stand with its arm fastened to the horn, is held there)
984
- const moving = s.motion.joints.filter((j) => !j.at && j.type !== 'fixed'), across = (a, b) => moving.find((jj) => beyond(s.motion, jj, ids.indexOf(a)) !== beyond(s.motion, jj, ids.indexOf(b)));
985
- const still = new Set([ids[0], ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]), ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id)]), same = links.filter(([a, b]) => ids.includes(a) && ids.includes(b) && !across(a, b));
986
- for (let grew = true; grew;) { grew = false; for (const [a, b] of same) { if (still.has(a) && !still.has(b)) { still.add(b); grew = true; } if (still.has(b) && !still.has(a)) { still.add(a); grew = true; } } }
2225
+ const moving = s.motion.joints.filter((j) => !j.at && j.type !== 'fixed'),
2226
+ across = (a, b) =>
2227
+ moving.find((jj) => beyond(s.motion, jj, ids.indexOf(a)) !== beyond(s.motion, jj, ids.indexOf(b)));
2228
+ const still = new Set([
2229
+ ids[0],
2230
+ ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]),
2231
+ ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id),
2232
+ ]),
2233
+ same = links.filter(([a, b]) => ids.includes(a) && ids.includes(b) && !across(a, b));
2234
+ for (let grew = true; grew;) {
2235
+ grew = false;
2236
+ for (const [a, b] of same) {
2237
+ if (still.has(a) && !still.has(b)) {
2238
+ still.add(b);
2239
+ grew = true;
2240
+ }
2241
+ if (still.has(b) && !still.has(a)) {
2242
+ still.add(a);
2243
+ grew = true;
2244
+ }
2245
+ }
2246
+ }
987
2247
  for (const x of s.fits.filter((q) => q.fastens)) {
988
- const [a, b] = [top(x.a), top(x.b)], ia = ids.indexOf(a), ib = ids.indexOf(b);
2248
+ const [a, b] = [top(x.a), top(x.b)],
2249
+ ia = ids.indexOf(a),
2250
+ ib = ids.indexOf(b);
989
2251
  if (ia < 0 || ib < 0) continue;
990
2252
  const j = across(a, b);
991
2253
  if (!j || (still.has(a) && still.has(b))) continue;
992
2254
  const [mover, left] = beyond(s.motion, j, ia) ? [a, b] : [b, a];
993
- f('warn', `${left} is fastened to ${mover} (a fit that fastens), but only ${mover} moves on ${j.id}: ${left} is placed where it stands, so it stays there in every pose and its mass is left out of what ${j.id} carries (joint.moment). Place ${left} on ${mover} by an anchor or an address ("at": "${mover}.<anchor>")`,
994
- `${left}: left behind by ${j.id}`, { code: 'assembly.fastened', refs: { items: [left, mover], joint: j.id } });
2255
+ f(
2256
+ 'warn',
2257
+ `${left} is fastened to ${mover} (a fit that fastens), but only ${mover} moves on ${j.id}: ${left} is placed where it stands, so it stays there in every pose and its mass is left out of what ${j.id} carries (joint.moment). Place ${left} on ${mover} by an anchor or an address ("at": "${mover}.<anchor>")`,
2258
+ `${left}: left behind by ${j.id}`,
2259
+ { code: 'assembly.fastened', refs: { items: [left, mover], joint: j.id } },
2260
+ );
995
2261
  }
996
2262
  }
997
2263
  // Gears: each mesh's centre distance and contact ratio, said between the two axes (the rest by --sweep)
998
2264
  for (const g of s.motion.meshes || []) {
999
- f('info', g.planetary ? g.text : `${g.with} drives ${g.joint}: ${g.text}`, null, { code: 'mesh.ratio', refs: { joints: [g.with, g.joint] } });
2265
+ f('info', g.planetary ? g.text : `${g.with} drives ${g.joint}: ${g.text}`, null, {
2266
+ code: 'mesh.ratio',
2267
+ refs: { joints: [g.with, g.joint] },
2268
+ });
2269
+ if (g.faces) faceOverlap(g);
1000
2270
  for (const x of g.findings) {
1001
- const between = x.between || g.between, mid = between[0].map((v, k) => (v + between[1][k]) / 2);
1002
- f(x.level, g.planetary ? x.text : `${g.with} and ${g.joint}: ${x.text}`, x.level === 'pass' ? null : `${g.joint}: ${x.code.split('.')[1]}`, { code: x.code, at: mid, between, ...(x.values ? { values: x.values } : {}), refs: { joints: [g.with, g.joint] } });
2271
+ const between = x.between || g.between,
2272
+ mid = between[0].map((v, k) => (v + between[1][k]) / 2);
2273
+ f(
2274
+ x.level,
2275
+ g.planetary ? x.text : `${g.with} and ${g.joint}: ${x.text}`,
2276
+ x.level === 'pass' ? null : `${g.joint}: ${x.code.split('.')[1]}`,
2277
+ {
2278
+ code: x.code,
2279
+ at: mid,
2280
+ between,
2281
+ ...(x.values ? { values: x.values } : {}),
2282
+ refs: { joints: [g.with, g.joint] },
2283
+ },
2284
+ );
1003
2285
  }
1004
2286
  }
1005
2287
  }
1006
2288
  if (s.a.fasten?.length && fastening) fastening.fastenChecks(s, f, { placeItems });
1007
2289
  // A holes fit and a fit that fastens the same two items: one fasten says both, and knows the screw
1008
- if (fastening) for (const g of fastening.fastenFromFits(s)) {
1009
- f('info', `${g.label} and the fit that fastens ${g.pair[0]} to ${g.pair[1]} are one screwed joint: a fasten says both and knows the screw (its holes, length, thread engaged, the seat under its head and the key that turns it). In place of the two, add to "fasten": ${JSON.stringify(g.fasten)}${g.screw ? '' : ' (with the screw it takes: no thread was found in the fits or the holes)'}, or run cad add fasten ${s.project}/${s.name} --from-fits`,
1010
- null, { code: 'fasten.suggest', refs: { fits: [g.holes, g.fastens], items: g.pair, paste: g.fasten } });
1011
- }
2290
+ if (fastening)
2291
+ for (const g of fastening.fastenFromFits(s)) {
2292
+ f(
2293
+ 'info',
2294
+ `${g.label} and the fit that fastens ${g.pair[0]} to ${g.pair[1]} are one screwed joint: a fasten says both and knows the screw (its holes, length, thread engaged, the seat under its head and the key that turns it). In place of the two, add to "fasten": ${JSON.stringify(g.fasten)}${g.screw ? '' : ' (with the screw it takes: no thread was found in the fits or the holes)'}, or run cad add fasten ${s.project}/${s.name} --from-fits`,
2295
+ null,
2296
+ { code: 'fasten.suggest', refs: { fits: [g.holes, g.fastens], items: g.pair, paste: g.fasten } },
2297
+ );
2298
+ }
1012
2299
  boughtFindings(s, f);
1013
2300
  beamFindings(s, f);
1014
2301
  fittingFindings(s, f);
@@ -1016,7 +2303,19 @@ export function checkAssembly(s) {
1016
2303
  serviceFindings(s, f);
1017
2304
  beltLoads(s, { placeItems, jointValues, mul }); // (a belt's carriage pushed at its acceleration: a load on its joint, before the motor's checks read the loads)
1018
2305
  guideFindings(s, f);
1019
- if (s.generated) { const m = s.generated, [what, ...more] = frameText(m); f('info', `generated: ${what}; ${more.map((x) => x.trim()).join('; ')}`, null, { code: 'frame.generated', values: { inside: m.inside, outside: m.outside, lengths: m.lengths.map(({ length, count }) => ({ length, count })) }, refs: { kind: m.kind, profile: m.profile, join: m.join.kind, arrangement: m.arrangement, by: m.by } }); }
2306
+ if (s.generated) {
2307
+ const m = s.generated,
2308
+ [what, ...more] = frameText(m);
2309
+ f('info', `generated: ${what}; ${more.map((x) => x.trim()).join('; ')}`, null, {
2310
+ code: 'frame.generated',
2311
+ values: {
2312
+ inside: m.inside,
2313
+ outside: m.outside,
2314
+ lengths: m.lengths.map(({ length, count }) => ({ length, count })),
2315
+ },
2316
+ refs: { kind: m.kind, profile: m.profile, join: m.join.kind, arrangement: m.arrangement, by: m.by },
2317
+ });
2318
+ }
1020
2319
  joinChecks(s, f);
1021
2320
  slotNutChecks(s, f);
1022
2321
  frameSquareChecks(s, f);
@@ -1027,32 +2326,53 @@ export function checkAssembly(s) {
1027
2326
  motorChecks(s, f, { placeItems, jointValues, mul }, materialOf(s.project));
1028
2327
  powerChecks(s, f);
1029
2328
  loadChecks(s, f, { placeItems, jointValues, mul });
1030
- frameChecks(s, f, { placeItems, jointValues, mul });
2329
+ // (join.drop after the frame's checks: a beam's drop is taken from the frame's own solve where it has one)
2330
+ const solved = frameChecks(s, f, { placeItems, jointValues, mul });
2331
+ joinDropChecks(s, f, solved);
2332
+ // (each printed foot judged at the load the frame's solve puts on it, #378)
2333
+ footFindings(s, f, solved);
1031
2334
  sizeChecks(s, f, { placeItems, jointValues, mul });
1032
2335
  gripChecks(s, f);
1033
- gaitChecks(s, f, { jointValues, placeItems, sweepOne: (v) => clashesOf(s.at(v), named) });
2336
+ gaitChecks(s, f, { jointValues, sweepOne: (v) => clashesOf(s.at(v), named) });
1034
2337
  taskChecks(s, f);
1035
2338
  orderChecks(s, f, { frame: frameBuild });
1036
2339
  // Plates print everything: no references
1037
2340
  if (s.a.kind === 'plate') {
1038
2341
  const refs = s.objects.filter((o) => o.role === 'reference' && !o.unplaced); // an unplaced item only lends its numbers
1039
- if (refs.length) f('fail', `a plate can't print references: ${refs.map((o) => o.id).join(', ')}`, null, { code: 'plate.reference', refs: { items: refs.map((o) => o.id) } });
2342
+ if (refs.length)
2343
+ f('fail', `a plate can't print references: ${refs.map((o) => o.id).join(', ')}`, null, {
2344
+ code: 'plate.reference',
2345
+ refs: { items: refs.map((o) => o.id) },
2346
+ });
1040
2347
  }
1041
2348
  // Rules that are only estimates, anywhere in the assembly or its components
1042
2349
  const est = new Set();
1043
- for (const o of s.objects) for (const e of o.built.entries) if (e.kind === 'estimate' && (e.used || !e.name.includes('.'))) est.add(e.name);
1044
- for (const n of s.seen) { const [u, k] = n.split('.'); if (loadRuleSet(u).rules[k]?.kind === 'estimate') est.add(n); }
1045
- if (est.size) f('warn', `uses estimates, not measurements: ${[...est].join(', ')}. Measure each and settle it with cad measured ${s.project}/${s.name} <name>=<value>`, `Estimate: ${[...est].join(', ')}`, { code: 'rules.estimate', refs: { rules: [...est] } });
2350
+ for (const o of s.objects)
2351
+ for (const e of o.built.entries) if (e.kind === 'estimate' && (e.used || !e.name.includes('.'))) est.add(e.name);
2352
+ for (const n of s.seen) {
2353
+ const [u, k] = n.split('.');
2354
+ if (loadRuleSet(u).rules[k]?.kind === 'estimate') est.add(n);
2355
+ }
2356
+ if (est.size)
2357
+ f(
2358
+ 'warn',
2359
+ `uses estimates, not measurements: ${[...est].join(', ')}. Measure each and settle it with cad measured ${s.project}/${s.name} <name>=<value>`,
2360
+ `Estimate: ${[...est].join(', ')}`,
2361
+ { code: 'rules.estimate', refs: { rules: [...est] } },
2362
+ );
1046
2363
  saveOverlaps();
1047
2364
  return out;
1048
2365
  }
1049
2366
 
1050
2367
  // Each loop at the assembly's pose: how far apart its two anchors are (mm), and their axes (degrees, either way round)
1051
2368
  export function loopGaps(s) {
1052
- const worlds = placeItems(s.motion, s.jointValues), I = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
2369
+ const worlds = placeItems(s.motion, s.jointValues),
2370
+ I = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
1053
2371
  return s.motion.loops.map((l) => {
1054
- const A = mul(l.a.item < 0 ? I : worlds[l.a.item], l.a.frame), B = mul(l.b.item < 0 ? I : worlds[l.b.item], l.b.frame);
1055
- const gap = Math.hypot(A[3] - B[3], A[7] - B[7], A[11] - B[11]), dot = Math.abs(A[2] * B[2] + A[6] * B[6] + A[10] * B[10]);
2372
+ const A = mul(l.a.item < 0 ? I : worlds[l.a.item], l.a.frame),
2373
+ B = mul(l.b.item < 0 ? I : worlds[l.b.item], l.b.frame);
2374
+ const gap = Math.hypot(A[3] - B[3], A[7] - B[7], A[11] - B[11]),
2375
+ dot = Math.abs(A[2] * B[2] + A[6] * B[6] + A[10] * B[10]);
1056
2376
  const angle = Math.acos(Math.min(1, dot)) / (Math.PI / 180);
1057
2377
  return { label: l.label, gap, angle, ok: gap <= l.tolerance && angle <= 0.05 };
1058
2378
  });
@@ -1060,14 +2380,29 @@ export function loopGaps(s) {
1060
2380
 
1061
2381
  // Pairs of parts that overlap, as checkAssembly finds them (fits with a negative min allowed): [[a, b, mm³]]
1062
2382
  function clashesOf(s, named) {
1063
- const allowed = (a, b) => threaded(a, b) || s.fits.some((x) => x.min != null && x.num(x.min) < 0 && ((named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a))));
1064
- const boxes = s.parts.map((p) => bounds(p.triangles)), out = [];
1065
- for (let i = 0; i < s.parts.length; i++) for (let j = i + 1; j < s.parts.length; j++) {
1066
- const pa = s.parts[i], pb = s.parts[j], A = boxes[i], B = boxes[j];
1067
- if (pa.leaf === pb.leaf || ![0, 1, 2].every((k) => A.lo[k] <= B.hi[k] + 1e-6 && B.lo[k] <= A.hi[k] + 1e-6) || allowed(pa, pb)) continue;
1068
- const v = pairOverlap(pa, pb);
1069
- if (v > 0.01) out.push([pa.name, pb.name, v]);
1070
- }
2383
+ const allowed = (a, b) =>
2384
+ threaded(a, b) ||
2385
+ s.fits.some(
2386
+ (x) =>
2387
+ x.min != null && x.num(x.min) < 0 && ((named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a))),
2388
+ );
2389
+ const boxes = s.parts.map((p) => bounds(p.triangles)),
2390
+ out = [];
2391
+ for (let i = 0; i < s.parts.length; i++)
2392
+ for (let j = i + 1; j < s.parts.length; j++) {
2393
+ const pa = s.parts[i],
2394
+ pb = s.parts[j],
2395
+ A = boxes[i],
2396
+ B = boxes[j];
2397
+ if (
2398
+ pa.leaf === pb.leaf ||
2399
+ ![0, 1, 2].every((k) => A.lo[k] <= B.hi[k] + 1e-6 && B.lo[k] <= A.hi[k] + 1e-6) ||
2400
+ allowed(pa, pb)
2401
+ )
2402
+ continue;
2403
+ const v = pairOverlap(pa, pb);
2404
+ if (v > 0.01) out.push([pa.name, pb.name, v]);
2405
+ }
1071
2406
  return out;
1072
2407
  }
1073
2408
  const isNamed = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`);
@@ -1075,32 +2410,76 @@ const isNamed = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name
1075
2410
  // sweep(s, { joint, steps }) -> findings: each free joint (or the one named) moved through its range, the others held
1076
2411
  // at the assembly's pose, looking for parts that collide and loops that come apart on the way
1077
2412
  export function sweep(s, { joint, steps = 24, progress } = {}) {
1078
- const out = [], f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }), mm = (n) => `${Number(n.toFixed(2))}`;
2413
+ const out = [],
2414
+ f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }),
2415
+ mm = (n) => `${Number(n.toFixed(2))}`;
1079
2416
  const free = s.motion.joints.filter((j) => !j.follow && j.dofs.length && (!joint || j.id === joint));
1080
- if (joint && !free.length) throw new Error(`no joint "${joint}" to sweep (${s.motion.joints.filter((j) => !j.follow && j.dofs.length).map((j) => j.id).join(', ') || 'none'})`);
2417
+ if (joint && !free.length)
2418
+ throw new Error(
2419
+ `no joint "${joint}" to sweep (${
2420
+ s.motion.joints
2421
+ .filter((j) => !j.follow && j.dofs.length)
2422
+ .map((j) => j.id)
2423
+ .join(', ') || 'none'
2424
+ })`,
2425
+ );
1081
2426
  const base = s.jointValues;
1082
- for (const j of free) j.dofs.forEach(([lo, hi], d) => {
1083
- const unit = DOFS[j.type][d] === 'angle' ? '°' : ' mm', name = `${j.id}${j.dofs.length > 1 ? ` ${'xyz'[d] && j.type === 'ball' ? 'xyz'[d] : DOFS[j.type][d]}` : ''}`;
1084
- const bad = []; // [value, what]
1085
- // a door with its latch shut: also tried just off shut, finer than a step, so a hit within the first degree is seen
1086
- const held = (s.panels ?? []).find((p) => p.latch && p.joint === j.id && DOFS[j.type][d] === 'angle'), probe = held ? Math.min(PANEL_CHECK.latch_probe.value, (hi - lo) / steps) : 0;
1087
- const values = [...Array(steps + 1).keys()].map((i) => lo + ((hi - lo) * i) / steps);
1088
- if (probe > 0 && probe < (hi - lo) / steps) values.splice(1, 0, lo + probe);
1089
- for (const [i, v] of values.entries()) {
1090
- const set = { ...base, [j.id]: base[j.id].map((x, k) => (k === d ? v : x)) };
1091
- const t = s.at(Object.fromEntries(Object.entries(set).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow)));
1092
- const what = [...clashesOf(t, isNamed).map(([a, b]) => `${a} hits ${b}`), ...loopGaps(t).filter((l) => !l.ok).map((l) => `${l.label} apart by ${mm(l.gap)} mm`)];
1093
- if (what.length) bad.push([v, what]);
1094
- progress?.({ stage: 'sweep', joint: j.id, step: Math.min(i, steps), steps });
1095
- }
1096
- const ranges = []; // runs of steps in a row that collide
1097
- for (const [v, what] of bad) { const r = ranges[ranges.length - 1]; if (r && Math.abs(v - r.to - (hi - lo) / steps) < 1e-9) { r.to = v; r.what = [...new Set([...r.what, ...what])]; } else ranges.push({ from: v, to: v, what }); }
1098
- const span = `${mm(lo)} to ${mm(hi)}${unit}`, note = held ? ` (${held.latch} shut over ${held.id}: also tried ${mm(probe)}${unit} off shut)` : '';
1099
- if (!ranges.length) f('pass', `sweep ${name}, ${span} in ${steps} steps${note}: nothing collides`, `${name}: clear ${span}`, { code: 'sweep', values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) }, refs: { joint: name, collisions: [], ...(held ? { latch: held.latch } : {}) } });
1100
- else f('fail', `sweep ${name}, ${span} in ${steps} steps${note}: ${ranges.map((r) => `${r.from === r.to ? `at ${mm(r.from)}` : `${mm(r.from)} to ${mm(r.to)}`}${unit.trim()}: ${r.what.slice(0, 3).join('; ')}${r.what.length > 3 ? `; and ${r.what.length - 3} more` : ''}`).join(' | ')}`,
1101
- `${name}: collides ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`,
1102
- { code: 'sweep', values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) }, refs: { joint: name, ...(held ? { latch: held.latch } : {}), collisions: ranges.map((r) => ({ from: r.from, to: r.to, what: r.what })) } });
1103
- });
2427
+ for (const j of free)
2428
+ j.dofs.forEach(([lo, hi], d) => {
2429
+ const unit = DOFS[j.type][d] === 'angle' ? '°' : ' mm',
2430
+ name = `${j.id}${j.dofs.length > 1 ? ` ${'xyz'[d] && j.type === 'ball' ? 'xyz'[d] : DOFS[j.type][d]}` : ''}`;
2431
+ const bad = []; // [value, what]
2432
+ // a door with its latch shut: also tried just off shut, finer than a step, so a hit within the first degree is seen
2433
+ const held = (s.panels ?? []).find((p) => p.latch && p.joint === j.id && DOFS[j.type][d] === 'angle'),
2434
+ probe = held ? Math.min(PANEL_CHECK.latch_probe.value, (hi - lo) / steps) : 0;
2435
+ const values = [...Array(steps + 1).keys()].map((i) => lo + ((hi - lo) * i) / steps);
2436
+ if (probe > 0 && probe < (hi - lo) / steps) values.splice(1, 0, lo + probe);
2437
+ for (const [i, v] of values.entries()) {
2438
+ const set = { ...base, [j.id]: base[j.id].map((x, k) => (k === d ? v : x)) };
2439
+ const t = s.at(
2440
+ Object.fromEntries(Object.entries(set).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow)),
2441
+ );
2442
+ const what = [
2443
+ ...clashesOf(t, isNamed).map(([a, b]) => `${a} hits ${b}`),
2444
+ ...loopGaps(t)
2445
+ .filter((l) => !l.ok)
2446
+ .map((l) => `${l.label} apart by ${mm(l.gap)} mm`),
2447
+ ];
2448
+ if (what.length) bad.push([v, what]);
2449
+ progress?.({ stage: 'sweep', joint: j.id, step: Math.min(i, steps), steps });
2450
+ }
2451
+ const ranges = []; // runs of steps in a row that collide
2452
+ for (const [v, what] of bad) {
2453
+ const r = ranges[ranges.length - 1];
2454
+ if (r && Math.abs(v - r.to - (hi - lo) / steps) < 1e-9) {
2455
+ r.to = v;
2456
+ r.what = [...new Set([...r.what, ...what])];
2457
+ } else ranges.push({ from: v, to: v, what });
2458
+ }
2459
+ const span = `${mm(lo)} to ${mm(hi)}${unit}`,
2460
+ note = held ? ` (${held.latch} shut over ${held.id}: also tried ${mm(probe)}${unit} off shut)` : '';
2461
+ if (!ranges.length)
2462
+ f('pass', `sweep ${name}, ${span} in ${steps} steps${note}: nothing collides`, `${name}: clear ${span}`, {
2463
+ code: 'sweep',
2464
+ values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) },
2465
+ refs: { joint: name, collisions: [], ...(held ? { latch: held.latch } : {}) },
2466
+ });
2467
+ else
2468
+ f(
2469
+ 'fail',
2470
+ `sweep ${name}, ${span} in ${steps} steps${note}: ${ranges.map((r) => `${r.from === r.to ? `at ${mm(r.from)}` : `${mm(r.from)} to ${mm(r.to)}`}${unit.trim()}: ${r.what.slice(0, 3).join('; ')}${r.what.length > 3 ? `; and ${r.what.length - 3} more` : ''}`).join(' | ')}`,
2471
+ `${name}: collides ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`,
2472
+ {
2473
+ code: 'sweep',
2474
+ values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) },
2475
+ refs: {
2476
+ joint: name,
2477
+ ...(held ? { latch: held.latch } : {}),
2478
+ collisions: ranges.map((r) => ({ from: r.from, to: r.to, what: r.what })),
2479
+ },
2480
+ },
2481
+ );
2482
+ });
1104
2483
  saveOverlaps();
1105
2484
  return out;
1106
2485
  }
@@ -1108,11 +2487,20 @@ export function sweep(s, { joint, steps = 24, progress } = {}) {
1108
2487
  // shapes(parts) -> { shapes: [{ part, polygons, triangles }], place: [[shape index, 12 numbers], …] }
1109
2488
  // Each distinct shape once, then where each copy goes: a 3 × 4 transform by rows (x' = a·x + b·y + c·z + d, …).
1110
2489
  export function shapes(parts) {
1111
- const index = new Map(), list = [], place = [];
2490
+ const index = new Map(),
2491
+ list = [],
2492
+ place = [];
1112
2493
  for (const p of parts) {
1113
- if (!index.has(p.shape)) { index.set(p.shape, list.length); list.push({ part: p, polygons: p.local, triangles: p.localTriangles }); }
1114
- const m = p.m, r = (x) => Number(x.toFixed(6)); // JSCAD's mat4 is column-major
1115
- place.push([index.get(p.shape), ...[m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14]].map(r)]);
2494
+ if (!index.has(p.shape)) {
2495
+ index.set(p.shape, list.length);
2496
+ list.push({ part: p, polygons: p.local, triangles: p.localTriangles });
2497
+ }
2498
+ const m = p.m,
2499
+ r = (x) => Number(x.toFixed(6)); // JSCAD's mat4 is column-major
2500
+ place.push([
2501
+ index.get(p.shape),
2502
+ ...[m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14]].map(r),
2503
+ ]);
1116
2504
  }
1117
2505
  return { shapes: list, place };
1118
2506
  }
@@ -1121,21 +2509,46 @@ export function shapes(parts) {
1121
2509
  export function motionData(s) {
1122
2510
  const mo = s.motion;
1123
2511
  if (!mo.joints.length) return {};
1124
- const r = (x) => Number(x.toFixed(6)), names = mo.items.map((x) => x[0]);
1125
- const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`), allow = [];
2512
+ const r = (x) => Number(x.toFixed(6)),
2513
+ names = mo.items.map((x) => x[0]);
2514
+ const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`),
2515
+ allow = [];
1126
2516
  const loose = s.fits.filter((x) => x.min != null && x.num(x.min) < 0);
1127
- s.parts.forEach((pa, i) => s.parts.forEach((pb, j) => {
1128
- if (j > i && pa.item !== pb.item && (threaded(pa, pb) || loose.some((x) => (named(pa, x.a) && named(pb, x.b)) || (named(pa, x.b) && named(pb, x.a))))) allow.push([i, j]);
1129
- }));
1130
- return { motion: {
1131
- items: mo.items.map(([n, ...m]) => [n, ...m.map(r)]),
1132
- joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone, step }) => ({ id, type, parent, child, a: a.map(r), b: b.map(r), dofs: dofs.map((d) => d.map(r)),
1133
- ...(label ? { label } : {}), ...(follow ? { follow } : {}), ...(path ? { path: path.map((p) => p.map(r)) } : {}), ...(cone != null ? { cone } : {}), ...(step ? { step } : {}) })),
1134
- poses: mo.poses, ...(s.pose ? { pose: s.pose } : {}),
1135
- part: s.parts.map((p) => names.indexOf(p.moves ?? p.item)), // (a screw moves with the item it sits in)
1136
- ...(allow.length ? { allow } : {}),
1137
- ...(s.gait ? { sequence: gaitSequence(s) ?? undefined } : {}),
1138
- } };
2517
+ s.parts.forEach((pa, i) =>
2518
+ s.parts.forEach((pb, j) => {
2519
+ if (
2520
+ j > i &&
2521
+ pa.item !== pb.item &&
2522
+ (threaded(pa, pb) ||
2523
+ loose.some((x) => (named(pa, x.a) && named(pb, x.b)) || (named(pa, x.b) && named(pb, x.a))))
2524
+ )
2525
+ allow.push([i, j]);
2526
+ }),
2527
+ );
2528
+ return {
2529
+ motion: {
2530
+ items: mo.items.map(([n, ...m]) => [n, ...m.map(r)]),
2531
+ joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone, step }) => ({
2532
+ id,
2533
+ type,
2534
+ parent,
2535
+ child,
2536
+ a: a.map(r),
2537
+ b: b.map(r),
2538
+ dofs: dofs.map((d) => d.map(r)),
2539
+ ...(label ? { label } : {}),
2540
+ ...(follow ? { follow } : {}),
2541
+ ...(path ? { path: path.map((p) => p.map(r)) } : {}),
2542
+ ...(cone != null ? { cone } : {}),
2543
+ ...(step ? { step } : {}),
2544
+ })),
2545
+ poses: mo.poses,
2546
+ ...(s.pose ? { pose: s.pose } : {}),
2547
+ part: s.parts.map((p) => names.indexOf(p.moves ?? p.item)), // (a screw moves with the item it sits in)
2548
+ ...(allow.length ? { allow } : {}),
2549
+ ...(s.gait ? { sequence: gaitSequence(s) ?? undefined } : {}),
2550
+ },
2551
+ };
1139
2552
  }
1140
2553
 
1141
2554
  // ---------- links ----------