@rulecad/cad 0.7.97 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/AGENTS.md +26 -10
  2. package/CHANGELOG.md +442 -2
  3. package/EXAMPLES.md +48 -42
  4. package/README.md +226 -73
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2253 -514
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1854 -437
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +734 -113
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +900 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2710 -502
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +792 -176
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +149 -18
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +3 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1022 -212
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +41 -0
  57. package/lib/optimise.mjs +979 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +224 -36
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +38 -4
  68. package/lib/sandbox-hooks.mjs +154 -12
  69. package/lib/sandbox-preload.mjs +2 -2
  70. package/lib/sandbox-run.mjs +127 -12
  71. package/lib/sandbox.mjs +632 -35
  72. package/lib/schema.mjs +43 -11
  73. package/lib/seats.mjs +227 -49
  74. package/lib/services.mjs +261 -52
  75. package/lib/sheet.mjs +851 -178
  76. package/lib/slotnuts.mjs +213 -34
  77. package/lib/targets/gist.mjs +4 -1
  78. package/lib/targets.mjs +42 -6
  79. package/lib/task.mjs +376 -79
  80. package/lib/versions.mjs +113 -28
  81. package/lib/wires.mjs +228 -45
  82. package/lib/workspace.mjs +216 -17
  83. package/package.json +19 -19
  84. package/schemas/assembly.schema.json +2 -2
  85. package/schemas/object.schema.json +1 -1
  86. package/schemas/project.schema.json +1 -1
package/lib/assembly.mjs CHANGED
@@ -20,21 +20,35 @@
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';
27
27
  import { fileURLToPath } from 'node:url';
28
28
  import { evaluate, loadRuleSet } from './rules.mjs';
29
29
  import { paths, printerOf } from './workspace.mjs';
30
- import { locate, build, readObject, jscad } from './design.mjs';
30
+ import { plainName, isPlainName } from './names.mjs';
31
+ import { locateIn, build, readObject, jscad } from './design.mjs';
31
32
  import { materialise } from './versions.mjs';
32
33
  import { satisfies } from '@rulecad/versions';
33
34
  import { bounds } from '@rulecad/printcheck';
34
35
  import { closest, closestAt, inside, distanceToFace, overlapAt } from '@rulecad/fit';
35
- import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
36
+ import { keys as keyCentres, readLayout } from './layout.mjs';
36
37
  import { DOFS, frame, turn, mul, inv, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
37
- 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';
38
52
  import { ops as booleans } from '@rulecad/shapes';
39
53
  import { motorBuilt, motorDrives, shaftFits, loadsOf, motorChecks, shaftFit, axisOf } from './motors.mjs';
40
54
  import { runningChecks, seatFit, printerRules } from './seats.mjs';
@@ -49,8 +63,8 @@ import { gaitOf, gaitChecks, gaitSequence } from './gait.mjs';
49
63
  import { boughtBuilt, boughtFindings, boughtSets } from './bought.mjs';
50
64
  import { orderChecks } from './order.mjs';
51
65
  import { beamBuilt, beamPlace, beamAddress, beamFindings, marksOf, framesContext } from './beams.mjs';
52
- import { fittingBuilt, fittingFindings, plasticOf } from './fittings.mjs';
53
- import { expandJoins, joinChecks } from './joins.mjs';
66
+ import { fittingBuilt, fittingFindings, footFindings, plasticOf } from './fittings.mjs';
67
+ import { expandJoins, joinChecks, joinDropChecks } from './joins.mjs';
54
68
  import { expandFrame, frameText } from './framegen.mjs';
55
69
  import { frameChecks } from './framecheck.mjs';
56
70
  import { sizeChecks } from './framesize.mjs';
@@ -64,8 +78,14 @@ import { frameSquareChecks, frameBuild } from './framebuild.mjs';
64
78
  let pinning = null; // lib/pins.mjs, loaded with the first assembly whose fits name pins
65
79
  let fastening = null; // lib/fasten.mjs, loaded with the first assembly that has a fasten: the rest start as fast as before
66
80
 
67
- export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
68
- export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
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)
69
89
 
70
90
  export { satisfies }; // from @rulecad/versions
71
91
 
@@ -88,40 +108,60 @@ export { satisfies }; // from @rulecad/versions
88
108
  // checked or printed.
89
109
  // An object item can be a variant: "object": "keycap:oem-r3" (or "variant": "oem-r3"), and pin a release: "keycap@0.4.0".
90
110
  // overrides: { itemId: { variable: value } }, set on this assembly's items by the assembly that uses it.
91
- // 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).
92
113
  export async function buildAssembly(ref, stack = [], overrides = {}, opts = {}) {
93
114
  await measurer();
94
115
  const outer = overrides;
95
116
  const [project, name] = ref.split('/');
96
117
  if (stack.includes(ref)) throw new Error(`assembly ${ref} contains itself (${[...stack, ref].join(' → ')})`);
97
- let a = readJson(assemblyPath(ref));
118
+ let a = opts.assembly ? structuredClone(opts.assembly) : readJson(assemblyPath(ref));
98
119
  // A pose may set items' variables as well as joints ("cocked": { "run": -30, "action.travel": 25 }): a flexure bent
99
120
  // as the pose bends it, while the part itself is printed as drawn. The pose being built sets them on its items.
100
- 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
+ };
101
130
  const builtPose = opts.pose ?? a.pose ?? Object.keys(a.poses || {})[0];
102
131
  const ownSets = typeof builtPose === 'string' ? itemSets(builtPose) : {};
103
132
  overrides = { ...overrides };
104
133
  const printer = printerOf(project);
105
134
  if (a.kind === 'plate' && !(a.uses || []).includes(printer)) a.uses = [...(a.uses || []), printer]; // a plate is checked as a print
106
- 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
+ );
107
141
 
108
142
  // Names in positions: rule sets (mx.pitch), items' variables (cap.lift), or into components (key-0-0.cap.lift).
109
143
  // Rule values may still be expressions (rules referring to rules): resolved on demand.
110
- const seen = new Set(), ids = [];
144
+ const seen = new Set(),
145
+ ids = [];
111
146
  const lookup = (n) => {
112
147
  const path = n.split('.');
113
148
  if ((a.uses || []).includes(path[0])) seen.add(n);
114
- 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
+ );
115
153
  let v = values;
116
154
  for (const k of path) v = v?.[k];
117
- 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}`));
118
157
  if (typeof v !== 'number') throw new Error(`"${n}" isn't a number`);
119
158
  return v;
120
159
  };
121
160
  const num = (x) => evaluate(x, lookup);
122
161
  // A generated frame (lib/framegen.mjs): "frame": { "kind": "box", "inside": [..] } into beams, joins and their ends, first
123
162
  let generated = null;
124
- 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()));
125
165
  // Joins between beams (lib/joins.mjs): their operations go on the beams and their screws into fasten before anything is built
126
166
  let joins = [];
127
167
  if (a.joins != null) ({ a, joins } = expandJoins(a, num, undefined, plasticOf(project)));
@@ -129,25 +169,60 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
129
169
  let panels = [];
130
170
  if ((a.items || []).some((it) => it?.panel)) ({ a, panels } = expandPanels(a, num, undefined, plasticOf(project)));
131
171
  // Services (lib/services.mjs): a bought board or supply on its printed mount, a wire's run along a slot held by clips
132
- let mounts = [], runs = [];
133
- 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)));
134
179
  // Guides (lib/guides.mjs): a rail on a beam's face, its screws into the slot, each carriage on its own sliding joint
135
180
  let guides = [];
136
181
  if (a.guides != null) ({ a, guides } = expandGuides(a, num, undefined, plasticOf(project)));
137
- const { translate, rotate, transform } = jscad.transforms, deg = Math.PI / 180;
182
+ const { transform } = jscad.transforms;
138
183
 
139
- const items = [], parts = [], objects = [], fits = [], requires = [];
184
+ const items = [],
185
+ parts = [],
186
+ objects = [],
187
+ fits = [],
188
+ requires = [];
140
189
  for (const [k, r] of Object.entries(a.requires || {})) requires.push({ object: k, range: r, from: ref });
141
190
  const built = new Map(); // each object or component is built once per set of values, however many copies are placed
142
191
  const source = async (it, extra) => {
143
- 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); }
144
- 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)
145
- 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)
146
- 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)
147
- 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)
148
217
  if (it.bought) {
149
218
  const key = JSON.stringify(['bought', it.id, it.bought, it.variant, it.set]);
150
- 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
+ );
151
226
  return built.get(key);
152
227
  }
153
228
  // from: inputs worked out from items built before this one ({ "usb_y": "board.pcb.pico_y" }): numbers, in this
@@ -159,25 +234,75 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
159
234
  let own = null;
160
235
  const ownValue = async (x) => {
161
236
  if (typeof x !== 'string') return x;
162
- 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
+ }
163
242
  if (!it.object || !new RegExp(`\\b${it.id}\\.`).test(x)) return x;
164
- if (!own) { const [r, named] = String(it.object).split(':'), [objName, pin] = r.split('@'), d = locate(`${project}/${objName}`); own = (await build({ ...(pin ? materialise(d, pin) : d), ...((named || it.variant) ? { variant: named || it.variant } : {}) }, base, opts)).values; }
165
- 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
+ });
166
262
  };
167
263
  const posed = {};
168
264
  for (const [k, x] of Object.entries(ownSets[it.id] || {})) posed[k] = await ownValue(x);
169
265
  const set = { ...(it.set || {}), ...from, ...posed, ...(overrides[it.id] || {}), ...(it.assembly ? {} : extra) };
170
266
  // Built for the mirror, an object's mirror settings win (no legends), so copies that differ only there are one shape
171
- if (opts.mirror && it.object) for (const k of Object.keys(readObject(locate(`${project}/${String(it.object).split(/[:@]/)[0]}`)).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];
172
278
  const sub = it.assembly ? extra : {}; // a component's values go to its items: { cap: { units: 1.5 } }
173
279
  const key = JSON.stringify([it.object, it.variant, it.assembly, set, sub]);
174
280
  if (!built.has(key)) {
175
- 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'
176
290
  else {
177
- const [ref, named] = String(it.object).split(':'), [objName, pin] = ref.split('@'), variant = named || it.variant;
178
- const d = locate(`${project}/${objName}`), 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 } : {}) };
179
296
  const b = await build(at, set, opts);
180
- 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)
181
306
  }
182
307
  }
183
308
  return built.get(key);
@@ -185,46 +310,87 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
185
310
  const placing = [];
186
311
  let builtCount = 0;
187
312
  for (const it of a.items || []) {
188
- if (!/^[a-z][\w-]*$/.test(it.id || '')) throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
189
- 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"`);
190
- 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
+ );
191
323
  // Copies: one, a grid from repeat x/y, or a layout's keys. Each: { id, offset (from at), extra (values to set) }
192
- 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 = [];
193
328
  if (rl) {
194
329
  // A layout file in the project's layouts/, or (older assemblies) object/name: a layout kept in an object's .json
195
330
  const [lp, ln] = String(rl).includes('/') ? String(rl).split('/') : [null, rl];
196
- const data = lp ? readObject(locate(`${project}/${lp}`)).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);
197
336
  if (!data) throw new Error(`item ${it.id}: no layout "${ln}" in ${lp}.json`);
198
337
  const step = num(it.repeat.step);
199
338
  // Values each copy sets: its width, a value for its row (rows: { "cap.row": ["R1", …] }) and constants (each)
200
339
  // per: { "cap.legend": "legend" } sets an input from each key's own property (skipped where the key has none)
201
- const per = (k) => Object.fromEntries(Object.entries(it.repeat.per || {}).filter(([, f]) => k[f] != null).map(([n, f]) => [n, k[f]]));
202
- const values = (k) => ({ ...(it.repeat.width ? { [it.repeat.width]: k.units } : {}), ...(it.repeat.each || {}), ...per(k),
203
- ...Object.fromEntries(Object.entries(it.repeat.rows || {}).map(([n, list]) => {
204
- if (k.index >= list.length) throw new Error(`item ${it.id}: repeat.rows ${n} has ${list.length} values, the layout ${rows(data)} rows`);
205
- return [n, list[k.index]];
206
- })) });
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
+ });
207
360
  const rows = (l) => (l.rows || []).length;
208
361
  for (const k of keyCentres(data)) {
209
362
  const extra = {};
210
363
  for (const [n, val] of Object.entries(values(k))) {
211
- if (!it.assembly) { extra[n] = val; continue; }
364
+ if (!it.assembly) {
365
+ extra[n] = val;
366
+ continue;
367
+ }
212
368
  const [item, name] = n.split('.'); // in a component: <item>.<variable>
213
- 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
+ );
214
373
  (extra[item] ||= {})[name] = val;
215
374
  }
216
375
  copies.push({ id: `${it.id}-${k.index}-${k.col}`, offset: [k.x * step, k.y * step], extra, label: k.label });
217
376
  }
218
377
  } else {
219
- const nx = rx ? Math.round(num(rx.count)) : 1, ny = ry ? Math.round(num(ry.count)) : 1;
220
- for (let i = 0; i < nx; i++) for (let j = 0; j < ny; j++) {
221
- 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: {} });
222
- }
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
+ }
223
388
  }
224
389
  const first = await source(it, copies[0].extra);
225
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
226
391
  for (const c of copies) {
227
- 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;
228
394
  opts.progress?.({ stage: 'build', assembly: ref, item: c.id, done: ++builtCount }); // progress: for a caller to show (cad --progress)
229
395
  }
230
396
  placing.push([it, copies]);
@@ -234,29 +400,80 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
234
400
  // placed by at and rotate, or by the joint whose child it is.
235
401
  const placed = []; // [it, copy], each a motion item, in order
236
402
  for (const [it, copies] of placing) {
237
- 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'}`);
238
- if (it.place === false) { // built only for its values ("place": false): a board a print plate's case is sized from
239
- 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
+ });
240
419
  continue;
241
420
  }
242
- 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
+ }
243
425
  }
244
- 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);
245
430
  // (items printed together in place, which the assembly order never takes apart: each by its id)
246
- 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(', ')})`);
247
- 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
+ );
248
441
  for (const [it, c] of placed) {
249
- const src = c.src, id = c.id;
442
+ const src = c.src,
443
+ id = c.id;
250
444
  if (src.sub) {
251
445
  const sub = src.sub;
252
446
  for (const o of sub.objects) objects.push({ ...o, id: `${id}.${o.id}` });
253
- 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})` });
254
449
  requires.push(...sub.requires);
255
450
  for (const n of sub.seen) seen.add(n);
256
451
  items.push({ ...it, id, sub, role: 'part' });
257
452
  } else {
258
- 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)
259
- 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
+ });
260
477
  }
261
478
  }
262
479
  // Every part, with its item where the joints put it at these values (jointValues); then the hardware of its fasten
@@ -265,31 +482,72 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
265
482
  const partsAt = (worlds) => {
266
483
  const out = [];
267
484
  placed.forEach(([, c], k) => {
268
- 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]);
269
489
  items[k].m = m;
270
490
  // Faces are moved as they are, not re-triangulated in place: triangulating again after a move rounds differently
271
491
  const move = (polys) => polys.map((poly) => poly.map((v) => jscad.maths.vec3.transform([0, 0, 0], v, m)));
272
492
  if (src.sub) {
273
493
  for (const p of src.sub.parts) {
274
494
  if (p.role === 'support' && a.kind !== 'plate') continue;
275
- out.push({ ...p, name: `${id}.${p.name}`, item: id, leaf: `${id}.${p.leaf}`, label: `${id} ${p.label}`,
276
- 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),
277
- ...(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)
278
514
  }
279
515
  } else {
280
516
  for (const p of src.b.parts) {
281
517
  if (p.role === 'support' && a.kind !== 'plate') continue; // supports are snipped off before parts go together
282
- 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}`,
283
- ...(p.filament ? { filament: p.filament } : {}), ...(p.mirror === false ? { mirror: false } : {}), ...(p.fill != null ? { fill: p.fill } : {}), part: p.name,
284
- geometry: transform(m, p.geometry), ...(p.collide ? { collide: transform(m, p.collide) } : {}), polygons: move(p.polygons), triangles: move(p.triangles),
285
- 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
+ });
286
539
  }
287
540
  }
288
541
  });
289
542
  for (const h of hardware) out.push(fastening.hardwarePart(h, toMat4(worlds[h.host])));
290
543
  return out;
291
544
  };
292
- 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
+ );
293
551
  // each beam's mark on the cut list and its sheet (beams that are the same share one), shown in its label
294
552
  const marks = marksOf(objects);
295
553
  for (const o of objects) if (marks.has(o.id)) o.mark = marks.get(o.id);
@@ -303,7 +561,9 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
303
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)
304
562
  if (a.fasten?.length && a.kind !== 'plate') {
305
563
  fastening ||= await import('./fasten.mjs');
306
- 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
+ });
307
567
  hardware = fastened.hardware;
308
568
  parts.push(...hardware.map((h) => fastening.hardwarePart(h, toMat4(worlds0[h.host]))));
309
569
  fits.push(...fastened.fits.map((x) => ({ ...x, num })));
@@ -312,41 +572,94 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
312
572
  // With * on both sides, each copy is checked against all the others: { "a": "key-*.cap", "b": "key-*.cap" }
313
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
314
574
  const beamIds = new Set(placed.filter(([it]) => it.beam).map(([, c]) => c.id));
315
- for (const x of a.fits || []) for (const n of [x.a, x.b, x.access].flat()) {
316
- 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}`}`);
317
- }
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
+ }
318
580
  if (a.fits?.some((x) => x.fastener && typeof x.fastener === 'object')) pinning ||= await import('./pins.mjs');
319
581
  for (let x of a.fits || []) {
320
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)
321
583
  if (x.seat != null && x.min == null) x = { ...x, min: -1000 }; // a seat presses, so the pair may overlap
322
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)
323
585
  const star = [x.a, x.b].find((n) => n.includes('*'));
324
- if (!star) { fits.push({ ...x, num }); continue; }
325
- const match = (n) => { const re = new RegExp(`^${n.split('.')[0].replace(/[-]/g, '\\-').replace('*', '([\\w-]+)')}$`); return ids.filter((id) => re.test(id)); };
326
- 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('.');
327
596
  if (!copies.length) throw new Error(`fit ${x.a} / ${x.b}: nothing matches ${star}`);
328
597
  if (x.a.includes('*') && x.b.includes('*')) {
329
598
  const others = match(x.b);
330
- 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 });
331
601
  continue;
332
602
  }
333
- 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
+ }
334
607
  }
335
608
  // at(pose): the same assembly in another pose (a name, or { joint: values }), nothing built again
336
609
  const same = (x, y) => JSON.stringify(x) === JSON.stringify(y);
337
610
  const others = {};
338
- 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 });
339
615
  const at = (p) => {
340
616
  if (typeof p === 'string' && others[p]) return others[p];
341
- const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
342
- 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
+ };
343
628
  };
344
629
  // A stepper's torque at speed follows its driver's supply: the bought supply's volts, where the assembly has one
345
630
  // (power.mjs holds the same supply against the draw); with none, @rulecad/motors' default
346
631
  const psu = objects.find((o) => o.bought?.part === 'supply' && !o.unplaced)?.built.values.output_voltage;
347
632
  if (psu > 0) for (const d of motion?.drives ?? []) if (d.model?.type === 'stepper') d.supply = psu;
348
- 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,
349
- 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
+ };
350
663
  return s;
351
664
  }
352
665
 
@@ -375,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
375
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];
376
689
  export const LIMITS = { angle: [-180, 180] };
377
690
  function motionOf(a, placed, num, ref) {
378
- const { translate, rotate } = jscad.transforms, deg = Math.PI / 180;
691
+ const { translate, rotate } = jscad.transforms,
692
+ deg = Math.PI / 180;
379
693
  const index = new Map(placed.map(([, c], k) => [c.id, k]));
380
- const where = (n, what) => { if (!index.has(n)) throw new Error(`${what}: no item "${n}" (items: ${[...index.keys()].join(', ')})`); return index.get(n); };
381
- const evalIn = (values, label) => (x) => evaluate(x, (n) => {
382
- let v = values;
383
- for (const k of n.split('.')) v = v?.[k];
384
- if (typeof v !== 'number') throw new Error(`${label}: "${n}" isn't one of its numbers`);
385
- return v;
386
- });
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
+ });
387
705
  const frameOf = (spec, ev) => {
388
706
  const at = (spec.at || [0, 0, 0]).map(ev);
389
- 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
+ }
390
714
  return frame(at, (spec.axis || [0, 0, 1]).map(ev), spec.ref && spec.ref.map(ev));
391
715
  };
392
716
  // An anchor: { item (index, -1 the world), frame (12 numbers, in the item's own frame) }
393
717
  const anchor = (spec, what) => {
394
- if (spec && typeof spec === 'object') return { item: spec.item ? where(spec.item, what) : -1, frame: frameOf(spec, num) };
395
- const bits = String(spec).split('.'), id = bits[0];
396
- 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}")`);
397
724
  const k = where(id, what);
398
- let src = placed[k][1].src, pre = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], i = 1;
399
- for (; i < bits.length - 1 && !src.beam; i++) { // into a component: its item's place there
400
- 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);
401
732
  if (!sub) throw new Error(`${what}: ${bits.slice(0, i).join('.')} has no item "${n}"`);
402
733
  pre = mul(pre, rows(sub.m));
403
734
  src = sub.sub ? { sub: sub.sub } : { b: sub.built, objName: sub.objName, beam: sub.beam };
404
735
  }
405
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)
406
- 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
+ };
407
742
  const name = bits[i];
408
743
  const anchors = src.b?.object.anchors || {};
409
- 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
+ );
410
748
  return { item: k, frame: mul(pre, frameOf(anchors[name], evalIn(src.b.values, `${src.objName} anchor ${name}`))) };
411
749
  };
412
- const joints = [], children = new Set();
750
+ const joints = [],
751
+ children = new Set();
413
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
414
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
415
- const atAddress = placed.map(([it]) => it).filter((it, k, all) => typeof it.at === 'string' && all.indexOf(it) === k).map((it) => {
416
- 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]`);
417
- 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`);
418
- return { id: `${it.id}@`, type: 'fixed', parent: it.at, child: { item: it.id, at: [0, 0, 0], ...(it.rotate ? { rotate: it.rotate } : {}) }, at: true };
419
- });
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
+ });
420
774
  for (const j of [...atAddress, ...(a.joints || [])]) {
421
775
  const what = `joint ${j.id}`;
422
- 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)}`);
423
- if (!Object.hasOwn(DOFS, j.type)) throw new Error(`${what}: type is one of ${Object.keys(DOFS).join(', ')} (got ${JSON.stringify(j.type)})`);
424
- 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);
425
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)
426
786
  if (c.item < 0) throw new Error(`${what}: its child must be an item`);
427
787
  if (j.at && p.item === c.item) throw new Error(`item ${j.child.item}: at "${j.parent}" is on the item itself`);
428
- 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
+ );
429
792
  const [it] = placed[c.item];
430
- 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
+ );
431
797
  children.add(c.item);
432
798
  const path = j.type === 'path' ? (j.path || []).map((pt) => pt.map(num)) : undefined;
433
799
  if (path && path.length < 2) throw new Error(`${what}: a path joint needs "path": two points or more`);
434
- const kinds = DOFS[j.type], list = (x) => (x == null ? [] : [].concat(x));
435
- 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);
436
805
  const dofs = kinds.map((kind, i) => {
437
806
  const range = j.type === 'path' ? [0, pathLength(path)] : kind === 'angle' ? LIMITS.angle : null;
438
- 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];
439
809
  if (mn == null || mx == null) throw new Error(`${what}: give its ${kind} a min and max`);
440
810
  if (mn > mx) throw new Error(`${what}: min ${mn} is above max ${mx}`);
441
811
  return [mn, mx, val[i] != null ? num(val[i]) : Math.min(mx, Math.max(mn, 0))];
442
812
  });
443
- 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 } : {}),
444
- ...(j.label ? { label: j.label } : {}), ...(path ? { path } : {}), ...(j.cone != null ? { cone: num(j.cone) } : {}),
445
- ...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}),
446
- ...(j.mesh ? { meshSpec: j.mesh } : {}), ...(j.brake ? { brake: j.brake } : {}) });
447
- }
448
- for (const j of joints) if (j.follow) {
449
- const l = joints.find((x) => x.id === j.follow[0]);
450
- if (!l) throw new Error(`joint ${j.id}: follows "${j.follow[0]}", which isn't a joint (${joints.map((x) => x.id).join(', ')})`);
451
- 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
+ });
452
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
+ }
453
844
  const items = placed.map(([it, c], k) => {
454
845
  if (children.has(k)) return [c.id];
455
846
  const ends = it.beam ? beamPlace(it, num) : null; // a beam by its ends (lib/beams.mjs)
456
847
  if (ends) return [c.id, ...ends];
457
- 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);
458
850
  // A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
459
- 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
+ ];
460
858
  });
461
859
  const meshes = [...gearMeshes(joints, items, num), ...planetaries(a.planetary || [], joints, items, num)];
462
- const drives = motorDrives(a, placed, joints, num), loads = loadsOf(a, anchor, num, joints);
463
- const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).filter(([id]) => !id.includes('.')).map(([id, v]) => {
464
- if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
465
- return [id, Array.isArray(v) ? v.map(num) : num(v)];
466
- }))]));
467
- if (a.pose && !poses[a.pose]) throw new Error(`pose "${a.pose}" isn't one of the poses (${Object.keys(poses).join(', ') || 'none'})`);
468
- 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'}`,
469
- 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
+ }));
470
883
  // Every object item's anchors, to say where things are: a finding near one names it (keyboard@pivot)
471
- const marks = placed.flatMap(([, c], k) => Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
472
- try { return { item: k, id: c.id, name, frame: frameOf(spec, evalIn(c.src.b.values, `${c.src.objName} anchor ${name}`)) }; } catch { return null; }
473
- })).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);
474
900
  // address(name): any anchor by name, a beam's addresses too (x1.top@120), as { item, frame }: for fits and the build order
475
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
476
- 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 })));
477
- 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
+ };
478
923
  }
479
924
 
480
925
  // A pair measured from its drawn teeth (@rulecad/gears contact: backlash, transmission error, interference), kept in
481
926
  // .cache/gears/ by the pair, the centre distance and the gears package's code, as it takes half a second
482
927
  let gearsCode = null;
483
928
  function measured(a, b, centre) {
484
- gearsCode ||= (() => { const dir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))); return fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs').sort().map((f) => fs.readFileSync(path.join(dir, f), 'utf8')).join(''); })();
485
- const file = paths.cache('gears', `${crypto.createHash('sha256').update(JSON.stringify([gearsCode, a, b, +centre.toFixed(6)])).digest('hex')}.json`);
486
- if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
487
- const r = contact(a, b, { centre, steps: 12 }), keep = { findings: r.findings, backlash: r.backlash, error: r.error };
488
- 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
+ }
489
953
  return keep;
490
954
  }
491
955
 
@@ -495,100 +959,278 @@ function measured(a, b, centre) {
495
959
  // follows it. With one held, each turns in proportion to the driver (Willis), so each is a follow: its ratio from the
496
960
  // teeth, its offset from where the parts are with their joints at 0, so a tooth sits in a gap everywhere.
497
961
  function planetaries(list, joints, items, num) {
498
- const out = [], DEG = Math.PI / 180;
499
- const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
500
- 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]];
501
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]];
502
- 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);
503
975
  const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v)); // radians
504
976
  list.forEach((g, n) => {
505
- 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
+ };
506
983
  const idx = { sun: index(g.sun, 'sun'), carrier: index(g.carrier, 'carrier'), ring: index(g.ring, 'ring') };
507
984
  const planets = [].concat(g.planets || []).map((id) => index(id, 'planet'));
508
985
  if (!planets.length) throw new Error(`${what}: planets names the planet items`);
509
- 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
+ };
510
991
  const held = ['sun', 'carrier', 'ring'].filter((m) => !moving(idx[m]));
511
- 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
+ );
512
996
  const drive = g.drive ?? ['carrier', 'sun', 'ring'].find((m) => m !== held[0]);
513
- 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]})`);
514
- const third = ['sun', 'carrier', 'ring'].find((m) => m !== held[0] && m !== drive), lead = moving(idx[drive]), follower = moving(idx[third]);
515
- 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})`);
516
- 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`);
517
- 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
+ });
518
1018
  const teeth = [].concat(g.teeth || []).map(num);
519
1019
  if (teeth.length !== 3) throw new Error(`${what}: teeth is [sun, planet, ring] (got ${JSON.stringify(g.teeth)})`);
520
- const [S, P, R] = teeth, common = { module: num(g.module), ...(g.pressureAngle != null ? { pressureAngle: num(g.pressureAngle) } : {}), ...(g.backlash != null ? { backlash: num(g.backlash) } : {}) };
521
- let sun, planet, ring;
522
- try { sun = gearModel({ ...common, teeth: S }); planet = gearModel({ ...common, teeth: P }); ring = internalModel({ ...common, teeth: R }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
523
- 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})`);
524
1036
  // Every part where it is with these joints at 0
525
1037
  const v = jointValues({ joints, poses: {} }, {});
526
1038
  for (const j of [lead, follower, ...planetJoints]) v[j.id] = [0];
527
- 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)
528
- const worlds = placeItems({ items, joints }, v), W = (k) => worlds[k];
529
- const O = org(W(idx.sun)), Z = col(W(idx.sun), 2), X0 = col(W(idx.sun), 0);
530
- 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));
531
- 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
+ }
532
1063
  const gr = ang(flat(col(W(idx.ring), 0), Z), X0, Z) * (dot(col(W(idx.ring), 2), Z) > 0 ? 1 : -1);
533
1064
  // planet k: where it sits (its centre's angle round the sun) and which way its first tooth points
534
- 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
+ });
535
1076
  // One configuration that meshes, everything at its zero: planet 0 in phase with the ring, the sun with planet 0
536
- 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);
537
1080
  // Willis on rotations from the zero (sun σ, carrier κ, ring ρ): σ − κ + (R/S)(ρ − κ) = σ0
538
1081
  const coef = { sun: 1, carrier: -(1 + R / S), ring: R / S };
539
1082
  const sg = { [drive]: sign(lead), [third]: sign(follower) };
540
1083
  // the third's rotation for the driver's: from the relation, with the held one still
541
- 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
+ };
542
1089
  // a straight line in the driver's value (f: degrees in, radians out): [ratio, offset in degrees]
543
- 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)
544
- 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
545
1100
  const [k3, o3] = lin((d) => sg[third] * rot(d * DEG)[third]);
546
- follower.follow = [lead.id, k3, o3]; free(follower);
547
- 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 } : {}) });
548
1105
  pl.forEach((p, i) => {
549
1106
  // the planet's first tooth from the sun's mesh: π = −(S/P) σ + β (1 + S/P) + π − π/P, β the planet's place
550
- 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
+ };
551
1112
  const [kp, op] = lin((d) => p.s * (tooth(d) - p.gamma - rot(d * DEG).carrier));
552
- p.joint.follow = [lead.id, kp, op]; free(p.joint);
1113
+ p.joint.follow = [lead.id, kp, op];
1114
+ free(p.joint);
553
1115
  // and with the ring: in phase with it too, or it can't go there
554
- const ringTooth = (P / R) * tooth(0) + p.beta * (1 - P / R) - Math.PI / R, pitch = (2 * Math.PI) / R;
555
- 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;
556
1119
  const centre = org(W(planets[i]));
557
- 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
+ );
558
1127
  const m = meshOf(sun, planet, { centre: p.r });
559
1128
  for (const x of m.findings) f(x.level, `sun and ${p.id}: ${x.text}`, x.code, [O, centre]);
560
1129
  if (i === 0) {
561
- 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]);
562
- 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]);
563
1134
  }
564
1135
  });
565
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'}`;
566
- 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
+ });
567
1147
  // A second ring, on the planets' second step: it follows the planets' turning as the first ring would
568
1148
  if (g.output) {
569
- const k2 = index(g.output.ring, 'output ring'), j2 = moving(k2), P2 = num(g.output.planet), R2 = num(g.output.teeth), oc = { ...common };
570
- if (!j2 || j2.type !== 'revolute') throw new Error(`${what}: the output ring ${g.output.ring} turns on a revolute`);
571
- if (j2.follow || j2.meshSpec) throw new Error(`${what}: ${j2.id} follows the planets here: give it no follow or mesh of its own`);
572
- 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
+ );
573
1162
  let p2, r2;
574
- try { p2 = gearModel({ ...oc, teeth: P2 }); r2 = internalModel({ ...oc, teeth: R2 }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
575
- const g2 = ang(flat(col(W(k2), 0), Z), X0, Z), s2 = sign(j2), p0 = pl[0], ps = Math.PI / R2;
576
- 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; };
577
- 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
+ };
578
1181
  const [k, o] = lin((d) => s2 * ring2(d));
579
- j2.follow = [lead.id, k, o]; free(j2);
580
- const eff = compoundEfficiency({ planet: P, planet2: P2, ring: R, ring2: R2 }), fails = [], ff = (level, text, code) => fails.push({ level, text, code, between: [O, O] });
581
- 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);
582
1189
  // Each planet's second step in phase with the output ring. A planet meshes the sun as well a whole tooth of its
583
1190
  // first step on (2π/P), and that turns its second step too: the first of those turns that puts it in phase with
584
1191
  // the ring is the one it takes (none, where every planet is in phase as it stands, as chapter 11's are)
585
1192
  pl.forEach((p, i) => {
586
- 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
+ };
587
1210
  const m = i === 0 ? 0 : Array.from({ length: P }, (_, k) => k).find((k) => Math.abs(missAt(k)) <= 1e-6);
588
- 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');
589
- 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,
590
1233
  });
591
- 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 });
592
1234
  }
593
1235
  });
594
1236
  return out;
@@ -598,37 +1240,85 @@ function planetaries(list, joints, items, num) {
598
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
599
1241
  // cones must share their apex. The ratio is the surface speeds' where the pitch cones touch; the phase puts a tooth
600
1242
  // of one against a space of the other along that line.
601
- function bevelDrive(j, lead, spec, teeth, common, joints, items, num) {
602
- const what = `joint ${j.id}: mesh`, DEG = Math.PI / 180;
603
- const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
604
- 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);
605
- 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));
606
1255
  const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v));
607
- const v = jointValues({ joints, poses: {} }, {}); v[lead.id] = [0]; v[j.id] = [0];
608
- const worlds = placeItems({ items, joints }, v), W1 = worlds[lead.child], W2 = worlds[j.child];
609
- 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);
610
1268
  const shaft = Math.acos(Math.max(-1, Math.min(1, dot(Z1, Z2)))) / DEG;
611
1269
  let g1, g2;
612
- 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
+ }
613
1276
  // each cone's apex: along its axis, its cone distance × cos δ from its back end
614
- 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)));
615
1279
  const findings = [];
616
1280
  const apart = len(sub(A1, A2));
617
- 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
+ });
618
1287
  // where the pitch cones touch: from the apex, δ1 from the first's axis toward the second's (both pointing away)
619
- const out1 = times(Z1, -1), out2 = times(Z2, -1), across = unit(sub(out2, times(out1, dot(out1, out2))));
620
- const g = add(times(out1, Math.cos(g1.pitchAngle * DEG)), times(across, Math.sin(g1.pitchAngle * DEG))), P = add(A1, times(g, g1.coneDistance));
621
- const radial = (Z, X) => { const r = sub(g, times(Z, dot(g, Z))); return ang(r, X, Z); };
622
- 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);
623
1299
  // the second turns so the surface speeds match where they touch: ω2 = ω1 (Z1 × P)·(Z2 × P) / |Z2 × P|², P from the apex
624
- const p = sub(P, A1), r = dot(crossP(Z1, p), crossP(Z2, p)) / dot(crossP(Z2, p), crossP(Z2, p));
625
- 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));
626
- 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];
627
1307
  const phi = b2 - Math.PI / z2 - r * b1;
628
1308
  j.follow = [lead.id, s2 * r * s1, (s2 * phi) / DEG];
629
- 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
+ );
630
1313
  findings.push(...m.findings);
631
- 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
+ };
632
1322
  }
633
1323
 
634
1324
  // A worm and its wheel: "mesh": { "with": <the worm's joint>, "module", "teeth": [starts, wheel's teeth], "worm": {
@@ -636,36 +1326,103 @@ function bevelDrive(j, lead, spec, teeth, common, joints, items, num) {
636
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
637
1327
  // that plane taken into account. The worm is drawn as @rulecad/gears draws it (axis up its z, from z = 0).
638
1328
  function wormDrive(j, lead, spec, teeth, common, joints, items, num) {
639
- const what = `joint ${j.id}: mesh`, DEG = Math.PI / 180;
640
- const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
641
- 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]];
642
- 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);
643
1337
  const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v));
644
1338
  const ws = spec.worm === true ? {} : spec.worm;
645
1339
  let w, wheel;
646
1340
  try {
647
- 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
+ });
648
1347
  wheel = gearModel({ ...common, teeth: teeth[1], helix: w.leadAngle, hand: w.hand });
649
- } catch (e) { throw new Error(`${what}: ${e.message}`); }
650
- const v = jointValues({ joints, poses: {} }, {}); v[lead.id] = [0]; v[j.id] = [0];
651
- const worlds = placeItems({ items, joints }, v), Ww = worlds[lead.child], W2 = worlds[j.child];
652
- 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);
653
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`);
654
1364
  // the line between the axes: across both (the worm's along U, the wheel's along Z2)
655
- 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);
656
- 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));
657
- 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;
658
1385
  // the wheel's helix: its tooth 0 at the worm's plane is turned by k z there
659
- const zMid = dot(sub(Ow, O2), Z2), k = (sense * Math.tan(w.leadAngle * DEG)) / r2;
660
- 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;
661
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
662
- const theta = (dw) => { const z0 = (sense * L * (tw - sw * dw * DEG)) / (2 * Math.PI); return s2 * ((z0 - phr) / r2 - g2) - k * zMid; };
663
- 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);
664
1397
  j.follow = [lead.id, (a1 - a0) / DEG, a0 / DEG];
665
- 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
+ );
666
1407
  const c = meshOf(wheel, rackModel({ ...common, teeth: 4 }), { centre: dist - w.pitch / 2 });
667
- 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") }))];
668
- 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
+ };
669
1426
  }
670
1427
 
671
1428
  // Gears that mesh: "mesh": { "with": <the driving joint>, "module", "teeth": [its, this one's], "shift"?, "ring"? } on
@@ -673,85 +1430,252 @@ function wormDrive(j, lead, spec, teeth, common, joints, items, num) {
673
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
674
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
675
1432
  // +y, its first space at x = 0), and its joint turns it about its own axis. The centre distance is checked here, the
676
- // 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.
677
1435
  function gearMeshes(joints, items, num) {
678
- const out = [], list = (x) => (x == null ? [] : [].concat(x));
679
- const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
680
- 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]];
681
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]];
682
- 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);
683
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
684
1450
  // Is an item held still relative to another: every joint between it and the world fixed (or no joint at all)?
685
1451
  const byChild = new Map(joints.map((j) => [j.child, j]));
686
- 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
+ };
687
1461
  for (const j of joints) {
688
1462
  if (!j.meshSpec) continue;
689
- const spec = j.meshSpec, what = `joint ${j.id}: mesh`;
1463
+ const spec = j.meshSpec,
1464
+ what = `joint ${j.id}: mesh`;
690
1465
  delete j.meshSpec;
691
1466
  if (j.follow) throw new Error(`${what}: a meshed joint follows its mate already: give mesh or follow, not both`);
692
1467
  const lead = joints.find((x) => x.id === spec.with);
693
- 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)})`);
694
- if (lead.type !== 'revolute') throw new Error(`${what}: ${lead.id} is a ${lead.type}; the driver is a gear turning on a revolute`);
695
- 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})`);
696
- const kind = spec.bevel ? 'bevel' : spec.worm ? 'worm' : j.type === 'prismatic' ? 'rack' : spec.ring ? 'internal' : 'external';
697
- 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`);
698
- const teeth = list(spec.teeth).map(num), shift = list(spec.shift ?? [0, 0]).map(num);
699
- if (teeth.length !== 2) throw new Error(`${what}: teeth is [the driver's, this one's] (got ${JSON.stringify(spec.teeth)})`);
700
- const common = { module: num(spec.module), ...(spec.pressureAngle != null ? { pressureAngle: num(spec.pressureAngle) } : {}), ...(spec.backlash != null ? { backlash: num(spec.backlash) } : {}) };
701
- if (kind === 'worm') { out.push(wormDrive(j, lead, spec, teeth, common, joints, items, num)); continue; }
702
- 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
+ }
703
1509
  let A, B;
704
1510
  try {
705
1511
  A = gearModel({ ...common, teeth: teeth[0], shift: shift[0] });
706
- B = kind === 'rack' ? rackModel({ ...common, teeth: teeth[1] }) : (kind === 'internal' ? internalModel : gearModel)({ ...common, teeth: teeth[1], shift: shift[1] ?? 0 });
707
- } 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
+ }
708
1519
  // Where the two gears are with their own joints at 0 (everything else as it stands by default)
709
- const v = jointValues({ joints: joints.map((x) => (x.meshSpec ? { ...x, meshSpec: undefined } : x)), poses: {} }, {});
710
- v[lead.id] = [0]; v[j.id] = [0];
711
- const worlds = placeItems({ items, joints }, v), W1 = worlds[lead.child], W2 = worlds[j.child];
712
- 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) }; };
713
- 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);
714
1537
  // the driver turns about its own centre and axis, or its teeth wander
715
- 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
+ );
716
1542
  const result = { joint: j.id, with: lead.id, kind, findings: [], between: null };
717
1543
  if (kind === 'rack') {
718
- 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);
719
1549
  const sTravel = Math.sign(dot(ax2.dir, U));
720
- 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)`);
721
- 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)`);
722
- const s1 = Math.sign(dot(Z1, Zr)), rel = sub(O1, R0), at = dot(rel, U), height = dot(rel, Y);
723
- 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);
724
1560
  j.follow = [lead.id, sTravel * s1 * k, sTravel * (k * g1 + rackPhase(A, at))];
725
1561
  const m = meshOf(A, B, { centre: height });
726
- 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
+ };
727
1577
  } else {
728
- const O2 = org(W2), X2 = col(W2, 0), Z2 = col(W2, 2), ax2 = axisOf(j);
729
- 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`);
730
- 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)`);
731
- 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);
732
1594
  const m = meshOf(A, B, { centre: len(d) });
733
- 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
+ );
734
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)
735
1603
  j.follow = [lead.id, s * m.ratio, s * (phase(A, B, beta) - g2)];
736
- 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
+ };
737
1612
  }
738
1613
  out.push(result);
739
1614
  }
740
1615
  return out;
741
1616
  }
742
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
+
743
1662
  // Where each item's anchors are in a pose: [{ id: 'keyboard@pivot', item, at: [x, y, z] }]
744
1663
  // Where an address is in the world, at these joint values: { id (its item), at, frame }, or null where it is not an
745
1664
  // address on a beam (x1.top@120, x1.a.1). A beam's address it does not have is refused by name.
746
1665
  export function addressAt(s, n, values = s.jointValues) {
747
- 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);
748
1668
  if (!it?.beam || !String(n).includes('.') || !s.motion?.address) return null;
749
- 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);
750
1671
  return { id, at: [W[3], W[7], W[11]], frame: W };
751
1672
  }
752
1673
  export function anchorsAt(s, values = s.jointValues) {
753
1674
  const worlds = placeItems(s.motion, values);
754
- 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
+ });
755
1679
  }
756
1680
 
757
1681
  // keyCentres(layout): each key's centre, from lib/layout.mjs (kept under this name for older callers)
@@ -766,37 +1690,71 @@ export function overlap(ga, gb) {
766
1690
  const fell = solid?.stats.fallbacks ?? 0;
767
1691
  const v = Math.abs(jscad.measurements.measureVolume((solid ? solid.intersect : jscad.booleans.intersect)(ga, gb)));
768
1692
  if (v < 1e-6) return 0;
769
- // JSCAD's answer (no Manifold, or a shape Manifold couldn't read): only if their surfaces really cross, which fit
770
- // says exactly (slower, so only here)
771
- 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; }
1693
+ // JSCAD's answer (no Manifold, or a shape Manifold couldn't read): only if fit says they really run into each other
1694
+ // (their surfaces cross, one is inside the other, or they share volume beside a face plane they share: slower, so
1695
+ // only here)
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
+ }
772
1700
  return v;
773
1701
  }
774
1702
  // How overlaps are measured: whether the surfaces cross, exactly (fit), and then how much, with Manifold where it's
775
1703
  // installed. JSCAD's intersection misreads faces that come near without touching: two gears 0.07 mm apart (their
776
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³.
777
1705
  // Manifold is exact; a shape it can't read as a closed solid falls back to JSCAD's for that pair.
778
- let solid = null, tried = false;
1706
+ let solid = null,
1707
+ tried = false;
779
1708
  async function measurer() {
780
- if (tried) return; tried = true;
781
- 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)
782
1716
  }
783
1717
 
784
1718
  // Overlaps between placed parts, remembered across runs (.cache/overlaps.json): a part is its build (the build cache's
785
1719
  // hash: everything it's made from) and where it's placed, so after an edit only the pairs it touches are measured again
786
1720
  const OVERLAPS = paths.cache('overlaps.json');
787
- let remembered = null, fresh = 0;
1721
+ let remembered = null,
1722
+ fresh = 0;
788
1723
  function pairOverlap(pa, pb) {
789
1724
  const solidOf = (p) => p.collide ?? p.geometry; // (a beam by its envelope: lib/beams.mjs)
790
1725
  if (!pa.hash || !pb.hash) return overlap(solidOf(pa), solidOf(pb));
791
- remembered ||= (() => { try { return JSON.parse(host.readText(OVERLAPS)); } catch { return {}; } })();
792
- const at = (p) => `${p.hash}@${Array.from(p.m || []).map((x) => Math.round(x * 1e6) / 1e6).join(',')}`;
793
- const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`crossing+tracks+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
794
- if (!(k in remembered)) { remembered[k] = overlap(solidOf(pa), solidOf(pb)); fresh++; }
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(',')}`;
1737
+ // (the words in front change whenever the measure does, so an answer remembered from before is measured again: flush
1738
+ // overlaps, which fit once read as touching and were remembered as 0, came with #371)
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
+ }
795
1748
  return remembered[k];
796
1749
  }
797
1750
  function saveOverlaps() {
798
1751
  if (!fresh) return;
799
- 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
+ }
800
1758
  }
801
1759
 
802
1760
  // A screw and what it is threaded into (its part, its nut, its insert) share space by design: fasten's hardware says which
@@ -804,81 +1762,182 @@ const threaded = (a, b) => !!(a.allow?.includes(b.leaf) || b.allow?.includes(a.l
804
1762
 
805
1763
  // checkAssembly(built) -> findings, as @rulecad/printcheck: { level, text, card? } (card: a short line for the mirror)
806
1764
  // What a project prints in, for the motors' heat and press-fit checks
807
- 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
+ };
808
1772
 
809
1773
  // What's printed and how much it weighs, so "design small" is seen on every change
810
1774
  function massFinding(s, f) {
811
1775
  if (!s.parts.some((p) => p.role === 'reference') && !s.motion?.joints.length) return; // a machine, not a keyboard plate
812
- const parts = printedParts(s); if (!parts.length) return;
813
- const sorted = [...parts].sort((a, b) => b.grams - a.grams), total = sorted.reduce((t, p) => t + p.grams, 0);
814
- 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
+ );
815
1789
  }
816
1790
 
817
1791
  export function checkAssembly(s) {
818
1792
  // the screws found in this pose (at(pose) leaves them to be found again): the fasten and slot nut checks read the same
819
- if (!s.fastened && s.a.fasten?.length && fastening) s = { ...s, fastened: fastening.fastenOf(s, placeItems(s.motion, s.jointValues)) };
820
- 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))}`;
821
1798
  // Versions: every pin, from this assembly and its components, against every copy of that object
822
1799
  const pins = new Map();
823
1800
  for (const r of s.requires) pins.set(`${r.object} ${r.range}`, r);
824
1801
  for (const { object, range } of pins.values()) {
825
1802
  const copies = s.objects.filter((o) => o.objName === object);
826
- 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
+ }
827
1810
  const bad = copies.filter((o) => !satisfies(o.version, range));
828
- f(bad.length ? 'fail' : 'pass', bad.length ? `${object} ${bad[0].version} doesn't meet ${range} (${bad.map((o) => o.id).join(', ')})`
829
- : `${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
+ );
830
1819
  }
831
1820
  // Overlaps between object instances, inside components too. Bounding boxes first: most pairs can't touch.
832
1821
  const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`);
833
- 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))));
834
- const box = new Map(), bx = (p) => box.get(p) || (box.set(p, bounds(p.triangles)), box.get(p));
835
- 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);
836
1832
  const clashes = [];
837
- for (let i = 0; i < s.parts.length; i++) for (let j = i + 1; j < s.parts.length; j++) {
838
- const pa = s.parts[i], pb = s.parts[j];
839
- if (pa.leaf === pb.leaf || !touch(pa, pb) || allowed(pa, pb)) continue;
840
- const v = pairOverlap(pa, pb);
841
- 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 });
842
- }
843
- 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`,
844
- { code: 'overlap', values: { count: clashes.length }, refs: { overlaps: clashes.map(({ a, b, volume }) => ({ a, b, volume })) } });
845
- 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
+ });
846
1861
  // Fits: the closest gap between two named things, against a range. Copies of one fit are reported together, worst first.
847
1862
  // A fit names parts (keyboard, key-0-0.cap), or the faces of an item near one of its anchors (keyboard@pivot, within
848
1863
  // "within" mm, 10 by default): the pocket round a pivot, not the whole case
849
- 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);
850
1866
  // A beam's address in a fit (x1.top@120): the faces near that point, as near an anchor
851
- 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
+ };
852
1871
  const near = (p, mark, r) => ({ ...p, polygons: p.polygons.filter((f) => distanceToFace(mark.at, f) <= r) });
853
1872
  const pickIn = (n, x) => {
854
1873
  if (Array.isArray(n)) return n.flatMap((m) => pickIn(m, x));
855
- 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)
856
1878
  const mark = marks.find((m) => m.id === n) ?? addressMark(n);
857
1879
  if (!mark) return [];
858
- 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);
859
1884
  };
860
1885
  const pick = (n) => pickIn(n, {});
861
1886
  const groups = new Map();
862
1887
  for (const x of s.fits) {
863
1888
  if (x.poses && !x.poses.includes(s.pose)) continue; // a fit for some poses only: the folded screen over the keys
864
- if (x.holes) { holesFit(x); continue; }
1889
+ if (x.holes) {
1890
+ holesFit(x);
1891
+ continue;
1892
+ }
865
1893
  if (x.silent) continue; // lets a pair overlap, and has nothing to report
866
- if (x.engage != null) { engageFit(x); continue; }
867
- 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
+ }
868
1902
  if (x.pin && pinning) pinFit(x); // (and its gap, as any fit's)
869
1903
  if (x.magnet && pinning) magnetFit(x);
870
- if (x.shaft != null) { shaftFit(x, s, f, { placeItems, jointValues, mul, materialName: materialOf(s.project), holeComp: printerRules(s).hole_comp ?? 0.1 }); continue; }
871
- const A = pickIn(x.a, x), key = x.note || `${x.a} / ${x.b}`;
872
- 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;
873
1917
  const reach = Math.max(2, ...[lo, hi].filter(Number.isFinite)) + 1; // look past the range, so a gap near it is measured
874
1918
  let B = pickIn(x.b, x);
875
- if (Array.isArray(x.b) && A.length) { // against many others: only those within reach
876
- 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])));
877
1923
  B = B.filter((p) => [0, 1, 2].every((k) => bx(p).lo[k] <= hi3[k] + reach && lo3[k] <= bx(p).hi[k] + reach));
878
1924
  }
879
- 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
+ }
880
1932
  const vol = A.reduce((t, pa) => t + B.reduce((u, pb) => u + (touch(pa, pb) ? pairOverlap(pa, pb) : 0), 0), 0);
881
- 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
+ );
882
1941
  const gap = !B.length ? Infinity : vol > 0.01 ? -vol : near.gap; // negative: overlap, mm³
883
1942
  const ok = vol > 0.01 ? lo < 0 : gap >= lo && gap <= hi;
884
1943
  if (!groups.has(key)) groups.set(key, { x, lo, hi, results: [] });
@@ -887,124 +1946,356 @@ export function checkAssembly(s) {
887
1946
  // The anchor nearest a point, if one is within 20 mm: where to look
888
1947
  const nearest = (pt) => {
889
1948
  if (!pt || !marks.length) return {};
890
- 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];
891
1952
  return m.d <= 20 ? { near: m.k.id, distance: Number(m.d.toFixed(2)) } : {};
892
1953
  };
893
1954
  for (const [key, { x, lo, hi, results }] of groups) {
894
1955
  const worst = results.reduce((w, r) => (!r.ok && w.ok ? r : r.ok === w.ok && r.gap < w.gap ? r : w), results[0]);
895
- 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`;
896
1958
  const n = results.length > 1 ? ` (${results.filter((r) => r.ok).length} of ${results.length} in range)` : '';
897
1959
  const label = (x.label || x.a).replace(/ \(.*\)$/, '');
898
1960
  const where = nearest(worst.at);
899
- 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
+ }`,
900
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)'}`,
901
- { 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 },
902
- 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
+ );
903
1992
  }
904
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
905
1994
  // joint between them, each part's material near the axis (within radius, 10 mm) spans a stretch; how far the two
906
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
907
1996
  // seated one does, and nothing overlaps either way: only this tells them apart.
908
1997
  function engageFit(x) {
909
- 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}`;
910
- 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); });
911
- 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 } });
912
- 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);
913
- 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);
914
2020
  const span = (parts) => {
915
- let lo = Infinity, hi = -Infinity;
916
- for (const p of parts) for (const t of p.triangles) for (const v of t) {
917
- 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];
918
- 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); }
919
- }
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
+ }
920
2033
  return [lo, hi];
921
2034
  };
922
- 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));
923
2038
  const ok = on >= need - 1e-3; // (flush is on: a hair under, in the floating point, is not short)
924
- 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
+ );
925
2086
  }
926
2087
 
927
2088
  // Pin fits: the pins a fit names, their holes found in the parts and held to the pins' models (lib/pins.mjs)
928
- 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
+ }
929
2099
  // Magnet fits: the magnets a fit names, their pockets found in the parts and held to the magnet's seat (lib/magnets.mjs)
930
- 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
+ }
931
2110
  // Holes fits: each mounting hole's screw path, clear into a hole, with material round it
932
2111
  function holesFit(x) {
933
- 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}`;
934
2115
  const board = A.length && s.objects.find((o) => o.id === A[0].leaf)?.built;
935
- 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`);
936
2118
  if (!B.length) return f('fail', `${label}: no such ${x.b}`);
937
2119
  const holes = board.circuit.filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id);
938
2120
  if (!holes.length) return f('fail', `${label}: ${x.a} has no mounting holes`);
939
- const depth = x.num(x.depth), down = x.direction === 'up' ? 1 : -1, faces = B.flatMap((p) => p.triangles);
940
- 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);
941
- 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 = [];
942
2128
  for (const h of holes) {
943
- const ring = x.ring != null ? x.num(x.ring) : h.hole_diameter, where = `hole at ${mm(h.x)}, ${mm(h.y)} mm`;
944
- const blocked = Array.from({ length: steps }, (_, i) => (depth * (i + 0.5)) / steps).find((t) => inside(at(h, 0, 0, t), faces));
945
- if (blocked != null) { misses.push(`${where}: solid ${mm(blocked)} mm along the screw's path`); continue; }
946
- 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));
947
- 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`);
948
2143
  }
949
- 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`,
950
2149
  `${label}: ${misses.length ? `${misses.length} of ${holes.length} miss` : `${holes.length} of ${holes.length} line up`}`,
951
- { 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
+ );
952
2152
  }
953
2153
  // Joints: every value in its range (a ball's tip within its cone), and every loop closed
954
2154
  if (s.motion?.joints.length) {
955
2155
  const outside = [];
956
2156
  for (const j of s.motion.joints) {
957
2157
  const v = s.jointValues[j.id];
958
- 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)})`); });
959
- 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
+ }
960
2165
  }
961
- if (outside.length) f('fail', `joints out of range: ${outside.join(', ')}`, `${outside.length} joints out of range`, { code: 'joint.range', refs: { joints: outside } });
962
- 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
+ );
963
2178
  // Held by something: in a mechanism, every part but the first either turns or slides on a joint, or is fastened,
964
2179
  // through a chain of fits with "fastens", to the first. A part only placed somewhere stays there in the model and
965
2180
  // nowhere else: a ring gear resting on its case turns with the planets; a pawl resting on its post walks off it.
966
2181
  if (s.motion.joints.some((j) => j.type !== 'fixed')) {
967
- 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];
968
2184
  // (a beam placed by its ends is the frame, held where it is drawn: what is screwed to it is held by it)
969
- 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)]);
970
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)
971
- 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]]); }
972
- 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
+ }
973
2209
  const placed = new Set(s.objects.filter((o) => !o.unplaced && o.role !== 'reference').map((o) => top(o.id)));
974
2210
  const loose = ids.filter((id) => !held.has(id) && placed.has(id));
975
- 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 } });
976
- 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
+ });
977
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
978
2223
  // joint moves, and placed where it stands, stays behind in every pose and is left out of what that joint carries
979
2224
  // (one also fastened to what stays, as a servo to its stand with its arm fastened to the horn, is held there)
980
- 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)));
981
- 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));
982
- 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
+ }
983
2247
  for (const x of s.fits.filter((q) => q.fastens)) {
984
- 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);
985
2251
  if (ia < 0 || ib < 0) continue;
986
2252
  const j = across(a, b);
987
2253
  if (!j || (still.has(a) && still.has(b))) continue;
988
2254
  const [mover, left] = beyond(s.motion, j, ia) ? [a, b] : [b, a];
989
- 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>")`,
990
- `${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
+ );
991
2261
  }
992
2262
  }
993
2263
  // Gears: each mesh's centre distance and contact ratio, said between the two axes (the rest by --sweep)
994
2264
  for (const g of s.motion.meshes || []) {
995
- 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);
996
2270
  for (const x of g.findings) {
997
- const between = x.between || g.between, mid = between[0].map((v, k) => (v + between[1][k]) / 2);
998
- 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
+ );
999
2285
  }
1000
2286
  }
1001
2287
  }
1002
2288
  if (s.a.fasten?.length && fastening) fastening.fastenChecks(s, f, { placeItems });
1003
2289
  // A holes fit and a fit that fastens the same two items: one fasten says both, and knows the screw
1004
- if (fastening) for (const g of fastening.fastenFromFits(s)) {
1005
- 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`,
1006
- null, { code: 'fasten.suggest', refs: { fits: [g.holes, g.fastens], items: g.pair, paste: g.fasten } });
1007
- }
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
+ }
1008
2299
  boughtFindings(s, f);
1009
2300
  beamFindings(s, f);
1010
2301
  fittingFindings(s, f);
@@ -1012,7 +2303,19 @@ export function checkAssembly(s) {
1012
2303
  serviceFindings(s, f);
1013
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)
1014
2305
  guideFindings(s, f);
1015
- 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
+ }
1016
2319
  joinChecks(s, f);
1017
2320
  slotNutChecks(s, f);
1018
2321
  frameSquareChecks(s, f);
@@ -1023,32 +2326,53 @@ export function checkAssembly(s) {
1023
2326
  motorChecks(s, f, { placeItems, jointValues, mul }, materialOf(s.project));
1024
2327
  powerChecks(s, f);
1025
2328
  loadChecks(s, f, { placeItems, jointValues, mul });
1026
- 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);
1027
2334
  sizeChecks(s, f, { placeItems, jointValues, mul });
1028
2335
  gripChecks(s, f);
1029
- gaitChecks(s, f, { jointValues, placeItems, sweepOne: (v) => clashesOf(s.at(v), named) });
2336
+ gaitChecks(s, f, { jointValues, sweepOne: (v) => clashesOf(s.at(v), named) });
1030
2337
  taskChecks(s, f);
1031
2338
  orderChecks(s, f, { frame: frameBuild });
1032
2339
  // Plates print everything: no references
1033
2340
  if (s.a.kind === 'plate') {
1034
2341
  const refs = s.objects.filter((o) => o.role === 'reference' && !o.unplaced); // an unplaced item only lends its numbers
1035
- 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
+ });
1036
2347
  }
1037
2348
  // Rules that are only estimates, anywhere in the assembly or its components
1038
2349
  const est = new Set();
1039
- 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);
1040
- for (const n of s.seen) { const [u, k] = n.split('.'); if (loadRuleSet(u).rules[k]?.kind === 'estimate') est.add(n); }
1041
- 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
+ );
1042
2363
  saveOverlaps();
1043
2364
  return out;
1044
2365
  }
1045
2366
 
1046
2367
  // Each loop at the assembly's pose: how far apart its two anchors are (mm), and their axes (degrees, either way round)
1047
2368
  export function loopGaps(s) {
1048
- 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];
1049
2371
  return s.motion.loops.map((l) => {
1050
- 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);
1051
- 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]);
1052
2376
  const angle = Math.acos(Math.min(1, dot)) / (Math.PI / 180);
1053
2377
  return { label: l.label, gap, angle, ok: gap <= l.tolerance && angle <= 0.05 };
1054
2378
  });
@@ -1056,14 +2380,29 @@ export function loopGaps(s) {
1056
2380
 
1057
2381
  // Pairs of parts that overlap, as checkAssembly finds them (fits with a negative min allowed): [[a, b, mm³]]
1058
2382
  function clashesOf(s, named) {
1059
- 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))));
1060
- const boxes = s.parts.map((p) => bounds(p.triangles)), out = [];
1061
- for (let i = 0; i < s.parts.length; i++) for (let j = i + 1; j < s.parts.length; j++) {
1062
- const pa = s.parts[i], pb = s.parts[j], A = boxes[i], B = boxes[j];
1063
- 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;
1064
- const v = pairOverlap(pa, pb);
1065
- if (v > 0.01) out.push([pa.name, pb.name, v]);
1066
- }
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
+ }
1067
2406
  return out;
1068
2407
  }
1069
2408
  const isNamed = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`);
@@ -1071,32 +2410,76 @@ const isNamed = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name
1071
2410
  // sweep(s, { joint, steps }) -> findings: each free joint (or the one named) moved through its range, the others held
1072
2411
  // at the assembly's pose, looking for parts that collide and loops that come apart on the way
1073
2412
  export function sweep(s, { joint, steps = 24, progress } = {}) {
1074
- 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))}`;
1075
2416
  const free = s.motion.joints.filter((j) => !j.follow && j.dofs.length && (!joint || j.id === joint));
1076
- 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
+ );
1077
2426
  const base = s.jointValues;
1078
- for (const j of free) j.dofs.forEach(([lo, hi], d) => {
1079
- 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]}` : ''}`;
1080
- const bad = []; // [value, what]
1081
- // a door with its latch shut: also tried just off shut, finer than a step, so a hit within the first degree is seen
1082
- 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;
1083
- const values = [...Array(steps + 1).keys()].map((i) => lo + ((hi - lo) * i) / steps);
1084
- if (probe > 0 && probe < (hi - lo) / steps) values.splice(1, 0, lo + probe);
1085
- for (const [i, v] of values.entries()) {
1086
- const set = { ...base, [j.id]: base[j.id].map((x, k) => (k === d ? v : x)) };
1087
- const t = s.at(Object.fromEntries(Object.entries(set).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow)));
1088
- 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`)];
1089
- if (what.length) bad.push([v, what]);
1090
- progress?.({ stage: 'sweep', joint: j.id, step: Math.min(i, steps), steps });
1091
- }
1092
- const ranges = []; // runs of steps in a row that collide
1093
- 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 }); }
1094
- const span = `${mm(lo)} to ${mm(hi)}${unit}`, note = held ? ` (${held.latch} shut over ${held.id}: also tried ${mm(probe)}${unit} off shut)` : '';
1095
- 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 } : {}) } });
1096
- 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(' | ')}`,
1097
- `${name}: collides ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`,
1098
- { 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 })) } });
1099
- });
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
+ });
1100
2483
  saveOverlaps();
1101
2484
  return out;
1102
2485
  }
@@ -1104,11 +2487,20 @@ export function sweep(s, { joint, steps = 24, progress } = {}) {
1104
2487
  // shapes(parts) -> { shapes: [{ part, polygons, triangles }], place: [[shape index, 12 numbers], …] }
1105
2488
  // Each distinct shape once, then where each copy goes: a 3 × 4 transform by rows (x' = a·x + b·y + c·z + d, …).
1106
2489
  export function shapes(parts) {
1107
- const index = new Map(), list = [], place = [];
2490
+ const index = new Map(),
2491
+ list = [],
2492
+ place = [];
1108
2493
  for (const p of parts) {
1109
- if (!index.has(p.shape)) { index.set(p.shape, list.length); list.push({ part: p, polygons: p.local, triangles: p.localTriangles }); }
1110
- const m = p.m, r = (x) => Number(x.toFixed(6)); // JSCAD's mat4 is column-major
1111
- 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
+ ]);
1112
2504
  }
1113
2505
  return { shapes: list, place };
1114
2506
  }
@@ -1117,21 +2509,46 @@ export function shapes(parts) {
1117
2509
  export function motionData(s) {
1118
2510
  const mo = s.motion;
1119
2511
  if (!mo.joints.length) return {};
1120
- const r = (x) => Number(x.toFixed(6)), names = mo.items.map((x) => x[0]);
1121
- 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 = [];
1122
2516
  const loose = s.fits.filter((x) => x.min != null && x.num(x.min) < 0);
1123
- s.parts.forEach((pa, i) => s.parts.forEach((pb, j) => {
1124
- 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]);
1125
- }));
1126
- return { motion: {
1127
- items: mo.items.map(([n, ...m]) => [n, ...m.map(r)]),
1128
- 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)),
1129
- ...(label ? { label } : {}), ...(follow ? { follow } : {}), ...(path ? { path: path.map((p) => p.map(r)) } : {}), ...(cone != null ? { cone } : {}), ...(step ? { step } : {}) })),
1130
- poses: mo.poses, ...(s.pose ? { pose: s.pose } : {}),
1131
- part: s.parts.map((p) => names.indexOf(p.moves ?? p.item)), // (a screw moves with the item it sits in)
1132
- ...(allow.length ? { allow } : {}),
1133
- ...(s.gait ? { sequence: gaitSequence(s) ?? undefined } : {}),
1134
- } };
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
+ };
1135
2552
  }
1136
2553
 
1137
2554
  // ---------- links ----------