@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/fittings.mjs CHANGED
@@ -8,7 +8,7 @@ import path from 'node:path';
8
8
  import crypto from 'node:crypto';
9
9
  import * as frames from '@rulecad/frames';
10
10
  const { bracketModel, bracket, plateModel, plate } = frames;
11
- import { host } from './host.mjs';
11
+ import { host, readJson, cached } from './host.mjs';
12
12
  import { paths, RULE_DIRS } from './workspace.mjs';
13
13
  import { named } from './parts.mjs';
14
14
  import { givenFor } from './frames.mjs';
@@ -16,23 +16,68 @@ import { peekRuleSet } from './rules.mjs';
16
16
  import { ops as booleans } from '@rulecad/shapes';
17
17
  import jscad from '@jscad/modeling';
18
18
 
19
- const KEYS = ['kind', 'profile', 'other', 'face', 'otherFace', 'shape', 'brace', 'load', 'count', 'thread', 'head', 'nut'];
19
+ const KEYS = [
20
+ 'kind',
21
+ 'profile',
22
+ 'other',
23
+ 'face',
24
+ 'otherFace',
25
+ 'shape',
26
+ 'brace',
27
+ 'load',
28
+ 'count',
29
+ 'thread',
30
+ 'head',
31
+ 'nut',
32
+ ];
20
33
  // The printed fittings for panels, doors and beams' ends: each kind's model and solid in @rulecad/frames, whether it
21
34
  // is drawn for a profile, and the parts it has (a hinge's two leaves, a levelling foot's body and pad: an item each)
22
35
  const MORE = {
23
- 'panel-clip': ['panelClipModel', 'panelClip'], 'panel-corner': ['panelCornerModel', 'panelCorner'], 'slot-cover': ['slotCoverModel', 'slotCover'], 'panel-edge': ['panelEdgeModel', 'panelEdge'],
24
- 'gasket-strip': ['gasketStripModel', 'gasketStrip', { profile: false }], hinge: ['hingeModel', 'hinge', { parts: ['frame', 'door'] }], handle: ['handleModel', 'handle', { profile: false }], latch: ['latchModel', 'latch'],
25
- 'magnet-catch': ['magnetCatchModel', 'magnetCatch'], 'end-cap': ['endCapModel', 'endCap'], foot: ['footModel', 'foot'], 'levelling-foot': ['levellingFootModel', 'levellingFoot', { parts: ['body', 'pad'] }],
26
- 'castor-plate': ['castorPlateModel', 'castorPlate'], 'stacking-foot': ['stackingFootModel', 'stackingFoot'],
27
- 'device-mount': ['deviceMountModel', 'deviceMount'], 'fan-mount': ['fanMountModel', 'fanMount'], 'drag-chain-end': ['dragChainEndModel', 'dragChainEnd'], 'din-rail': ['dinRailAdapterModel', 'dinRailAdapter'],
28
- 'cable-clip': ['cableClipModel', 'cableClip'], 'tie-anchor': ['tieAnchorModel', 'tieAnchor'], 'spool-holder': ['spoolHolderModel', 'spoolHolder'],
29
- 'rail-jig': ['railJigModel', 'railJig'], 'wheel-plate': ['wheelsModel', 'wheelPlate'], slider: ['sliderModel', 'slider'],
36
+ 'panel-clip': ['panelClipModel', 'panelClip'],
37
+ 'panel-corner': ['panelCornerModel', 'panelCorner'],
38
+ 'slot-cover': ['slotCoverModel', 'slotCover'],
39
+ 'panel-edge': ['panelEdgeModel', 'panelEdge'],
40
+ 'gasket-strip': ['gasketStripModel', 'gasketStrip', { profile: false }],
41
+ hinge: ['hingeModel', 'hinge', { parts: ['frame', 'door'] }],
42
+ handle: ['handleModel', 'handle', { profile: false }],
43
+ latch: ['latchModel', 'latch'],
44
+ 'magnet-catch': ['magnetCatchModel', 'magnetCatch'],
45
+ 'end-cap': ['endCapModel', 'endCap'],
46
+ foot: ['footModel', 'foot'],
47
+ 'levelling-foot': ['levellingFootModel', 'levellingFoot', { parts: ['body', 'pad'] }],
48
+ 'castor-plate': ['castorPlateModel', 'castorPlate'],
49
+ 'stacking-foot': ['stackingFootModel', 'stackingFoot'],
50
+ 'device-mount': ['deviceMountModel', 'deviceMount'],
51
+ 'fan-mount': ['fanMountModel', 'fanMount'],
52
+ 'drag-chain-end': ['dragChainEndModel', 'dragChainEnd'],
53
+ 'din-rail': ['dinRailAdapterModel', 'dinRailAdapter'],
54
+ 'cable-clip': ['cableClipModel', 'cableClip'],
55
+ 'tie-anchor': ['tieAnchorModel', 'tieAnchor'],
56
+ 'spool-holder': ['spoolHolderModel', 'spoolHolder'],
57
+ 'rail-jig': ['railJigModel', 'railJig'],
58
+ 'wheel-plate': ['wheelsModel', 'wheelPlate'],
59
+ slider: ['sliderModel', 'slider'],
30
60
  'nut-carrier': ['carrierModel', 'carrier', { pose: { fit: 'slot', print: 'print' } }],
31
- 'rod-holder': ['rodHolderModel', 'rodHolder'], 'rod-carriage': ['rodCarriageModel', 'rodCarriage'], 'motor-plate': ['motorPlateModel', 'motorPlate'], 'endstop-mount': ['endstopMountModel', 'endstopMount'],
32
- 'belt-plate': ['beltPlateModel', 'beltPlate'], 'belt-clamp': ['beltClampModel', 'beltClamp', { profile: false }], 'belt-idler': ['beltIdlerModel', 'beltIdler'],
61
+ 'rod-holder': ['rodHolderModel', 'rodHolder'],
62
+ 'rod-carriage': ['rodCarriageModel', 'rodCarriage'],
63
+ 'motor-plate': ['motorPlateModel', 'motorPlate'],
64
+ 'endstop-mount': ['endstopMountModel', 'endstopMount'],
65
+ 'belt-plate': ['beltPlateModel', 'beltPlate'],
66
+ 'belt-clamp': ['beltClampModel', 'beltClamp', { profile: false }],
67
+ 'belt-idler': ['beltIdlerModel', 'beltIdler'],
33
68
  };
34
69
  // the kinds whose tongue or stem stands in the slot, inside the beam's envelope: the overlap check measures them without it
35
- const TONGUED = ['panel-clip', 'magnet-catch', 'panel-corner', 'cable-clip', 'tie-anchor', 'spool-holder', 'rail-jig', 'slider', 'end-cap'];
70
+ const TONGUED = [
71
+ 'panel-clip',
72
+ 'magnet-catch',
73
+ 'panel-corner',
74
+ 'cable-clip',
75
+ 'tie-anchor',
76
+ 'spool-holder',
77
+ 'rail-jig',
78
+ 'slider',
79
+ 'end-cap',
80
+ ];
36
81
  // parts that lie in a slot by design (an in-slot panel edge, a slot cover's strip, a nut carrier): only what stands above the face is
37
82
  // measured by the overlap check, as a tongue is left out
38
83
  const IN_SLOT = ['panel-edge', 'slot-cover', 'nut-carrier'];
@@ -46,11 +91,22 @@ export const fittingCache = {
46
91
  get(key) {
47
92
  if (process.env.CAD_NO_CACHE) return undefined;
48
93
  const file = paths.cache('fitting', `${crypto.createHash('sha256').update(key).digest('hex').slice(0, 24)}.json`);
49
- try { return host.exists(file) ? JSON.parse(host.readText(file)) : undefined; } catch { return undefined; }
94
+ try {
95
+ return cached(file) ? JSON.parse(host.readText(file)) : undefined;
96
+ } catch {
97
+ return undefined;
98
+ }
50
99
  },
51
100
  set(key, v) {
52
101
  if (process.env.CAD_NO_CACHE) return;
53
- try { host.writeText(paths.cache('fitting', `${crypto.createHash('sha256').update(key).digest('hex').slice(0, 24)}.json`), JSON.stringify(v)); } catch {} // (a cache that cannot be written is solved again next time)
102
+ try {
103
+ host.writeText(
104
+ paths.cache('fitting', `${crypto.createHash('sha256').update(key).digest('hex').slice(0, 24)}.json`),
105
+ JSON.stringify(v),
106
+ );
107
+ } catch {
108
+ // (a cache that cannot be written is solved again next time)
109
+ }
54
110
  },
55
111
  };
56
112
 
@@ -62,7 +118,11 @@ export const fittingCache = {
62
118
  */
63
119
  export function plasticOf(project) {
64
120
  let raw;
65
- try { raw = JSON.parse(fs.readFileSync(path.join(paths.project(project), 'project.json'), 'utf8')).material; } catch { return 'pla'; }
121
+ try {
122
+ raw = readJson(path.join(paths.project(project), 'project.json')).material;
123
+ } catch {
124
+ return 'pla';
125
+ }
66
126
  return plasticNamed(raw, `project ${project}`);
67
127
  }
68
128
 
@@ -72,14 +132,27 @@ export function plasticOf(project) {
72
132
  * @param {any} raw the material as written @param {string} [where] what names it, for the refusal @returns {string | object}
73
133
  */
74
134
  export function plasticNamed(raw, where = 'the project') {
75
- const m = String(raw || 'pla').trim().toLowerCase().split(/\s/)[0];
135
+ const m = String(raw || 'pla')
136
+ .trim()
137
+ .toLowerCase()
138
+ .split(/\s/)[0];
76
139
  if (['pla', 'petg'].includes(m)) return m;
77
- let set = null; try { set = peekRuleSet(m); } catch {}
140
+ let set = null;
141
+ try {
142
+ set = peekRuleSet(m);
143
+ } catch {
144
+ // (no such material rule set: the figures it lacks are named just below)
145
+ }
78
146
  const lacks = ['strength', 'modulus', 'density'].filter((k) => !(typeof set?.rules?.[k]?.value === 'number'));
79
147
  const have = plastics().join(', ');
80
- if (set && !lacks.length && rubber(set.rules)) throw new Error(`${where}: its material is ${JSON.stringify(raw)}, a rubber (its strength over its modulus is ${(set.rules.strength.value / set.rules.modulus.value).toFixed(2)}, a strain far past where its stiffness holds), and printed fittings are sized with sums for a stiff plastic that do not hold for it. Set the material to one of ${have}`);
148
+ if (set && !lacks.length && rubber(set.rules))
149
+ throw new Error(
150
+ `${where}: its material is ${JSON.stringify(raw)}, a rubber (its strength over its modulus is ${(set.rules.strength.value / set.rules.modulus.value).toFixed(2)}, a strain far past where its stiffness holds), and printed fittings are sized with sums for a stiff plastic that do not hold for it. Set the material to one of ${have}`,
151
+ );
81
152
  if (set && !lacks.length) return set;
82
- throw new Error(`${where}: its material is ${JSON.stringify(raw)}, and printed fittings are sized from their plastic's strength, modulus and density: ${set ? `rules/${m}.json gives no ${lacks.join(', ')}` : `the kit and this workspace have rule sets for ${have}, and there is no rules/${m}.json`}. Give rules/${m}.json with all three, or set the material to one of ${have}`);
153
+ throw new Error(
154
+ `${where}: its material is ${JSON.stringify(raw)}, and printed fittings are sized from their plastic's strength, modulus and density: ${set ? `rules/${m}.json gives no ${lacks.join(', ')}` : `the kit and this workspace have rule sets for ${have}, and there is no rules/${m}.json`}. Give rules/${m}.json with all three, or set the material to one of ${have}`,
155
+ );
83
156
  }
84
157
 
85
158
  // A rubber (TPU): its strength over its modulus, the strain where a stiff plastic yields, is past 0.5. Its stiffness
@@ -94,10 +167,21 @@ const rubber = (r) => r.strength.value / r.modulus.value > 0.5;
94
167
  export function plastics() {
95
168
  const out = new Set();
96
169
  for (const d of RULE_DIRS) {
97
- let files = []; try { files = fs.readdirSync(d).filter((f) => f.endsWith('.json')); } catch { continue; }
170
+ let files = [];
171
+ try {
172
+ files = fs.readdirSync(d).filter((f) => f.endsWith('.json'));
173
+ } catch {
174
+ continue;
175
+ }
98
176
  for (const f of files) {
99
- let r; try { r = JSON.parse(fs.readFileSync(path.join(d, f), 'utf8')).rules; } catch { continue; }
100
- if (['strength', 'modulus', 'density', 'modulus_z'].every((k) => typeof r?.[k]?.value === 'number') && !rubber(r)) out.add(f.slice(0, -5));
177
+ let r;
178
+ try {
179
+ r = readJson(path.join(d, f)).rules;
180
+ } catch {
181
+ continue;
182
+ }
183
+ if (['strength', 'modulus', 'density', 'modulus_z'].every((k) => typeof r?.[k]?.value === 'number') && !rubber(r))
184
+ out.add(f.slice(0, -5));
101
185
  }
102
186
  }
103
187
  return [...out].sort();
@@ -110,12 +194,21 @@ export function plastics() {
110
194
  * @param {object} s a built assembly @returns {{ id: string, of: string, fitting: object, grams: number }[]}
111
195
  */
112
196
  export function companions(s) {
113
- const items = s.items ?? [], out = [];
197
+ const items = s.items ?? [],
198
+ out = [];
114
199
  for (const o of s.objects) {
115
200
  if (o.unplaced || o.fitting?.fitting !== 'levelling-foot' || !o.fitting.printed) continue;
116
201
  const it = items.find((x) => x.id === o.id);
117
202
  if (!it?.fitting || (it.fitting.part ?? 'body') !== 'body') continue;
118
- if (items.some((x) => x.fitting?.kind === 'levelling-foot' && x.fitting.part === 'pad' && JSON.stringify(x.at) === JSON.stringify(it.at))) continue;
203
+ if (
204
+ items.some(
205
+ (x) =>
206
+ x.fitting?.kind === 'levelling-foot' &&
207
+ x.fitting.part === 'pad' &&
208
+ JSON.stringify(x.at) === JSON.stringify(it.at),
209
+ )
210
+ )
211
+ continue;
119
212
  const { pose, ...spec } = it.fitting;
120
213
  out.push({ id: `${o.id}-pad`, of: o.id, fitting: { ...spec, part: 'pad' }, grams: o.fitting.padGrams });
121
214
  }
@@ -128,36 +221,88 @@ export function companions(s) {
128
221
  * @param {object} context framesContext()'s @param {string | object} [material] pla, petg or a material's rule set (plasticOf) @param {string} [what] who asks
129
222
  */
130
223
  export function fittingModel(spec, context, material = 'pla', what = 'fitting') {
131
- if (!spec || typeof spec !== 'object' || Array.isArray(spec)) throw new Error(`${what}: fitting is { "kind": "bracket", "profile": "2020-misumi-hfs5" } (got ${shown(spec)})`);
132
- if (!FITTING_KINDS.includes(spec?.kind)) throw new Error(`${what}: fitting.kind is one of ${FITTING_KINDS.join(', ')} (got ${shown(spec?.kind)})`);
224
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec))
225
+ throw new Error(`${what}: fitting is { "kind": "bracket", "profile": "2020-misumi-hfs5" } (got ${shown(spec)})`);
226
+ if (!FITTING_KINDS.includes(spec?.kind))
227
+ throw new Error(`${what}: fitting.kind is one of ${FITTING_KINDS.join(', ')} (got ${shown(spec?.kind)})`);
133
228
  if (MORE[spec.kind]) return moreModel(spec, context, material, what);
134
- for (const k of Object.keys(spec)) if (!KEYS.includes(k)) throw new Error(`${what}: a fitting has no "${k}": it takes ${KEYS.join(', ')}`);
135
- const given = givenFor(context, spec.profile), o = { given, material, cache: fittingCache };
229
+ for (const k of Object.keys(spec))
230
+ if (!KEYS.includes(k)) throw new Error(`${what}: a fitting has no "${k}": it takes ${KEYS.join(', ')}`);
231
+ const given = givenFor(context, spec.profile),
232
+ o = { given, material, cache: fittingCache };
136
233
  for (const k of ['thread', 'head', 'nut', 'load']) if (spec[k] != null) o[k] = spec[k];
137
234
  try {
138
- if (spec.kind === 'bracket') return bracketModel(spec.profile, { ...o, ...(spec.other ? { other: spec.other } : {}), ...(spec.face ? { face: spec.face } : {}), ...(spec.otherFace ? { otherFace: spec.otherFace } : {}), ...(spec.brace != null ? { brace: spec.brace } : {}) });
139
- return plateModel(spec.profile, { ...o, shape: spec.kind === 'splice' ? 'splice' : spec.shape ?? 'L', ...(spec.other ? { other: spec.other } : {}), ...(spec.face ? { face: spec.face } : {}), ...(spec.count != null ? { count: spec.count } : {}) });
140
- } catch (e) { throw new Error(`${what}: ${strip(e)}`); }
235
+ if (spec.kind === 'bracket')
236
+ return bracketModel(spec.profile, {
237
+ ...o,
238
+ ...(spec.other ? { other: spec.other } : {}),
239
+ ...(spec.face ? { face: spec.face } : {}),
240
+ ...(spec.otherFace ? { otherFace: spec.otherFace } : {}),
241
+ ...(spec.brace != null ? { brace: spec.brace } : {}),
242
+ });
243
+ return plateModel(spec.profile, {
244
+ ...o,
245
+ shape: spec.kind === 'splice' ? 'splice' : (spec.shape ?? 'L'),
246
+ ...(spec.other ? { other: spec.other } : {}),
247
+ ...(spec.face ? { face: spec.face } : {}),
248
+ ...(spec.count != null ? { count: spec.count } : {}),
249
+ });
250
+ } catch (e) {
251
+ throw new Error(`${what}: ${strip(e)}`);
252
+ }
141
253
  }
142
254
 
143
255
  // A panel's, a door's or an end's fitting: its options are the model's own (refused by name there), its part chosen
144
256
  function moreModel(spec, context, material, what) {
145
- const [model, , o = {}] = MORE[spec.kind], { kind, profile, part, ...rest } = spec;
257
+ const [model, , o = {}] = MORE[spec.kind],
258
+ { kind, profile, part, ...rest } = spec;
146
259
  // (a device mount names its device's rule set, which is read here: its holes come from it)
147
260
  if (kind === 'device-mount') {
148
- if (typeof rest.device !== 'string') throw new Error(`${what}: a device mount names its device's rule set in "device", as supply-24v (got ${shown(rest.device)})`);
149
- try { rest.device = peekRuleSet(rest.device); } catch (e) { throw new Error(`${what}: device: ${e.message}`); }
261
+ if (typeof rest.device !== 'string')
262
+ throw new Error(
263
+ `${what}: a device mount names its device's rule set in "device", as supply-24v (got ${shown(rest.device)})`,
264
+ );
265
+ try {
266
+ rest.device = peekRuleSet(rest.device);
267
+ } catch (e) {
268
+ throw new Error(`${what}: device: ${e.message}`);
269
+ }
150
270
  }
151
- if (o.parts ? part != null && !o.parts.includes(part) : part != null) throw new Error(`${what}: ${o.parts ? `part is ${o.parts.join(' or ')}` : `a ${kind} has one part: leave part out`} (got ${shown(part)})`);
152
- if (o.profile !== false && typeof profile !== 'string') throw new Error(`${what}: a ${kind} is drawn for a profile: give "profile", as 2020-misumi-hfs5 (got ${shown(profile)})`);
153
- if (o.profile === false && profile != null) throw new Error(`${what}: a ${kind} is drawn for no profile: leave profile out`);
271
+ if (o.parts ? part != null && !o.parts.includes(part) : part != null)
272
+ throw new Error(
273
+ `${what}: ${o.parts ? `part is ${o.parts.join(' or ')}` : `a ${kind} has one part: leave part out`} (got ${shown(part)})`,
274
+ );
275
+ if (o.profile !== false && typeof profile !== 'string')
276
+ throw new Error(
277
+ `${what}: a ${kind} is drawn for a profile: give "profile", as 2020-misumi-hfs5 (got ${shown(profile)})`,
278
+ );
279
+ if (o.profile === false && profile != null)
280
+ throw new Error(`${what}: a ${kind} is drawn for no profile: leave profile out`);
154
281
  // (a gasket strip is PETG, which springs back, unless the item says otherwise; the rest take the project's plastic)
155
282
  try {
156
- const m = o.profile === false ? frames[model]({ ...(kind === 'gasket-strip' ? {} : { material }), ...rest }) : frames[model](profile, { given: givenFor(context, profile), material, ...rest });
283
+ const m =
284
+ o.profile === false
285
+ ? frames[model]({ ...(kind === 'gasket-strip' ? {} : { material }), ...rest })
286
+ : frames[model](profile, { given: givenFor(context, profile), material, ...rest });
157
287
  // (a printed carrier in a slot is its own kind of model: named here as a fitting, with the nut or insert it holds to buy)
158
- if (kind === 'nut-carrier') return { ...m, fitting: 'nut-carrier', hardware: [{ kind: m.holds === 'insert' ? 'insert' : 'nut', name: `${m.thread} ${m.holds === 'insert' ? 'heat-set insert' : 'hex nut'}`, thread: m.thread, count: m.count ?? 1, why: `held in the carrier, ${m.holds === 'insert' ? 'pressed in from below' : 'slid in from the side'}` }] };
288
+ if (kind === 'nut-carrier')
289
+ return {
290
+ ...m,
291
+ fitting: 'nut-carrier',
292
+ hardware: [
293
+ {
294
+ kind: m.holds === 'insert' ? 'insert' : 'nut',
295
+ name: `${m.thread} ${m.holds === 'insert' ? 'heat-set insert' : 'hex nut'}`,
296
+ thread: m.thread,
297
+ count: m.count ?? 1,
298
+ why: `held in the carrier, ${m.holds === 'insert' ? 'pressed in from below' : 'slid in from the side'}`,
299
+ },
300
+ ],
301
+ };
159
302
  return m;
160
- } catch (e) { throw new Error(`${what}: ${String(e?.message ?? e).replace(/^\w+: /, '')}`); }
303
+ } catch (e) {
304
+ throw new Error(`${what}: ${String(e?.message ?? e).replace(/^\w+: /, '')}`);
305
+ }
161
306
  }
162
307
 
163
308
  /**
@@ -168,23 +313,82 @@ function moreModel(spec, context, material, what) {
168
313
  export async function fittingBuilt(it, id, context, material = 'pla') {
169
314
  // "pose": "print" lays it as it prints, for a plate (cad plates writes it so); the model is the same either way
170
315
  const { pose = 'fit', ...spec } = it.fitting ?? {};
171
- if (pose !== 'fit' && pose !== 'print') throw new Error(`item ${id}: fitting.pose is fit (in its place, the default) or print (as it prints, for a plate) (got ${shown(pose)})`);
316
+ if (pose !== 'fit' && pose !== 'print')
317
+ throw new Error(
318
+ `item ${id}: fitting.pose is fit (in its place, the default) or print (as it prints, for a plate) (got ${shown(pose)})`,
319
+ );
172
320
  const m = fittingModel(spec, context, material, `item ${id}`);
173
321
  // joined and cut by Manifold where the workspace has it, so the solid is watertight for the overlap check (JSCAD's
174
322
  // booleans leave seams that Manifold cannot read, and JSCAD's own intersection then misreads a head in its seat)
175
- let ops = null; try { ops = await booleans('manifold'); } catch {}
323
+ let ops = null;
324
+ try {
325
+ ops = await booleans('manifold');
326
+ } catch {
327
+ // (Manifold isn't installed: JSCAD's own booleans cut the fitting)
328
+ }
176
329
  if (MORE[it.fitting.kind]) return moreBuilt(it, id, m, ops, pose);
177
- const draw = (o) => { const f = m.fitting === 'bracket' ? bracket : plate; try { return f(m, { ...o, ...(ops ? { ops } : {}) }); } catch { return f(m, o); } };
330
+ const draw = (o) => {
331
+ const f = m.fitting === 'bracket' ? bracket : plate;
332
+ try {
333
+ return f(m, { ...o, ...(ops ? { ops } : {}) });
334
+ } catch {
335
+ return f(m, o);
336
+ }
337
+ };
178
338
  const parts = named({ body: draw({ pose }) }, { body: { label: m.title } });
179
339
  // its tongues stand in the slots, inside the beams' envelopes: the overlap check measures the body without them
180
340
  if (pose === 'fit') parts[0].collide = named({ body: draw({ pose: 'fit', tongues: false }) }, {})[0].geometry;
181
341
  // an anchor on each screw's axis at its head's seat, z out of the fitting toward the head: b1, b2 .. into b; a1 .. into a
182
- const count = { a: 0, b: 0 }, anchors = Object.fromEntries(m.screws.map((sc) => [`${sc.leg}${++count[sc.leg]}`, { at: m.fitting === 'bracket' ? sc.at : [sc.at[0], sc.at[1], m.thickness], axis: sc.axis.map((c) => (c ? -c : 0)) }]));
183
- const values = { thickness: m.thickness, width: m.width, grams: m.grams, margin: m.margin, stiffness: m.stiffness.bending, load: m.load.force, ...(m.leg ? { leg: m.leg } : { arm: m.arm }) };
184
- const entries = Object.entries({ thickness: ['mm', 'sized from the load'], grams: ['g', 'its mass'], margin: ['×', 'its strength over the peak stress at the load, by finite elements'], stiffness: ['N mm/rad', 'its own bending stiffness about the joint, by finite elements'] })
185
- .map(([k, [unit, rule]]) => ({ name: `${m.name}.${k}`, value: values[k], unit, rule: `The printed fitting's ${rule}`, kind: 'derived', source: '@rulecad/frames fitting.mjs', checked: '2026-11-17', set: m.name }));
186
- const hash = crypto.createHash('sha256').update(JSON.stringify([it.fitting, material, m.name, m.thickness, m.grams])).digest('hex').slice(0, 16);
187
- const b = { object: { name: m.name, title: m.title, role: 'part', version: '0.0.0', anchors }, values, entries, deps: [], units: {}, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash };
342
+ const count = { a: 0, b: 0 },
343
+ anchors = Object.fromEntries(
344
+ m.screws.map((sc) => [
345
+ `${sc.leg}${++count[sc.leg]}`,
346
+ {
347
+ at: m.fitting === 'bracket' ? sc.at : [sc.at[0], sc.at[1], m.thickness],
348
+ axis: sc.axis.map((c) => (c ? -c : 0)),
349
+ },
350
+ ]),
351
+ );
352
+ const values = {
353
+ thickness: m.thickness,
354
+ width: m.width,
355
+ grams: m.grams,
356
+ margin: m.margin,
357
+ stiffness: m.stiffness.bending,
358
+ load: m.load.force,
359
+ ...(m.leg ? { leg: m.leg } : { arm: m.arm }),
360
+ };
361
+ const entries = Object.entries({
362
+ thickness: ['mm', 'sized from the load'],
363
+ grams: ['g', 'its mass'],
364
+ margin: ['×', 'its strength over the peak stress at the load, by finite elements'],
365
+ stiffness: ['N mm/rad', 'its own bending stiffness about the joint, by finite elements'],
366
+ }).map(([k, [unit, rule]]) => ({
367
+ name: `${m.name}.${k}`,
368
+ value: values[k],
369
+ unit,
370
+ rule: `The printed fitting's ${rule}`,
371
+ kind: 'derived',
372
+ source: '@rulecad/frames fitting.mjs',
373
+ checked: '2026-11-17',
374
+ set: m.name,
375
+ }));
376
+ const hash = crypto
377
+ .createHash('sha256')
378
+ .update(JSON.stringify([it.fitting, material, m.name, m.thickness, m.grams]))
379
+ .digest('hex')
380
+ .slice(0, 16);
381
+ const b = {
382
+ object: { name: m.name, title: m.title, role: 'part', version: '0.0.0', anchors },
383
+ values,
384
+ entries,
385
+ deps: [],
386
+ units: {},
387
+ parts,
388
+ polygons: parts.flatMap((p) => p.polygons),
389
+ triangles: parts.flatMap((p) => p.triangles),
390
+ hash,
391
+ };
188
392
  return { key: `fitting:${id}:${hash}`, objName: `fitting:${m.name}`, b, version: '0.0.0', role: 'part', fitting: m };
189
393
  }
190
394
 
@@ -192,27 +396,77 @@ export async function fittingBuilt(it, id, context, material = 'pla') {
192
396
  // an anchor on each screw's axis at its head (b1, b2 .. for screws into a slot or a bore; d1, d2 .. for a hinge's
193
397
  // door leaf's, through the door); a hinge's door leaf and a levelling foot's pad carry no findings or hardware of their own
194
398
  function moreBuilt(it, id, m, ops, pose = 'fit') {
195
- const [, solid, o = {}] = MORE[it.fitting.kind], part = it.fitting.part ?? o.parts?.[0], second = o.parts && part !== o.parts[0];
196
- const drawn = o.pose?.[pose] ?? pose, draw = (x) => { const f = (y) => frames[solid](m, { pose: drawn, ...(part ? { part } : {}), ...x, ...y }); try { return f(ops ? { ops } : {}); } catch { return f({}); } };
399
+ const [, solid, o = {}] = MORE[it.fitting.kind],
400
+ part = it.fitting.part ?? o.parts?.[0],
401
+ second = o.parts && part !== o.parts[0];
402
+ const drawn = o.pose?.[pose] ?? pose,
403
+ draw = (x) => {
404
+ const f = (y) => frames[solid](m, { pose: drawn, ...(part ? { part } : {}), ...x, ...y });
405
+ try {
406
+ return f(ops ? { ops } : {});
407
+ } catch {
408
+ return f({});
409
+ }
410
+ };
197
411
  const parts = named({ body: draw({}) }, { body: { label: `${m.title}${part ? `, ${part}` : ''}` } });
198
- if (TONGUED.includes(m.fitting) && pose === 'fit') parts[0].collide = named({ body: draw({ tongues: false }) }, {})[0].geometry;
199
- if (IN_SLOT.includes(m.fitting) && pose === 'fit') { const { intersect } = jscad.booleans, { cuboid } = jscad.primitives, above = intersect(parts[0].geometry, cuboid({ size: [1e4, 1e4, 1e3], center: [0, 0, 500] })); parts[0].collide = above; }
200
- const list = it.fitting.kind === 'hinge' && part === 'door' ? m.door.map((q, k) => [`d${k + 1}`, q]) : (m.screws ?? []).filter((q) => q.into !== 'castor' && q.into !== 'pilot').map((q, k) => [`b${k + 1}`, q]);
201
- const anchors = { ...Object.fromEntries(list.map(([n, q]) => [n, { at: q.at, axis: q.axis.map((c) => (c ? -c : 0)) }])), ...(m.anchors ?? {}) }; // (and its own: a mount's device and screws, a clip's cable)
202
- const values = { grams: m.grams, ...(m.margin != null && Number.isFinite(m.margin) ? { margin: m.margin } : {}), ...(m.load?.force ? { load: m.load.force } : {}) };
203
- const hash = crypto.createHash('sha256').update(JSON.stringify([it.fitting, m.name, m.grams, part])).digest('hex').slice(0, 16);
204
- const b = { object: { name: `${m.name}${part ? `-${part}` : ''}`, title: m.title, role: 'part', version: '0.0.0', anchors }, values, entries: [], deps: [], units: {}, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash };
412
+ if (TONGUED.includes(m.fitting) && pose === 'fit')
413
+ parts[0].collide = named({ body: draw({ tongues: false }) }, {})[0].geometry;
414
+ if (IN_SLOT.includes(m.fitting) && pose === 'fit') {
415
+ const { intersect } = jscad.booleans,
416
+ { cuboid } = jscad.primitives,
417
+ above = intersect(parts[0].geometry, cuboid({ size: [1e4, 1e4, 1e3], center: [0, 0, 500] }));
418
+ parts[0].collide = above;
419
+ }
420
+ const list =
421
+ it.fitting.kind === 'hinge' && part === 'door'
422
+ ? m.door.map((q, k) => [`d${k + 1}`, q])
423
+ : (m.screws ?? []).filter((q) => q.into !== 'castor' && q.into !== 'pilot').map((q, k) => [`b${k + 1}`, q]);
424
+ const anchors = {
425
+ ...Object.fromEntries(list.map(([n, q]) => [n, { at: q.at, axis: q.axis.map((c) => (c ? -c : 0)) }])),
426
+ ...(m.anchors ?? {}),
427
+ }; // (and its own: a mount's device and screws, a clip's cable)
428
+ const values = {
429
+ grams: m.grams,
430
+ ...(m.margin != null && Number.isFinite(m.margin) ? { margin: m.margin } : {}),
431
+ ...(m.load?.force ? { load: m.load.force } : {}),
432
+ };
433
+ const hash = crypto
434
+ .createHash('sha256')
435
+ .update(JSON.stringify([it.fitting, m.name, m.grams, part]))
436
+ .digest('hex')
437
+ .slice(0, 16);
438
+ const b = {
439
+ object: { name: `${m.name}${part ? `-${part}` : ''}`, title: m.title, role: 'part', version: '0.0.0', anchors },
440
+ values,
441
+ entries: [],
442
+ deps: [],
443
+ units: {},
444
+ parts,
445
+ polygons: parts.flatMap((p) => p.polygons),
446
+ triangles: parts.flatMap((p) => p.triangles),
447
+ hash,
448
+ };
205
449
  const model = second ? { ...m, findings: [], hardware: [] } : m;
206
- return { key: `fitting:${id}:${hash}`, objName: `fitting:${m.name}${part ? `-${part}` : ''}`, b, version: '0.0.0', role: 'part', fitting: model };
450
+ return {
451
+ key: `fitting:${id}:${hash}`,
452
+ objName: `fitting:${m.name}${part ? `-${part}` : ''}`,
453
+ b,
454
+ version: '0.0.0',
455
+ role: 'part',
456
+ fitting: model,
457
+ };
207
458
  }
208
459
 
209
460
  // ---------- a join's printed fitting, placed ----------
210
- const col = (f, k) => [f[k], f[4 + k], f[8 + k]], org = (f) => [f[3], f[7], f[11]];
211
- 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]];
461
+ const col = (f, k) => [f[k], f[4 + k], f[8 + k]];
462
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
463
+ sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
212
464
  const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
213
- const world = (f, p) => [0, 1, 2].map((k) => f[4 * k] * p[0] + f[4 * k + 1] * p[1] + f[4 * k + 2] * p[2] + f[4 * k + 3]);
465
+ const world = (f, p) =>
466
+ [0, 1, 2].map((k) => f[4 * k] * p[0] + f[4 * k + 1] * p[1] + f[4 * k + 2] * p[2] + f[4 * k + 3]);
214
467
  const turn = (f, v) => [0, 1, 2].map((k) => f[4 * k] * v[0] + f[4 * k + 1] * v[1] + f[4 * k + 2] * v[2]);
215
- const mm = (x) => String(+Number(x).toFixed(2)), r3 = (x) => +x.toFixed(3);
468
+ const mm = (x) => String(+Number(x).toFixed(2)),
469
+ r3 = (x) => +x.toFixed(3);
216
470
  // a place's face as slotSide takes it: top, or top.2 where the face has two slots
217
471
  const faceOf = (B, place) => (B.places.filter((q) => q.face === place.face).length > 1 ? place.name : place.face);
218
472
 
@@ -225,57 +479,172 @@ const faceOf = (B, place) => (B.places.filter((q) => q.face === place.face).leng
225
479
  * @returns {{ item: object, fasten: object[], model: object, stiffness: object }}
226
480
  */
227
481
  export function joinFitting(j, i, { ia, ib, A, B, m, ends, place: placeOf }, num, context, material, ids) {
228
- const what = `join ${i + 1}`, label = j.note || `${j.kind} join of ${j.a} to ${j.b}`, bm = m.fitting?.bought ?? null, made = bm ? bm.set : `a printed ${j.kind}`;
229
- const fa = placeOf(ia, num), fb = placeOf(ib, num);
230
- if (!fa || !fb) throw new Error(`${what}: ${made} is placed from where the beams are: place ${!fa ? ia.id : ib.id} by its ends (from, to)`);
231
- const free = (base) => { let n = base, k = 2; while (ids.has(n)) n = `${base}-${k++}`; ids.add(n); return n; };
482
+ const what = `join ${i + 1}`,
483
+ label = j.note || `${j.kind} join of ${j.a} to ${j.b}`,
484
+ bm = m.fitting?.bought ?? null,
485
+ made = bm ? bm.set : `a printed ${j.kind}`;
486
+ const fa = placeOf(ia, num),
487
+ fb = placeOf(ib, num);
488
+ if (!fa || !fb)
489
+ throw new Error(
490
+ `${what}: ${made} is placed from where the beams are: place ${!fa ? ia.id : ib.id} by its ends (from, to)`,
491
+ );
492
+ const free = (base) => {
493
+ let n = base,
494
+ k = 2;
495
+ while (ids.has(n)) n = `${base}-${k++}`;
496
+ ids.add(n);
497
+ return n;
498
+ };
232
499
  // a bought anchor connector: its post along a's axis from b's face, at the place on b the join names
233
500
  if (bm && j.kind === 'anchor') {
234
501
  const id = free(`${ia.id}-${ib.id}-${j.kind}`);
235
- return { item: { id, bought: bm.set, at: `${ib.id}.${m.b.place}@${r3(m.b.distance)}`, join: i }, fasten: [], model: bm };
502
+ return {
503
+ item: { id, bought: bm.set, at: `${ib.id}.${m.b.place}@${r3(m.b.distance)}`, join: i },
504
+ fasten: [],
505
+ model: bm,
506
+ };
236
507
  }
237
508
  // its screws, each by the set's thread, length and head, into the set's nut where it names one (a corner bracket's
238
509
  // and a plate's); an inner connector's grub screws are part of it
239
- const boughtFasten = (id, legs) => legs.map(([leg, beam, place]) => ({ screw: `${bm.thread}${bm.length != null ? `x${bm.length}` : ''} ${bm.head}`, through: [id], into: `${beam}.${place}`, at: bm.screws.filter((q) => q.leg === leg).map((_, k) => `${id}.${leg}${k + 1}`), note: `${label}: ${bm.set} into ${beam}`, join: i, ...(bm.nutKind ? { nut: bm.nutKind } : {}) }));
510
+ const boughtFasten = (id, legs) =>
511
+ legs.map(([leg, beam, place]) => ({
512
+ screw: `${bm.thread}${bm.length != null ? `x${bm.length}` : ''} ${bm.head}`,
513
+ through: [id],
514
+ into: `${beam}.${place}`,
515
+ at: bm.screws.filter((q) => q.leg === leg).map((_, k) => `${id}.${leg}${k + 1}`),
516
+ note: `${label}: ${bm.set} into ${beam}`,
517
+ join: i,
518
+ ...(bm.nutKind ? { nut: bm.nutKind } : {}),
519
+ }));
240
520
  if (j.kind === 'bracket' || j.kind === 'hidden') {
241
- const bp = B.places.find((q) => q.name === m.b.place), d = m.b.distance, ub = col(fb, 2), nb = turn(fb, [...bp.normal, 0]);
242
- const P = world(fb, [bp.at[0], bp.at[1], d]), roomB = B.length - d, sign = roomB >= d ? 1 : -1, dir = ub.map((c) => c * sign);
521
+ const bp = B.places.find((q) => q.name === m.b.place),
522
+ d = m.b.distance,
523
+ ub = col(fb, 2),
524
+ nb = turn(fb, [...bp.normal, 0]);
525
+ const P = world(fb, [bp.at[0], bp.at[1], d]),
526
+ roomB = B.length - d,
527
+ sign = roomB >= d ? 1 : -1,
528
+ dir = ub.map((c) => c * sign);
243
529
  // a's face that looks along b, toward the side with more room; of its slots, the one in the bracket's plane
244
- const z = cross(dir, nb), faces = A.places.filter((q) => q.slot && dot(turn(fa, [...q.normal, 0]), dir) > 1 - 1e-6);
245
- if (!faces.length) throw new Error(`${what}: a printed bracket lies on a face of ${ia.id} that looks along ${ib.id}, and none of ${ia.id}'s slotted faces does: turn ${ia.id} with roll so one faces along ${ib.id}`);
246
- const ap = faces.map((q) => ({ q, Q: world(fa, [q.at[0], q.at[1], 0]) })).sort((x, y) => Math.abs(dot(sub(x.Q, P), z)) - Math.abs(dot(sub(y.Q, P), z)))[0];
247
- const off = dot(sub(ap.Q, P), dir), at = d + sign * off, spec = { kind: 'bracket', profile: B.profile.name, ...(A.profile.name !== B.profile.name ? { other: A.profile.name } : {}), face: faceOf(B, bp), otherFace: faceOf(A, ap.q), ...(j.brace != null ? { brace: j.brace } : {}), ...(j.load != null ? { load: j.load } : {}), ...(j.nut ? { nut: j.nut } : {}) };
248
- const fm = bm ?? fittingModel(spec, context, material, what), room = sign > 0 ? B.length - at : at, endA = ends.a.rest[0], aRoom = A.length, said = bm ? `${bm.set}'s` : 'a printed bracket\'s';
249
- if (room < fm.leg - 1e-6) throw new Error(`${what}: ${said} ${mm(fm.leg)} mm leg runs ${mm(fm.leg - room)} mm past ${ib.id}'s end ${sign > 0 ? 'b' : 'a'}: it goes on the side of ${ia.id} with more of ${ib.id}, and there is only ${mm(room)} mm there. A gusset or a blind join will do`);
250
- if (aRoom < (fm.legA ?? fm.leg) - 1e-6) throw new Error(`${what}: ${said} ${mm(fm.legA ?? fm.leg)} mm leg is longer than ${ia.id} (${mm(aRoom)} mm)`);
530
+ const z = cross(dir, nb),
531
+ faces = A.places.filter((q) => q.slot && dot(turn(fa, [...q.normal, 0]), dir) > 1 - 1e-6);
532
+ if (!faces.length)
533
+ throw new Error(
534
+ `${what}: a printed bracket lies on a face of ${ia.id} that looks along ${ib.id}, and none of ${ia.id}'s slotted faces does: turn ${ia.id} with roll so one faces along ${ib.id}`,
535
+ );
536
+ const ap = faces
537
+ .map((q) => ({ q, Q: world(fa, [q.at[0], q.at[1], 0]) }))
538
+ .sort((x, y) => Math.abs(dot(sub(x.Q, P), z)) - Math.abs(dot(sub(y.Q, P), z)))[0];
539
+ const off = dot(sub(ap.Q, P), dir),
540
+ at = d + sign * off,
541
+ spec = {
542
+ kind: 'bracket',
543
+ profile: B.profile.name,
544
+ ...(A.profile.name !== B.profile.name ? { other: A.profile.name } : {}),
545
+ face: faceOf(B, bp),
546
+ otherFace: faceOf(A, ap.q),
547
+ ...(j.brace != null ? { brace: j.brace } : {}),
548
+ ...(j.load != null ? { load: j.load } : {}),
549
+ ...(j.nut ? { nut: j.nut } : {}),
550
+ };
551
+ const fm = bm ?? fittingModel(spec, context, material, what),
552
+ room = sign > 0 ? B.length - at : at,
553
+ endA = ends.a.rest[0],
554
+ aRoom = A.length,
555
+ said = bm ? `${bm.set}'s` : "a printed bracket's";
556
+ if (room < fm.leg - 1e-6)
557
+ throw new Error(
558
+ `${what}: ${said} ${mm(fm.leg)} mm leg runs ${mm(fm.leg - room)} mm past ${ib.id}'s end ${sign > 0 ? 'b' : 'a'}: it goes on the side of ${ia.id} with more of ${ib.id}, and there is only ${mm(room)} mm there. A gusset or a blind join will do`,
559
+ );
560
+ if (aRoom < (fm.legA ?? fm.leg) - 1e-6)
561
+ throw new Error(`${what}: ${said} ${mm(fm.legA ?? fm.leg)} mm leg is longer than ${ia.id} (${mm(aRoom)} mm)`);
251
562
  const id = free(`${ia.id}-${ib.id}-${bm ? j.kind : 'bracket'}`);
252
563
  if (bm) {
253
- const item = { id, bought: bm.set, at: `${ib.id}.${bp.name}@${r3(at)}`, rotate: sign > 0 ? [90, 0, 0] : [90, 0, 180], join: i };
254
- return { item, fasten: j.kind === 'hidden' ? [] : boughtFasten(id, [['b', ib.id, bp.name], ['a', ia.id, ap.q.name]]), model: bm, side: sign > 0 ? 'b' : 'a', endA };
564
+ const item = {
565
+ id,
566
+ bought: bm.set,
567
+ at: `${ib.id}.${bp.name}@${r3(at)}`,
568
+ rotate: sign > 0 ? [90, 0, 0] : [90, 0, 180],
569
+ join: i,
570
+ };
571
+ return {
572
+ item,
573
+ fasten:
574
+ j.kind === 'hidden'
575
+ ? []
576
+ : boughtFasten(id, [
577
+ ['b', ib.id, bp.name],
578
+ ['a', ia.id, ap.q.name],
579
+ ]),
580
+ model: bm,
581
+ side: sign > 0 ? 'b' : 'a',
582
+ endA,
583
+ };
255
584
  }
256
- const item = { id, fitting: spec, at: `${ib.id}.${bp.name}@${r3(at)}`, rotate: sign > 0 ? [90, 0, 0] : [90, 0, 180], join: i };
585
+ const item = {
586
+ id,
587
+ fitting: spec,
588
+ at: `${ib.id}.${bp.name}@${r3(at)}`,
589
+ rotate: sign > 0 ? [90, 0, 0] : [90, 0, 180],
590
+ join: i,
591
+ };
257
592
  const screw = `${fm.thread} ${fm.head}`;
258
593
  // (each into the slot nut the bracket was drawn for, so the screw it was thickened for is the one chosen)
259
- const fasten = [{ screw, through: [id], into: `${ib.id}.${bp.name}`, at: [`${id}.b1`], note: `${label}: the bracket into ${ib.id}`, join: i, nut: j.nut ?? fm.screws[0].nutKind },
260
- { screw, through: [id], into: `${ia.id}.${ap.q.name}`, at: [`${id}.a1`], note: `${label}: the bracket into ${ia.id}`, join: i, nut: j.nut ?? fm.screws[1].nutKind }];
594
+ const fasten = [
595
+ {
596
+ screw,
597
+ through: [id],
598
+ into: `${ib.id}.${bp.name}`,
599
+ at: [`${id}.b1`],
600
+ note: `${label}: the bracket into ${ib.id}`,
601
+ join: i,
602
+ nut: j.nut ?? fm.screws[0].nutKind,
603
+ },
604
+ {
605
+ screw,
606
+ through: [id],
607
+ into: `${ia.id}.${ap.q.name}`,
608
+ at: [`${id}.a1`],
609
+ note: `${label}: the bracket into ${ia.id}`,
610
+ join: i,
611
+ nut: j.nut ?? fm.screws[1].nutKind,
612
+ },
613
+ ];
261
614
  return { item, fasten, model: fm, side: sign > 0 ? 'b' : 'a', endA };
262
615
  }
263
616
  // a plate (a gusset, or a splice plate): on a face of each beam, the two in one plane. Its frame: x along b away from
264
617
  // the joint (a gusset's toward b's end with more room; a splice's into b), y along a away from b (a splice's across),
265
618
  // z out of the faces; it sits at an address on b, turned in that frame
266
- const splice = j.kind === 'splice', ua = col(fa, 2).map((c) => (ends.a.rest[0] === 'a' ? c : -c)), ub = col(fb, 2);
619
+ const splice = j.kind === 'splice',
620
+ ua = col(fa, 2).map((c) => (ends.a.rest[0] === 'a' ? c : -c)),
621
+ ub = col(fb, 2);
267
622
  const d = splice ? (m.b.end === 'a' ? 0 : B.length) : m.b.distance;
268
- let x, y, n, shapeAt = null;
623
+ let x,
624
+ y,
625
+ n,
626
+ shapeAt = null;
269
627
  if (splice) {
270
628
  x = ub.map((c) => (m.b.end === 'a' ? c : -c));
271
- const bq = B.places.find((q) => q.slot && Math.abs(dot(turn(fb, [...q.normal, 0]), x)) < 1e-6 && A.places.some((r) => r.slot && dot(turn(fa, [...r.normal, 0]), turn(fb, [...q.normal, 0])) > 1 - 1e-6));
272
- if (!bq) throw new Error(`${what}: a printed splice plate lies on a slotted face of both beams, in one plane, and ${ia.id} and ${ib.id} share none`);
273
- n = turn(fb, [...bq.normal, 0]); y = cross(n, x);
629
+ const bq = B.places.find(
630
+ (q) =>
631
+ q.slot &&
632
+ Math.abs(dot(turn(fb, [...q.normal, 0]), x)) < 1e-6 &&
633
+ A.places.some((r) => r.slot && dot(turn(fa, [...r.normal, 0]), turn(fb, [...q.normal, 0])) > 1 - 1e-6),
634
+ );
635
+ if (!bq)
636
+ throw new Error(
637
+ `${what}: a printed splice plate lies on a slotted face of both beams, in one plane, and ${ia.id} and ${ib.id} share none`,
638
+ );
639
+ n = turn(fb, [...bq.normal, 0]);
640
+ y = cross(n, x);
274
641
  } else {
275
642
  const half = Math.max(A.profile.width, A.profile.height) / 2;
276
643
  const room = { b: B.length - d - half, a: d - half };
277
644
  shapeAt = { room };
278
- x = ub.map((c) => (room.b >= room.a ? c : -c)); y = ua; n = cross(x, y);
645
+ x = ub.map((c) => (room.b >= room.a ? c : -c));
646
+ y = ua;
647
+ n = cross(x, y);
279
648
  }
280
649
  // a gusset on the other face of b (j.face): the same L turned over its diagonal, its arm drawn for b along a and its
281
650
  // arm drawn for a along b, so it lies on the faces looking along -n (a mirror image of the L is itself turned so)
@@ -284,44 +653,139 @@ export function joinFitting(j, i, { ia, ib, A, B, m, ends, place: placeOf }, num
284
653
  const want = B.places.find((q) => q.slot && (q.name === j.face || (q.face === j.face && q.name.endsWith('.1'))));
285
654
  const along = want ? dot(turn(fb, [...want.normal, 0]), n) : 0;
286
655
  if (!want || Math.abs(Math.abs(along) - 1) > 1e-6) {
287
- const can = B.places.filter((q) => q.slot && Math.abs(Math.abs(dot(turn(fb, [...q.normal, 0]), n)) - 1) < 1e-6).map((q) => faceOf(B, q));
288
- throw new Error(`${what}: face is the face of ${ib.id} a printed gusset lies on, square to ${ia.id}: ${[...new Set(can)].join(' or ') || 'none of its slotted faces is'} (got ${JSON.stringify(j.face)})`);
656
+ const can = B.places
657
+ .filter((q) => q.slot && Math.abs(Math.abs(dot(turn(fb, [...q.normal, 0]), n)) - 1) < 1e-6)
658
+ .map((q) => faceOf(B, q));
659
+ throw new Error(
660
+ `${what}: face is the face of ${ib.id} a printed gusset lies on, square to ${ia.id}: ${[...new Set(can)].join(' or ') || 'none of its slotted faces is'} (got ${JSON.stringify(j.face)})`,
661
+ );
662
+ }
663
+ if (along < 0) {
664
+ flip = true;
665
+ n = n.map((c) => -c);
289
666
  }
290
- if (along < 0) { flip = true; n = n.map((c) => -c); }
291
667
  }
292
- const bq = B.places.find((q) => q.slot && dot(turn(fb, [...q.normal, 0]), n) > 1 - 1e-6), aq = A.places.find((q) => q.slot && dot(turn(fa, [...q.normal, 0]), n) > 1 - 1e-6);
293
- if (!bq || !aq) throw new Error(`${what}: a printed ${splice ? 'splice plate' : 'gusset'} lies on a slotted face of both beams that looks the same way, and ${!bq ? ib.id : ia.id} has none that does: turn it with roll`);
294
- const Pb = world(fb, [bq.at[0], bq.at[1], d]), Qa = world(fa, [aq.at[0], aq.at[1], 0]), apart = dot(sub(Qa, Pb), n);
295
- if (Math.abs(apart) > 0.05) throw new Error(`${what}: a printed ${splice ? 'splice plate' : 'gusset'} lies flat on both beams, and ${ia.id}'s ${aq.face} face stands ${mm(Math.abs(apart))} mm ${apart > 0 ? 'proud of' : 'below'} ${ib.id}'s ${bq.face} face`);
296
- const spec0 = { kind: splice ? 'splice' : 'gusset', profile: B.profile.name, ...(A.profile.name !== B.profile.name ? { other: A.profile.name } : {}), face: faceOf(B, bq), ...(j.load != null ? { load: j.load } : {}), ...(j.nut ? { nut: j.nut } : {}) };
297
- let fm = bm ?? fittingModel({ ...spec0, ...(splice ? {} : { shape: 'L' }) }, context, material, what), shape = bm?.shape ?? 'L';
668
+ const bq = B.places.find((q) => q.slot && dot(turn(fb, [...q.normal, 0]), n) > 1 - 1e-6),
669
+ aq = A.places.find((q) => q.slot && dot(turn(fa, [...q.normal, 0]), n) > 1 - 1e-6);
670
+ if (!bq || !aq)
671
+ throw new Error(
672
+ `${what}: a printed ${splice ? 'splice plate' : 'gusset'} lies on a slotted face of both beams that looks the same way, and ${!bq ? ib.id : ia.id} has none that does: turn it with roll`,
673
+ );
674
+ const Pb = world(fb, [bq.at[0], bq.at[1], d]),
675
+ Qa = world(fa, [aq.at[0], aq.at[1], 0]),
676
+ apart = dot(sub(Qa, Pb), n);
677
+ if (Math.abs(apart) > 0.05)
678
+ throw new Error(
679
+ `${what}: a printed ${splice ? 'splice plate' : 'gusset'} lies flat on both beams, and ${ia.id}'s ${aq.face} face stands ${mm(Math.abs(apart))} mm ${apart > 0 ? 'proud of' : 'below'} ${ib.id}'s ${bq.face} face`,
680
+ );
681
+ const spec0 = {
682
+ kind: splice ? 'splice' : 'gusset',
683
+ profile: B.profile.name,
684
+ ...(A.profile.name !== B.profile.name ? { other: A.profile.name } : {}),
685
+ face: faceOf(B, bq),
686
+ ...(j.load != null ? { load: j.load } : {}),
687
+ ...(j.nut ? { nut: j.nut } : {}),
688
+ };
689
+ let fm = bm ?? fittingModel({ ...spec0, ...(splice ? {} : { shape: 'L' }) }, context, material, what),
690
+ shape = bm?.shape ?? 'L';
298
691
  if (bm) {
299
692
  // a bought plate's shape is its set's: a T needs room along b both sides of a, an L on one
300
- const { room } = shapeAt ?? { room: { a: Infinity, b: Infinity } }, xs = fm.outline.map((q) => q[0]), reach = Math.max(...xs.map(Math.abs));
301
- if (shape === 'T' && Math.min(room.a, room.b) + (A.profile.width / 2) < reach - 1e-6) throw new Error(`${what}: ${bm.set} is a T, ${mm(2 * reach)} mm along ${ib.id}, and there is ${mm(Math.min(room.a, room.b))} mm on one side of ${ia.id}: an L or a bracket will do`);
302
- const id = free(`${ia.id}-${ib.id}-${splice ? 'splice' : 'gusset'}`), along = dot(x, ub) > 0;
303
- const item = { id, bought: bm.set, at: `${ib.id}.${bq.name}@${r3(d)}`, ...(along ? {} : { rotate: [0, 0, 180] }), join: i };
304
- return { item, fasten: boughtFasten(id, [['b', ib.id, bq.name], ['a', ia.id, aq.name]]), model: bm };
693
+ const { room } = shapeAt ?? { room: { a: Infinity, b: Infinity } },
694
+ xs = fm.outline.map((q) => q[0]),
695
+ reach = Math.max(...xs.map(Math.abs));
696
+ if (shape === 'T' && Math.min(room.a, room.b) + A.profile.width / 2 < reach - 1e-6)
697
+ throw new Error(
698
+ `${what}: ${bm.set} is a T, ${mm(2 * reach)} mm along ${ib.id}, and there is ${mm(Math.min(room.a, room.b))} mm on one side of ${ia.id}: an L or a bracket will do`,
699
+ );
700
+ const id = free(`${ia.id}-${ib.id}-${splice ? 'splice' : 'gusset'}`),
701
+ along = dot(x, ub) > 0;
702
+ const item = {
703
+ id,
704
+ bought: bm.set,
705
+ at: `${ib.id}.${bq.name}@${r3(d)}`,
706
+ ...(along ? {} : { rotate: [0, 0, 180] }),
707
+ join: i,
708
+ };
709
+ return {
710
+ item,
711
+ fasten: boughtFasten(id, [
712
+ ['b', ib.id, bq.name],
713
+ ['a', ia.id, aq.name],
714
+ ]),
715
+ model: bm,
716
+ };
305
717
  }
306
- if (flip && (A.profile.name !== B.profile.name || aq.slot !== bq.slot)) throw new Error(`${what}: a printed gusset turned onto ${ib.id}'s ${j.face} face puts the arm drawn for ${ib.id}'s slot in ${ia.id}'s, and ${ia.id}'s ${aq.face} face (${aq.slot}) and ${ib.id}'s ${bq.face} face (${bq.slot}) differ: leave face out, or join with a bracket`);
718
+ if (flip && (A.profile.name !== B.profile.name || aq.slot !== bq.slot))
719
+ throw new Error(
720
+ `${what}: a printed gusset turned onto ${ib.id}'s ${j.face} face puts the arm drawn for ${ib.id}'s slot in ${ia.id}'s, and ${ia.id}'s ${aq.face} face (${aq.slot}) and ${ib.id}'s ${bq.face} face (${bq.slot}) differ: leave face out, or join with a bracket`,
721
+ );
307
722
  if (!splice) {
308
- const reach = fm.width / 2 + fm.arm, { room } = shapeAt;
723
+ const reach = fm.width / 2 + fm.arm,
724
+ { room } = shapeAt;
309
725
  const fits = Math.min(room.a, room.b) + fm.width / 2 >= reach;
310
- if (j.shape === 'T' && flip) throw new Error(`${what}: shape T: a printed gusset turned onto ${ib.id}'s ${j.face} face is an L only (a T's bar would lie along ${ia.id}): give shape L, or leave face out`);
311
- if (j.shape === 'T' && !fits) throw new Error(`${what}: shape T: a printed T gusset's bar runs ${mm(fm.arm)} mm along ${ib.id} on both sides of ${ia.id}, and there is ${mm(Math.min(room.a, room.b))} mm on one side: give shape L, or leave shape out`);
312
- if (!flip && fits && j.shape !== 'L') { shape = 'T'; fm = fittingModel({ ...spec0, shape }, context, material, what); } // (an L only, turned over: a T's bar would lie along a)
313
- else if (Math.max(room.a, room.b) + fm.width / 2 < reach - 1e-6) throw new Error(`${what}: a printed gusset's ${mm(fm.arm)} mm arm runs past ${ib.id}'s ends: there is ${mm(Math.max(room.a, room.b))} mm beside ${ia.id}, and it needs ${mm(fm.arm)}. A bracket will do`);
314
- if (A.length < fm.arm - 1e-6) throw new Error(`${what}: a printed gusset's ${mm(fm.arm)} mm arm is longer than ${ia.id} (${mm(A.length)} mm)`);
315
- } else if (Math.min(A.length, B.length) < fm.arm - 1e-6) throw new Error(`${what}: a printed splice plate's ${mm(fm.arm)} mm arms are longer than ${A.length < B.length ? ia.id : ib.id}`);
316
- if (A.profile.name !== B.profile.name && faceOf(A, aq) !== faceOf(B, bq)) throw new Error(`${what}: a printed plate is drawn for one profile's slots, and ${ia.id} (${A.profile.name}) and ${ib.id} (${B.profile.name}) differ: a bracket takes two`);
317
- const id = free(`${ia.id}-${ib.id}-${splice ? 'splice' : 'gusset'}`), along = dot(x, ub) > 0;
726
+ if (j.shape === 'T' && flip)
727
+ throw new Error(
728
+ `${what}: shape T: a printed gusset turned onto ${ib.id}'s ${j.face} face is an L only (a T's bar would lie along ${ia.id}): give shape L, or leave face out`,
729
+ );
730
+ if (j.shape === 'T' && !fits)
731
+ throw new Error(
732
+ `${what}: shape T: a printed T gusset's bar runs ${mm(fm.arm)} mm along ${ib.id} on both sides of ${ia.id}, and there is ${mm(Math.min(room.a, room.b))} mm on one side: give shape L, or leave shape out`,
733
+ );
734
+ if (!flip && fits && j.shape !== 'L') {
735
+ shape = 'T';
736
+ fm = fittingModel({ ...spec0, shape }, context, material, what);
737
+ } // (an L only, turned over: a T's bar would lie along a)
738
+ else if (Math.max(room.a, room.b) + fm.width / 2 < reach - 1e-6)
739
+ throw new Error(
740
+ `${what}: a printed gusset's ${mm(fm.arm)} mm arm runs past ${ib.id}'s ends: there is ${mm(Math.max(room.a, room.b))} mm beside ${ia.id}, and it needs ${mm(fm.arm)}. A bracket will do`,
741
+ );
742
+ if (A.length < fm.arm - 1e-6)
743
+ throw new Error(`${what}: a printed gusset's ${mm(fm.arm)} mm arm is longer than ${ia.id} (${mm(A.length)} mm)`);
744
+ } else if (Math.min(A.length, B.length) < fm.arm - 1e-6)
745
+ throw new Error(
746
+ `${what}: a printed splice plate's ${mm(fm.arm)} mm arms are longer than ${A.length < B.length ? ia.id : ib.id}`,
747
+ );
748
+ if (A.profile.name !== B.profile.name && faceOf(A, aq) !== faceOf(B, bq))
749
+ throw new Error(
750
+ `${what}: a printed plate is drawn for one profile's slots, and ${ia.id} (${A.profile.name}) and ${ib.id} (${B.profile.name}) differ: a bracket takes two`,
751
+ );
752
+ const id = free(`${ia.id}-${ib.id}-${splice ? 'splice' : 'gusset'}`),
753
+ along = dot(x, ub) > 0;
318
754
  const spec = { ...spec0, ...(splice ? {} : { shape }) };
319
755
  // (at b's face's anchor the item's x runs along b and its z out of the face; turned over, its x runs along a: a
320
756
  // quarter turn about z, the way that keeps its arm drawn for b along a away from b)
321
- const item = { id, fitting: spec, at: `${ib.id}.${bq.name}@${r3(d)}`, ...(flip ? { rotate: [0, 0, along ? -90 : 90] } : along ? {} : { rotate: [0, 0, 180] }), join: i };
322
- const anchorsOf = (leg) => fm.screws.map((sc, k) => [sc, k]).filter(([sc]) => sc.leg === (flip ? (leg === 'a' ? 'b' : 'a') : leg)).map((_, k) => `${id}.${flip ? (leg === 'a' ? 'b' : 'a') : leg}${k + 1}`);
323
- const fasten = [{ screw: `${fm.thread} ${fm.head}`, through: [id], into: `${ib.id}.${bq.name}`, at: anchorsOf('b'), note: `${label}: the ${splice ? 'splice plate' : 'gusset'} into ${ib.id}`, join: i, nut: j.nut ?? fm.screws[0].nutKind },
324
- { screw: `${fm.thread} ${fm.head}`, through: [id], into: `${ia.id}.${aq.name}`, at: anchorsOf('a'), note: `${label}: the ${splice ? 'splice plate' : 'gusset'} into ${ia.id}`, join: i, nut: j.nut ?? fm.screws[0].nutKind }];
757
+ const item = {
758
+ id,
759
+ fitting: spec,
760
+ at: `${ib.id}.${bq.name}@${r3(d)}`,
761
+ ...(flip ? { rotate: [0, 0, along ? -90 : 90] } : along ? {} : { rotate: [0, 0, 180] }),
762
+ join: i,
763
+ };
764
+ const anchorsOf = (leg) =>
765
+ fm.screws
766
+ .map((sc, k) => [sc, k])
767
+ .filter(([sc]) => sc.leg === (flip ? (leg === 'a' ? 'b' : 'a') : leg))
768
+ .map((_, k) => `${id}.${flip ? (leg === 'a' ? 'b' : 'a') : leg}${k + 1}`);
769
+ const fasten = [
770
+ {
771
+ screw: `${fm.thread} ${fm.head}`,
772
+ through: [id],
773
+ into: `${ib.id}.${bq.name}`,
774
+ at: anchorsOf('b'),
775
+ note: `${label}: the ${splice ? 'splice plate' : 'gusset'} into ${ib.id}`,
776
+ join: i,
777
+ nut: j.nut ?? fm.screws[0].nutKind,
778
+ },
779
+ {
780
+ screw: `${fm.thread} ${fm.head}`,
781
+ through: [id],
782
+ into: `${ia.id}.${aq.name}`,
783
+ at: anchorsOf('a'),
784
+ note: `${label}: the ${splice ? 'splice plate' : 'gusset'} into ${ia.id}`,
785
+ join: i,
786
+ nut: j.nut ?? fm.screws[0].nutKind,
787
+ },
788
+ ];
325
789
  return { item, fasten, model: fm };
326
790
  }
327
791
 
@@ -332,9 +796,46 @@ export function joinFitting(j, i, { ia, ib, A, B, m, ends, place: placeOf }, num
332
796
  * @param {object} k joinStiffness's @param {object} fm the fitting's model
333
797
  */
334
798
  export function fittedStiffness(k, fm) {
335
- const share = k.share ?? { value: 1, kind: 'estimate' }, fe = fm.stiffness.bending, bending = fe * share.value;
336
- return { ...k, bending, end: { rx: k.twist, ry: bending, rz: bending }, measured: { ...(k.measured ?? {}), bending: share.kind === 'measured' ? share.checked ?? null : null }, fitting: { name: fm.name, bending, fe, share: share.value, shareKind: share.kind, linear: fm.stiffness.linear, margin: fm.margin, grams: fm.grams, load: fm.load.force },
337
- rests: [{ value: fe, unit: 'N mm/rad', kind: 'derived', source: `${fm.name}: by finite elements on the printed fitting as drawn; the slot nuts and lips not in it` }, ...(share.value !== 1 || share.kind === 'measured' ? [{ value: share.value, unit: '', kind: share.kind, source: share.source, ...(share.checked ? { checked: share.checked } : {}) }] : []), ...k.rests.slice(1)] };
799
+ const share = k.share ?? { value: 1, kind: 'estimate' },
800
+ fe = fm.stiffness.bending,
801
+ bending = fe * share.value;
802
+ return {
803
+ ...k,
804
+ bending,
805
+ end: { rx: k.twist, ry: bending, rz: bending },
806
+ measured: { ...(k.measured ?? {}), bending: share.kind === 'measured' ? (share.checked ?? null) : null },
807
+ fitting: {
808
+ name: fm.name,
809
+ bending,
810
+ fe,
811
+ share: share.value,
812
+ shareKind: share.kind,
813
+ linear: fm.stiffness.linear,
814
+ margin: fm.margin,
815
+ grams: fm.grams,
816
+ load: fm.load.force,
817
+ },
818
+ rests: [
819
+ {
820
+ value: fe,
821
+ unit: 'N mm/rad',
822
+ kind: 'derived',
823
+ source: `${fm.name}: by finite elements on the printed fitting as drawn; the slot nuts and lips not in it`,
824
+ },
825
+ ...(share.value !== 1 || share.kind === 'measured'
826
+ ? [
827
+ {
828
+ value: share.value,
829
+ unit: '',
830
+ kind: share.kind,
831
+ source: share.source,
832
+ ...(share.checked ? { checked: share.checked } : {}),
833
+ },
834
+ ]
835
+ : []),
836
+ ...k.rests.slice(1),
837
+ ],
838
+ };
338
839
  }
339
840
 
340
841
  /**
@@ -342,5 +843,98 @@ export function fittedStiffness(k, fm) {
342
843
  * fitting.stiffness, fitting.mass and the rest), each said of its item. @param {object} s a built assembly @param {Function} f the findings' sink
343
844
  */
344
845
  export function fittingFindings(s, f) {
345
- for (const o of s.objects) if (o.fitting && !o.unplaced) for (const x of o.fitting.findings) f(x.level, `${o.id}: ${x.text}`, x.level === 'fail' || x.level === 'warn' ? `${o.id}: ${x.code.split('.')[1]}` : null, { code: x.code, ...(x.values ? { values: x.values } : {}), refs: { item: o.id, fitting: o.fitting.name, ...(x.refs ?? {}) } });
846
+ for (const o of s.objects)
847
+ if (o.fitting && !o.unplaced)
848
+ for (const x of o.fitting.findings) if (!(isFoot(o) && AT_LOAD.includes(x.code))) said(f, o, x);
849
+ }
850
+ const said = (f, o, x, refs = {}) =>
851
+ f(
852
+ x.level,
853
+ `${o.id}: ${x.text}`,
854
+ x.level === 'fail' || x.level === 'warn' ? `${o.id}: ${x.code.split('.')[1]}` : null,
855
+ {
856
+ code: x.code,
857
+ ...(x.values ? { values: x.values } : {}),
858
+ refs: { item: o.id, fitting: o.fitting.name, ...(x.refs ?? {}), ...refs },
859
+ },
860
+ );
861
+
862
+ // The printed parts a frame stands on, and their findings that hang on the load they carry: said by footFindings once
863
+ // the frame is solved, at the load the frame puts on each (#378)
864
+ const FEET = ['foot', 'levelling-foot', 'castor-plate', 'stacking-foot'],
865
+ AT_LOAD = ['fitting.margin', 'fitting.seat'];
866
+ const isFoot = (o) => FEET.includes(o.fitting?.fitting);
867
+
868
+ /**
869
+ * Each printed foot's (a foot's, a levelling foot's, a castor plate's or a stacking foot's) fitting.margin, and a castor
870
+ * plate's fitting.seat, judged at the load the frame puts on it: the largest downward reaction at the beam's end it
871
+ * stands under, over the frame's load cases, with the joins' springs and with them rigid (the larger taken). A load
872
+ * given in the item's fitting is kept where it is the larger. Where the frame is not solved, or holds nothing at that
873
+ * end, the part is judged at the load it was drawn for, and a default load is said to be one, not the frame's.
874
+ * @param {object} s a built assembly @param {Function} f the findings' sink
875
+ * @param {{ model: object, results: object[] } | null} frame frameChecks's result: the frame's model and each case's solve
876
+ */
877
+ export function footFindings(s, f, frame) {
878
+ const items = new Map((s.a.items ?? []).map((it) => [it.id, it]));
879
+ for (const o of s.objects) {
880
+ if (!isFoot(o) || o.unplaced || !o.fitting.findings.some((x) => AT_LOAD.includes(x.code))) continue;
881
+ const it = items.get(o.id),
882
+ m = o.fitting,
883
+ given = it?.fitting?.load != null,
884
+ R = frame && it ? reactionAt(frame, it.at) : null;
885
+ let at, refs;
886
+ if (R && R.force > 0 && (!given || R.force > m.load.force)) {
887
+ const F = +R.force.toFixed(1),
888
+ resize =
889
+ m.fitting === 'castor-plate' && F > m.load.force
890
+ ? `; the plate was drawn for ${mm(m.load.force)} N: give its fitting "load": ${Math.ceil(F)} to size it for this`
891
+ : given
892
+ ? `, more than the ${mm(m.load.force)} N its fitting gives`
893
+ : '';
894
+ at = frames.footAt(m, F, {
895
+ from: `the frame's largest reaction at ${R.where}${R.cases > 1 ? `, worst ${R.label}, of its ${R.cases} load cases` : ''}${R.rigid ? ', with the joins rigid' : ''}${resize}`,
896
+ });
897
+ refs = { support: R.where, reaction: F };
898
+ } else if (given)
899
+ at = frames.footAt(m, m.load.force, {
900
+ from:
901
+ R && R.force > 0
902
+ ? `its fitting's load, more than the frame's reaction of ${mm(R.force)} N`
903
+ : "its fitting's load",
904
+ });
905
+ else
906
+ at = frames.footAt(m, m.load.force, {
907
+ from: `the default ${mm(frames.END_DEFAULTS.load.value)} N for one foot, not the frame's load: ${
908
+ !frame
909
+ ? 'no frame is solved here'
910
+ : !R
911
+ ? `the frame's solve holds nothing at ${it?.at ?? 'its end'}`
912
+ : 'the frame lifts off it or puts no weight on it in every load case'
913
+ }`,
914
+ });
915
+ for (const x of at.findings) if (AT_LOAD.includes(x.code)) said(f, o, x, refs);
916
+ }
917
+ }
918
+ // The largest downward force the frame puts on a support at a beam's end (as "z1.a"), over its cases: with the joins'
919
+ // springs, or with them rigid where that is more than a hundredth larger. { force, where, label, cases, rigid }, or
920
+ // null where the solve holds nothing there
921
+ function reactionAt({ model: fm, results }, addr) {
922
+ const m = typeof addr === 'string' ? /^([\w-]+)\.([ab])(\.\d+)?$/.exec(addr.trim()) : null,
923
+ b = m && fm.beams.get(m[1]);
924
+ if (!b) return null;
925
+ const node = fm.nodeAt(b, m[2] === 'a' ? 0 : b.L),
926
+ most = (rigid) => {
927
+ let best = null;
928
+ for (const r of results ?? []) {
929
+ const six = (rigid ? r.rigid : r.spring)?.reactions?.[node];
930
+ if (!six) continue;
931
+ const force = -dot(six.slice(0, 3), fm.down); // (the support pushes up on the frame: the foot carries its opposite)
932
+ if (!best || force > best.force) best = { force, where: `${m[1]}.${m[2]}`, label: r.case.label, rigid };
933
+ }
934
+ return best;
935
+ };
936
+ const spring = most(false),
937
+ rigid = most(true),
938
+ best = rigid && (!spring || rigid.force > 1.01 * spring.force) ? rigid : spring;
939
+ return best && { ...best, cases: results.length };
346
940
  }