@rulecad/cad 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/AGENTS.md +24 -10
  2. package/CHANGELOG.md +404 -0
  3. package/EXAMPLES.md +40 -38
  4. package/README.md +193 -67
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2250 -512
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1847 -434
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +649 -121
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +899 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2702 -507
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +790 -175
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +123 -21
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +2 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1021 -213
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +3 -1
  57. package/lib/optimise.mjs +978 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +223 -35
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +15 -5
  68. package/lib/sandbox-hooks.mjs +77 -19
  69. package/lib/sandbox-run.mjs +117 -18
  70. package/lib/sandbox.mjs +509 -60
  71. package/lib/schema.mjs +42 -11
  72. package/lib/seats.mjs +227 -49
  73. package/lib/services.mjs +261 -52
  74. package/lib/sheet.mjs +851 -178
  75. package/lib/slotnuts.mjs +213 -34
  76. package/lib/targets/gist.mjs +4 -1
  77. package/lib/targets.mjs +22 -4
  78. package/lib/task.mjs +376 -79
  79. package/lib/versions.mjs +111 -28
  80. package/lib/wires.mjs +228 -45
  81. package/lib/workspace.mjs +197 -12
  82. package/package.json +19 -19
  83. package/schemas/assembly.schema.json +2 -2
@@ -23,9 +23,9 @@
23
23
  // found stands over it (its covers): where no build reaches one, the build is refused with that reason.
24
24
  import { squareness, CUT_DEFAULTS, JOIN_PLAY } from '@rulecad/frames';
25
25
  import { placeItems } from '@rulecad/model-link';
26
- import fs from 'node:fs';
27
26
  import path from 'node:path';
28
27
  import { paths } from './workspace.mjs';
28
+ import { readOwnText } from './host.mjs';
29
29
  import { cutListOf, sheetFile } from './beams.mjs';
30
30
  import { orderOf, fastenerText } from './order.mjs';
31
31
  import { preloadOf, trappedOf, closuresOf, nutGroupsOf } from './slotnuts.mjs';
@@ -33,7 +33,10 @@ import { preloadOf, trappedOf, closuresOf, nutGroupsOf } from './slotnuts.mjs';
33
33
  const mm = (x) => String(+Number(x).toFixed(2));
34
34
  const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
35
35
  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]];
36
- const norm = (a) => { const l = Math.hypot(...a); return a.map((x) => x / l); };
36
+ const norm = (a) => {
37
+ const l = Math.hypot(...a);
38
+ return a.map((x) => x / l);
39
+ };
37
40
  const list = (xs) => (xs.length < 2 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs.at(-1)}`);
38
41
 
39
42
  // A beam's cut tolerance and what it rests on: the assembly's frame.cut.tolerance (the workshop's own saw), else the
@@ -42,29 +45,60 @@ const list = (xs) => (xs.length < 2 ? xs.join('') : `${xs.slice(0, -1).join(', '
42
45
  export function cutToleranceOf(s) {
43
46
  const c = s.a.frame?.cut;
44
47
  if (c == null) return null;
45
- if (typeof c !== 'object' || Array.isArray(c)) throw new Error(`frame.cut is { "tolerance": 0.5 }: how far this workshop's cuts may be from the length asked, in mm (got ${JSON.stringify(c)})`);
46
- for (const k of Object.keys(c)) if (k !== 'tolerance') throw new Error(`frame.cut has no "${k}": it takes tolerance (mm)`);
48
+ if (typeof c !== 'object' || Array.isArray(c))
49
+ throw new Error(
50
+ `frame.cut is { "tolerance": 0.5 }: how far this workshop's cuts may be from the length asked, in mm (got ${JSON.stringify(c)})`,
51
+ );
52
+ for (const k of Object.keys(c))
53
+ if (k !== 'tolerance') throw new Error(`frame.cut has no "${k}": it takes tolerance (mm)`);
47
54
  if (c.tolerance == null) return null;
48
55
  const t = s.num(c.tolerance);
49
- if (!(Number.isFinite(t) && t >= 0)) throw new Error(`frame.cut.tolerance is how far a cut may be from the length asked, either way, a number of mm, 0 or more (got ${JSON.stringify(c.tolerance)})`);
56
+ if (!(Number.isFinite(t) && t >= 0))
57
+ throw new Error(
58
+ `frame.cut.tolerance is how far a cut may be from the length asked, either way, a number of mm, 0 or more (got ${JSON.stringify(c.tolerance)})`,
59
+ );
50
60
  return t;
51
61
  }
52
62
  function tolOf(s, p, printed = false) {
53
63
  // (a printed beam is not cut: its length comes off the printer, held here to a saw cut's tolerance, an estimate)
54
- if (printed) return { tol: CUT_DEFAULTS.tolerance.value, tolKind: 'estimate', tolFrom: 'frames.cut.tolerance, taken for a printed length', printed: true };
64
+ if (printed)
65
+ return {
66
+ tol: CUT_DEFAULTS.tolerance.value,
67
+ tolKind: 'estimate',
68
+ tolFrom: 'frames.cut.tolerance, taken for a printed length',
69
+ printed: true,
70
+ };
55
71
  const given = cutToleranceOf(s);
56
- if (given != null) return { tol: given, tolKind: 'given', tolFrom: 'the assembly\'s frame.cut.tolerance' };
57
- if (p.supply?.cutTolerance != null) return { tol: p.supply.cutTolerance, tolKind: p.figures?.cut_tolerance?.kind ?? 'spec', tolFrom: `${p.name}.cut_tolerance` };
72
+ if (given != null) return { tol: given, tolKind: 'given', tolFrom: "the assembly's frame.cut.tolerance" };
73
+ if (p.supply?.cutTolerance != null)
74
+ return {
75
+ tol: p.supply.cutTolerance,
76
+ tolKind: p.figures?.cut_tolerance?.kind ?? 'spec',
77
+ tolFrom: `${p.name}.cut_tolerance`,
78
+ };
58
79
  return { tol: CUT_DEFAULTS.tolerance.value, tolKind: CUT_DEFAULTS.tolerance.kind, tolFrom: 'frames.cut.tolerance' };
59
80
  }
60
81
 
61
82
  // Each beam as a line in the world: end a, its axis, its section's two axes and sizes, its length, its cut tolerance
62
83
  function linesOf(s) {
63
- const placed = placeItems(s.motion, s.jointValues), worlds = Object.fromEntries(s.motion.items.map((x, i) => [x[0], placed[i]])), out = new Map(); // (placeItems: by the order of the motion's items)
84
+ const placed = placeItems(s.motion, s.jointValues),
85
+ worlds = Object.fromEntries(s.motion.items.map((x, i) => [x[0], placed[i]])),
86
+ out = new Map(); // (placeItems: by the order of the motion's items)
64
87
  for (const o of s.objects) {
65
88
  if (!o.beam || o.unplaced || !worlds[o.id]) continue;
66
- const W = worlds[o.id], p = o.beam.profile;
67
- out.set(o.id, { id: o.id, O: [W[3], W[7], W[11]], d: norm([W[2], W[6], W[10]]), X: [W[0], W[4], W[8]], Y: [W[1], W[5], W[9]], w: p.width, h: p.height, L: o.beam.length, ...tolOf(s, p, !!o.beam.printed) });
89
+ const W = worlds[o.id],
90
+ p = o.beam.profile;
91
+ out.set(o.id, {
92
+ id: o.id,
93
+ O: [W[3], W[7], W[11]],
94
+ d: norm([W[2], W[6], W[10]]),
95
+ X: [W[0], W[4], W[8]],
96
+ Y: [W[1], W[5], W[9]],
97
+ w: p.width,
98
+ h: p.height,
99
+ L: o.beam.length,
100
+ ...tolOf(s, p, !!o.beam.printed),
101
+ });
68
102
  }
69
103
  return out;
70
104
  }
@@ -77,41 +111,103 @@ const reach = (b, e) => (Math.abs(dot(b.X, e)) * b.w + Math.abs(dot(b.Y, e)) * b
77
111
  * @returns {{ beams: string[], name: string, width: number, height: number, square: object }[]}
78
112
  */
79
113
  export function baysOf(s) {
80
- const L = linesOf(s), ids = [...L.keys()], joined = new Set();
81
- for (const j of s.joins ?? []) { joined.add(`${j.items[0]}|${j.items[1]}`); joined.add(`${j.items[1]}|${j.items[0]}`); }
82
- const J = (a, b) => joined.has(`${a}|${b}`), par = (a, b) => Math.abs(Math.abs(dot(a.d, b.d)) - 1) < 1e-6, perp = (a, b) => Math.abs(dot(a.d, b.d)) < 1e-6;
83
- const out = [], seen = new Set();
84
- for (let i = 0; i < ids.length; i++) for (let k = i + 1; k < ids.length; k++) {
85
- const A = L.get(ids[i]), B = L.get(ids[k]);
86
- if (!par(A, B)) continue;
87
- const cross_ = ids.filter((id) => id !== A.id && id !== B.id && perp(L.get(id), A) && J(id, A.id) && J(id, B.id));
88
- for (let m = 0; m < cross_.length; m++) for (let q = m + 1; q < cross_.length; q++) {
89
- const C = L.get(cross_[m]), D = L.get(cross_[q]);
90
- if (!par(C, D)) continue;
91
- const n = norm(cross(A.d, C.d)), on = (b) => Math.abs(dot(b.O.map((x, t) => x - A.O[t]), n)) < 1e-3;
92
- if (![B, C, D].every(on)) continue;
93
- const key = [A.id, B.id, C.id, D.id].sort().join('|');
94
- if (seen.has(key)) continue;
95
- seen.add(key);
96
- const v = C.d, u = A.d, width = Math.abs(dot(A.O, v) - dot(B.O, v)) - reach(A, v) - reach(B, v), height = Math.abs(dot(C.O, u) - dot(D.O, u)) - reach(C, u) - reach(D, u);
97
- if (!(width > 0 && height > 0)) continue;
98
- // what squares it: each beam whose end butts a beam of the bay sets the opening along it by its cut length; each
99
- // join of the bay's beams lets a's end sit off by its play along b (JOIN_PLAY), stacked worst case
100
- const bay = [A, B, C, D], ids4 = bay.map((x) => x.id), along = (x) => (par(x, C) ? 'width' : 'height');
101
- const inBay = (s.joins ?? []).filter((j) => ids4.includes(j.items[0]) && ids4.includes(j.items[1]) && j.items[0] !== j.items[1]);
102
- const cuts = bay.filter((x) => inBay.some((j) => j.items[0] === x.id)).map((x) => ({ name: x.id, along: along(x), tolerance: x.tol, kind: x.tolKind, ...(x.printed ? { printed: true } : {}) }));
103
- const plays = inBay.map((j) => { const r = JOIN_PLAY[j.kind]; return r ? { name: `join ${j.index + 1} (${j.kind})`, along: along(L.get(j.items[1])), slip: r.value, kind: r.kind } : null; }).filter(Boolean);
104
- const sq = squareness(width, height, { tolerance: Math.max(...bay.map((x) => x.tol)), cuts, plays });
105
- out.push({ beams: ids4, name: `${A.id}, ${B.id}, ${C.id} and ${D.id}`, width: +width.toFixed(2), height: +height.toFixed(2), square: sq, joins: inBay.map((j) => j.index), tolFrom: [...new Set(bay.map((x) => x.tolFrom))] });
106
- }
114
+ const L = linesOf(s),
115
+ ids = [...L.keys()],
116
+ joined = new Set();
117
+ for (const j of s.joins ?? []) {
118
+ joined.add(`${j.items[0]}|${j.items[1]}`);
119
+ joined.add(`${j.items[1]}|${j.items[0]}`);
107
120
  }
121
+ const J = (a, b) => joined.has(`${a}|${b}`),
122
+ par = (a, b) => Math.abs(Math.abs(dot(a.d, b.d)) - 1) < 1e-6,
123
+ perp = (a, b) => Math.abs(dot(a.d, b.d)) < 1e-6;
124
+ const out = [],
125
+ seen = new Set();
126
+ for (let i = 0; i < ids.length; i++)
127
+ for (let k = i + 1; k < ids.length; k++) {
128
+ const A = L.get(ids[i]),
129
+ B = L.get(ids[k]);
130
+ if (!par(A, B)) continue;
131
+ const cross_ = ids.filter((id) => id !== A.id && id !== B.id && perp(L.get(id), A) && J(id, A.id) && J(id, B.id));
132
+ for (let m = 0; m < cross_.length; m++)
133
+ for (let q = m + 1; q < cross_.length; q++) {
134
+ const C = L.get(cross_[m]),
135
+ D = L.get(cross_[q]);
136
+ if (!par(C, D)) continue;
137
+ const n = norm(cross(A.d, C.d)),
138
+ on = (b) =>
139
+ Math.abs(
140
+ dot(
141
+ b.O.map((x, t) => x - A.O[t]),
142
+ n,
143
+ ),
144
+ ) < 1e-3;
145
+ if (![B, C, D].every(on)) continue;
146
+ const key = [A.id, B.id, C.id, D.id].sort().join('|');
147
+ if (seen.has(key)) continue;
148
+ seen.add(key);
149
+ const v = C.d,
150
+ u = A.d,
151
+ width = Math.abs(dot(A.O, v) - dot(B.O, v)) - reach(A, v) - reach(B, v),
152
+ height = Math.abs(dot(C.O, u) - dot(D.O, u)) - reach(C, u) - reach(D, u);
153
+ if (!(width > 0 && height > 0)) continue;
154
+ // what squares it: each beam whose end butts a beam of the bay sets the opening along it by its cut length; each
155
+ // join of the bay's beams lets a's end sit off by its play along b (JOIN_PLAY), stacked worst case
156
+ const bay = [A, B, C, D],
157
+ ids4 = bay.map((x) => x.id),
158
+ along = (x) => (par(x, C) ? 'width' : 'height');
159
+ const inBay = (s.joins ?? []).filter(
160
+ (j) => ids4.includes(j.items[0]) && ids4.includes(j.items[1]) && j.items[0] !== j.items[1],
161
+ );
162
+ const cuts = bay
163
+ .filter((x) => inBay.some((j) => j.items[0] === x.id))
164
+ .map((x) => ({
165
+ name: x.id,
166
+ along: along(x),
167
+ tolerance: x.tol,
168
+ kind: x.tolKind,
169
+ ...(x.printed ? { printed: true } : {}),
170
+ }));
171
+ const plays = inBay
172
+ .map((j) => {
173
+ const r = JOIN_PLAY[j.kind];
174
+ return r
175
+ ? {
176
+ name: `join ${j.index + 1} (${j.kind})`,
177
+ along: along(L.get(j.items[1])),
178
+ slip: r.value,
179
+ kind: r.kind,
180
+ }
181
+ : null;
182
+ })
183
+ .filter(Boolean);
184
+ const sq = squareness(width, height, { tolerance: Math.max(...bay.map((x) => x.tol)), cuts, plays });
185
+ out.push({
186
+ beams: ids4,
187
+ name: `${A.id}, ${B.id}, ${C.id} and ${D.id}`,
188
+ width: +width.toFixed(2),
189
+ height: +height.toFixed(2),
190
+ square: sq,
191
+ joins: inBay.map((j) => j.index),
192
+ tolFrom: [...new Set(bay.map((x) => x.tolFrom))],
193
+ });
194
+ }
195
+ }
108
196
  return out;
109
197
  }
110
198
 
111
199
  // One join's screws as the steps say them: each fastening of its relations, with its key and torque
112
200
  function joinLines(s, j) {
113
201
  const fits = s.fits.filter((f) => j.fasten.includes(f.fasten) && (f.fastener || f.key));
114
- return fits.map((f) => fastenerText({ fit: f.note, ...(f.fastener ? { fastener: f.fastener } : {}), ...(f.count != null ? { count: f.num ? f.num(f.count) : f.count } : {}), ...(f.key ? { key: f.key } : {}), ...(f.tighten ? { tighten: f.tighten } : {}) }));
202
+ return fits.map((f) =>
203
+ fastenerText({
204
+ fit: f.note,
205
+ ...(f.fastener ? { fastener: f.fastener } : {}),
206
+ ...(f.count != null ? { count: f.num ? f.num(f.count) : f.count } : {}),
207
+ ...(f.key ? { key: f.key } : {}),
208
+ ...(f.tighten ? { tighten: f.tighten } : {}),
209
+ }),
210
+ );
115
211
  }
116
212
 
117
213
  /**
@@ -139,180 +235,473 @@ export function frameStepOf(b) {
139
235
  }
140
236
 
141
237
  function buildFrame(s) {
142
- const joins = s.joins ?? [], L = linesOf(s), beamIds = [...L.keys()], none = { steps: [], sides: [], notFlat: [], bays: [], torques: [] };
238
+ const joins = s.joins ?? [],
239
+ L = linesOf(s),
240
+ beamIds = [...L.keys()],
241
+ none = { steps: [], sides: [], notFlat: [], bays: [], torques: [] };
143
242
  const order = orderOf(s);
144
243
  if (order.stuck) return { ...none, stuck: { ...order.stuck } };
145
244
  // nuts shut in by joins at both ends: in every order the second of those joins shuts them in, so no build is offered
146
245
  const trapped = trappedOf(s);
147
246
  if (trapped.length) {
148
- const t = trapped[0], [p, q] = t.joins;
149
- const alt = t.alternative ? `: give "nut": "${t.alternative.nutKind}" (${t.alternative.name}), which goes in through the opening anywhere` : `: no ${t.kind} nut of this thread goes in through the opening, so move the part to a slot with an open end`;
150
- return { ...none, stuck: { item: t.item, place: t.place, nut: t.nut, joins: [p.index, q.index], fasten: t.fasten, ...(t.alternative ? { alternative: t.alternative.name } : {}),
151
- text: `${t.item}'s ${t.named} slot: ${t.count} ${t.kind} nut${t.count > 1 ? 's' : ''} (${t.nut}) for ${t.part} would be shut in between the ${p.label} and the ${q.label}: whichever of the two is made second shuts them in, and a nut loaded before it can never be taken out or replaced${alt}` } };
247
+ const t = trapped[0],
248
+ [p, q] = t.joins;
249
+ const alt = t.alternative
250
+ ? `: give "nut": "${t.alternative.nutKind}" (${t.alternative.name}), which goes in through the opening anywhere`
251
+ : `: no ${t.kind} nut of this thread goes in through the opening, so move the part to a slot with an open end`;
252
+ return {
253
+ ...none,
254
+ stuck: {
255
+ item: t.item,
256
+ place: t.place,
257
+ nut: t.nut,
258
+ joins: [p.index, q.index],
259
+ fasten: t.fasten,
260
+ ...(t.alternative ? { alternative: t.alternative.name } : {}),
261
+ text: `${t.item}'s ${t.named} slot: ${t.count} ${t.kind} nut${t.count > 1 ? 's' : ''} (${t.nut}) for ${t.part} would be shut in between the ${p.label} and the ${q.label}: whichever of the two is made second shuts them in, and a nut loaded before it can never be taken out or replaced${alt}`,
262
+ },
263
+ };
152
264
  }
153
- const bays = baysOf(s), fittings = new Map(joins.filter((j) => j.fitted?.item).map((j) => [j.fitted.item, j]));
154
- const rank = new Map(); order.steps.forEach((st, i) => st.items.forEach((id) => rank.set(id, i)));
265
+ const bays = baysOf(s),
266
+ fittings = new Map(joins.filter((j) => j.fitted?.item).map((j) => [j.fitted.item, j]));
267
+ const rank = new Map();
268
+ order.steps.forEach((st, i) => st.items.forEach((id) => rank.set(id, i)));
155
269
  const byOrder = [...beamIds].sort((p, q) => (rank.get(p) ?? 1e9) - (rank.get(q) ?? 1e9)); // (beams going on one at a time keep the assembly order's sequence, which reaches every screw)
156
270
  const dirOf = (id) => order.steps.find((st) => st.items.includes(id))?.dir ?? [0, 0, 1];
157
- const joinsBetween = (id, set) => joins.filter((j) => (j.items[0] === id && set.has(j.items[1])) || (j.items[1] === id && set.has(j.items[0])));
271
+ const joinsBetween = (id, set) =>
272
+ joins.filter((j) => (j.items[0] === id && set.has(j.items[1])) || (j.items[1] === id && set.has(j.items[0])));
158
273
  const par = (a, b) => Math.abs(Math.abs(dot(a, b)) - 1) < 1e-6;
159
274
  // A side going on as one: the heads of its blind joins to the frame slide along their slots as it goes on, so every
160
275
  // slot they go into runs one way, and each has a way in from the end that leads, with no join already made across it
161
276
  const slideIn = (bay, js, made) => {
162
277
  const heads = js.filter((j) => j.kind === 'blind' && L.has(j.items[1]));
163
278
  if (!heads.length) return { why: null, dir: null };
164
- const u = L.get(heads[0].items[1]).d, odd = heads.find((j) => !par(L.get(j.items[1]).d, u));
165
- if (odd) return { why: `the heads of its joins to the frame go into slots that run different ways (the ${heads[0].label} along ${heads[0].items[1]}, the ${odd.label} along ${odd.items[1]}), so they can't all slide in as it goes on` };
279
+ const u = L.get(heads[0].items[1]).d,
280
+ odd = heads.find((j) => !par(L.get(j.items[1]).d, u));
281
+ if (odd)
282
+ return {
283
+ why: `the heads of its joins to the frame go into slots that run different ways (the ${heads[0].label} along ${heads[0].items[1]}, the ${odd.label} along ${odd.items[1]}), so they can't all slide in as it goes on`,
284
+ };
166
285
  let last = null;
167
- for (const sg of [1, -1]) { // (the side comes from +u or -u: a head enters a slot of the side at the end that leads, a slot of the frame at the other)
168
- const blocked = heads.map((j) => {
169
- const rb = j.items[1], want = bay.beams.includes(rb) ? -sg : sg, end = dot(L.get(rb).d, u) * want > 0 ? 'b' : 'a', d = j.model.b.distance;
170
- const by = closuresOf(s, rb, j.model.b.place).find((c) => c.join && made.has(c.join.index) && !js.includes(c.join) && (end === 'a' ? c.at < d - 1e-3 : c.at > d + 1e-3));
171
- return by ? { j, end, by: by.join } : null;
172
- }).find(Boolean);
286
+ for (const sg of [1, -1]) {
287
+ // (the side comes from +u or -u: a head enters a slot of the side at the end that leads, a slot of the frame at the other)
288
+ const blocked = heads
289
+ .map((j) => {
290
+ const rb = j.items[1],
291
+ want = bay.beams.includes(rb) ? -sg : sg,
292
+ end = dot(L.get(rb).d, u) * want > 0 ? 'b' : 'a',
293
+ d = j.model.b.distance;
294
+ const by = closuresOf(s, rb, j.model.b.place).find(
295
+ (c) =>
296
+ c.join &&
297
+ made.has(c.join.index) &&
298
+ !js.includes(c.join) &&
299
+ (end === 'a' ? c.at < d - 1e-3 : c.at > d + 1e-3),
300
+ );
301
+ return by ? { j, end, by: by.join } : null;
302
+ })
303
+ .find(Boolean);
173
304
  if (!blocked) return { why: null, dir: u.map((x) => +(x * sg).toFixed(6) || 0) };
174
305
  last = blocked;
175
306
  }
176
- return { why: `the head of the ${last.j.label} can't slide into ${last.j.items[1]}'s slot from either end as it goes on: the ${last.by.label}, made on the bench, closes the way` };
307
+ return {
308
+ why: `the head of the ${last.j.label} can't slide into ${last.j.items[1]}'s slot from either end as it goes on: the ${last.by.label}, made on the bench, closes the way`,
309
+ };
177
310
  };
178
- const barred = new Set(), notFlat = [], key = (b) => b.beams.join('|');
311
+ const barred = new Set(),
312
+ notFlat = [],
313
+ key = (b) => b.beams.join('|');
179
314
  for (;;) {
180
315
  // sides: bays that share no beam with a side already chosen, in the order they are found; a bay that shares one is
181
316
  // squared once the frame is joined
182
- const sides = [], used = new Set();
183
- for (const bay of bays) if (!barred.has(key(bay)) && !bay.beams.some((b) => used.has(b))) { sides.push(bay); for (const b of bay.beams) used.add(b); }
317
+ const sides = [],
318
+ used = new Set();
319
+ for (const bay of bays)
320
+ if (!barred.has(key(bay)) && !bay.beams.some((b) => used.has(b))) {
321
+ sides.push(bay);
322
+ for (const b of bay.beams) used.add(b);
323
+ }
184
324
  const r = attempt(sides, used);
185
- if (!r.problem) return { ...r, sides: sides.map((b) => ({ beams: b.beams, name: b.name, square: b.square })), notFlat, bays, stuck: null };
325
+ if (!r.problem)
326
+ return {
327
+ ...r,
328
+ sides: sides.map((b) => ({ beams: b.beams, name: b.name, square: b.square })),
329
+ notFlat,
330
+ bays,
331
+ stuck: null,
332
+ };
186
333
  const side = r.problem.bay ?? sides.find((b) => r.problem.ids.some((id) => b.beams.includes(id)));
187
334
  if (!side) return { ...none, notFlat, bays, stuck: r.problem.stuck };
188
- barred.add(key(side)); notFlat.push({ beams: side.beams, name: side.name, why: r.problem.why });
335
+ barred.add(key(side));
336
+ notFlat.push({ beams: side.beams, name: side.name, why: r.problem.why });
189
337
  }
190
338
 
191
339
  function attempt(sides, used) {
192
- const steps = [], made = new Set(), bench = new Map(); // (bench: a beam of a side after the first, built flat away from the frame, to its side)
193
- sides.forEach((b, i) => { if (i) for (const id of b.beams) bench.set(id, i); });
194
- const step = (x) => { steps.push({ enters: [], ...x }); };
340
+ const steps = [],
341
+ made = new Set(),
342
+ bench = new Map(); // (bench: a beam of a side after the first, built flat away from the frame, to its side)
343
+ sides.forEach((b, i) => {
344
+ if (i) for (const id of b.beams) bench.set(id, i);
345
+ });
346
+ const step = (x) => {
347
+ steps.push({ enters: [], ...x });
348
+ };
195
349
  // cut and drill
196
350
  const c = cutListOf(s);
197
351
  if (c) {
198
- step({ kind: 'cut', text: `Cut the beams: ${c.marks.map((m) => `${m.count} × ${m.mark} at ${mm(m.length)} mm`).join(', ')} (kerf ${c.rules.kerf.value} mm, ${c.rules.trim.value} mm off each bar's first end; cut each mark against one stop)`,
199
- lines: c.stock.flatMap((st) => [`${st.profile}: buy ${st.buy.map((x) => `${x.count} × ${mm(x.length)} mm`).join(', ')}`, ...st.bars.map((b, i) => `bar ${i + 1}, ${mm(b.length)} mm: ${b.cuts.map((q) => `${q.mark} ${mm(q.length)} (${q.item})`).join(', ')}; offcut ${mm(b.offcut)}`)]) });
352
+ step({
353
+ kind: 'cut',
354
+ text: `Cut the beams: ${c.marks.map((m) => `${m.count} × ${m.mark} at ${mm(m.length)} mm`).join(', ')} (kerf ${c.rules.kerf.value} mm, ${c.rules.trim.value} mm off each bar's first end; cut each mark against one stop)`,
355
+ lines: c.stock.flatMap((st) => [
356
+ `${st.profile}: buy ${st.buy.map((x) => `${x.count} × ${mm(x.length)} mm`).join(', ')}`,
357
+ ...st.bars.map(
358
+ (b, i) =>
359
+ `bar ${i + 1}, ${mm(b.length)} mm: ${b.cuts.map((q) => `${q.mark} ${mm(q.length)} (${q.item})`).join(', ')}; offcut ${mm(b.offcut)}`,
360
+ ),
361
+ ]),
362
+ });
200
363
  const work = c.marks.filter((m) => m.ops.length);
201
- if (work.length) step({ kind: 'drill', text: `Drill and tap each mark as its sheet shows, and write the item on each beam`, lines: work.map((m) => `${m.mark} (${m.items.join(', ')}): ${m.ops.join('; ')}: ${['exports', s.project, path.basename(sheetFile(s, m.mark))].join('/')}`) });
364
+ if (work.length)
365
+ step({
366
+ kind: 'drill',
367
+ text: `Drill and tap each mark as its sheet shows, and write the item on each beam`,
368
+ lines: work.map(
369
+ (m) =>
370
+ `${m.mark} (${m.items.join(', ')}): ${m.ops.join('; ')}: ${['exports', s.project, path.basename(sheetFile(s, m.mark))].join('/')}`,
371
+ ),
372
+ });
202
373
  }
203
374
  // a beam going on: the joins it makes with what is there, each of its screws
204
375
  const joinStep = (ids, set) => {
205
- const js = [...new Map(ids.flatMap((id) => joinsBetween(id, set)).map((j) => [j.index, j])).values()].filter((j) => !made.has(j.index));
376
+ const js = [...new Map(ids.flatMap((id) => joinsBetween(id, set)).map((j) => [j.index, j])).values()].filter(
377
+ (j) => !made.has(j.index),
378
+ );
206
379
  for (const j of js) made.add(j.index);
207
- return { joins: js.map((j) => j.index), lines: js.flatMap((j) => { const l = joinLines(s, j); return l.length ? l : [`${j.label}: ${j.fitted ? `its ${j.fitted.item}` : 'no screws: its fitting comes with the kind'}`]; }) };
380
+ return {
381
+ joins: js.map((j) => j.index),
382
+ lines: js.flatMap((j) => {
383
+ const l = joinLines(s, j);
384
+ return l.length
385
+ ? l
386
+ : [`${j.label}: ${j.fitted ? `its ${j.fitted.item}` : 'no screws: its fitting comes with the kind'}`];
387
+ }),
388
+ };
208
389
  };
209
390
  // (the way a beam goes on: where its end's head goes into a slot of a beam already there, along that slot from its nearer end)
210
- const slideOf = (id, js) => { const j = js.find((q) => q.kind === 'blind' && q.items[0] === id && L.has(q.items[1])); if (!j) return {}; const b = L.get(j.items[1]), sg = j.model.b.distance < b.L / 2 ? -1 : 1; return { dir: b.d.map((x) => +(x * sg).toFixed(6) || 0) }; };
211
- const placeOne = (id, set, prefix = '', side = null) => { const x = joinStep([id], set); step({ kind: 'join', items: [id], ...(side != null ? { side, bench: side > 0 } : {}), ...slideOf(id, x.joins.map((k) => joins[k])), enters: side ? [] : [id], text: `${prefix}${id} goes on${x.joins.length ? `, joined to ${list([...new Set(x.joins.map((k) => joins[k].items.find((q) => q !== id)))])}` : ''}`, ...x }); set.add(id); };
391
+ const slideOf = (id, js) => {
392
+ const j = js.find((q) => q.kind === 'blind' && q.items[0] === id && L.has(q.items[1]));
393
+ if (!j) return {};
394
+ const b = L.get(j.items[1]),
395
+ sg = j.model.b.distance < b.L / 2 ? -1 : 1;
396
+ return { dir: b.d.map((x) => +(x * sg).toFixed(6) || 0) };
397
+ };
398
+ const placeOne = (id, set, prefix = '', side = null) => {
399
+ const x = joinStep([id], set);
400
+ step({
401
+ kind: 'join',
402
+ items: [id],
403
+ ...(side != null ? { side, bench: side > 0 } : {}),
404
+ ...slideOf(
405
+ id,
406
+ x.joins.map((k) => joins[k]),
407
+ ),
408
+ enters: side ? [] : [id],
409
+ text: `${prefix}${id} goes on${x.joins.length ? `, joined to ${list([...new Set(x.joins.map((k) => joins[k].items.find((q) => q !== id)))])}` : ''}`,
410
+ ...x,
411
+ });
412
+ set.add(id);
413
+ };
212
414
  // sides, each built flat
213
415
  sides.forEach((bay, i) => {
214
- const own = new Set(bay.beams), set = new Set(), name = `Side ${i + 1} (${bay.name})`;
215
- const first = [...bay.beams].sort((p, q) => joinsBetween(q, own).length - joinsBetween(p, own).length || beamIds.indexOf(p) - beamIds.indexOf(q))[0];
216
- step({ kind: 'side', side: i, bench: i > 0, items: [first], enters: i ? [] : [first], text: `${name}, built flat on the bench: lay ${first} down` }); set.add(first);
416
+ const own = new Set(bay.beams),
417
+ set = new Set(),
418
+ name = `Side ${i + 1} (${bay.name})`;
419
+ const first = [...bay.beams].sort(
420
+ (p, q) => joinsBetween(q, own).length - joinsBetween(p, own).length || beamIds.indexOf(p) - beamIds.indexOf(q),
421
+ )[0];
422
+ step({
423
+ kind: 'side',
424
+ side: i,
425
+ bench: i > 0,
426
+ items: [first],
427
+ enters: i ? [] : [first],
428
+ text: `${name}, built flat on the bench: lay ${first} down`,
429
+ });
430
+ set.add(first);
217
431
  for (let left = bay.beams.filter((b) => b !== first); left.length;) {
218
432
  const next = left.find((b) => joinsBetween(b, set).length) ?? left[0];
219
- placeOne(next, set, `${name}: `, i); left = left.filter((b) => b !== next);
433
+ placeOne(next, set, `${name}: `, i);
434
+ left = left.filter((b) => b !== next);
220
435
  }
221
- step({ kind: 'square', side: i, bench: i > 0, items: bay.beams, text: `Square side ${i + 1}, then tighten its joins: ${bay.square.text}. Push the corners of the long diagonal together until the two are within that, then tighten each join to its torque and measure again` });
436
+ step({
437
+ kind: 'square',
438
+ side: i,
439
+ bench: i > 0,
440
+ items: bay.beams,
441
+ text: `Square side ${i + 1}, then tighten its joins: ${bay.square.text}. Push the corners of the long diagonal together until the two are within that, then tighten each join to its torque and measure again`,
442
+ });
222
443
  });
223
444
  // the frame: from the first side (or the first beam), beams on one at a time, sides on as one
224
- const set = new Set(sides[0]?.beams ?? byOrder.slice(0, 1)), sideLeft = sides.slice(1).map((b, k) => ({ bay: b, i: k + 1 }));
225
- if (!sides.length && byOrder.length) step({ kind: 'join', items: [byOrder[0]], enters: [byOrder[0]], text: `${byOrder[0]} first`, joins: [], lines: [] });
445
+ const set = new Set(sides[0]?.beams ?? byOrder.slice(0, 1)),
446
+ sideLeft = sides.slice(1).map((b, k) => ({ bay: b, i: k + 1 }));
447
+ if (!sides.length && byOrder.length)
448
+ step({
449
+ kind: 'join',
450
+ items: [byOrder[0]],
451
+ enters: [byOrder[0]],
452
+ text: `${byOrder[0]} first`,
453
+ joins: [],
454
+ lines: [],
455
+ });
226
456
  for (let singles = byOrder.filter((b) => !used.has(b) && !set.has(b)); singles.length || sideLeft.length;) {
227
457
  const one = singles.find((b) => joinsBetween(b, set).length);
228
- if (one) { placeOne(one, set); singles = singles.filter((b) => b !== one); continue; }
458
+ if (one) {
459
+ placeOne(one, set);
460
+ singles = singles.filter((b) => b !== one);
461
+ continue;
462
+ }
229
463
  const k = sideLeft.findIndex((x) => x.bay.beams.some((b) => joinsBetween(b, set).length));
230
464
  if (k >= 0) {
231
- const { bay, i } = sideLeft.splice(k, 1)[0], js = [...new Map(bay.beams.flatMap((id) => joinsBetween(id, set)).map((j) => [j.index, j])).values()];
465
+ const { bay, i } = sideLeft.splice(k, 1)[0],
466
+ js = [...new Map(bay.beams.flatMap((id) => joinsBetween(id, set)).map((j) => [j.index, j])).values()];
232
467
  const slide = slideIn(bay, js, made);
233
468
  if (slide.why) return { problem: { bay, why: slide.why } };
234
469
  const x = joinStep(bay.beams, set);
235
- step({ kind: 'join', side: i, items: bay.beams, enters: bay.beams, ...(slide.dir ? { dir: slide.dir } : {}), text: `Side ${i + 1} goes on as one, joined to ${list([...new Set(x.joins.flatMap((q) => joins[q].items).filter((q) => !bay.beams.includes(q)))])}`, ...x });
470
+ step({
471
+ kind: 'join',
472
+ side: i,
473
+ items: bay.beams,
474
+ enters: bay.beams,
475
+ ...(slide.dir ? { dir: slide.dir } : {}),
476
+ text: `Side ${i + 1} goes on as one, joined to ${list([...new Set(x.joins.flatMap((q) => joins[q].items).filter((q) => !bay.beams.includes(q)))])}`,
477
+ ...x,
478
+ });
236
479
  for (const b of bay.beams) set.add(b);
237
480
  continue;
238
481
  }
239
- if (singles.length) { placeOne(singles[0], set); singles = singles.slice(1); continue; } // (a beam joined to nothing yet)
240
- const { bay, i } = sideLeft.shift(); for (const b of bay.beams) set.add(b);
241
- step({ kind: 'join', side: i, items: bay.beams, enters: bay.beams, text: `Side ${i + 1} goes on as one`, joins: [], lines: [] });
482
+ if (singles.length) {
483
+ placeOne(singles[0], set);
484
+ singles = singles.slice(1);
485
+ continue;
486
+ } // (a beam joined to nothing yet)
487
+ const { bay, i } = sideLeft.shift();
488
+ for (const b of bay.beams) set.add(b);
489
+ step({
490
+ kind: 'join',
491
+ side: i,
492
+ items: bay.beams,
493
+ enters: bay.beams,
494
+ text: `Side ${i + 1} goes on as one`,
495
+ joins: [],
496
+ lines: [],
497
+ });
242
498
  }
243
- const where = () => { const at = new Map(), enter = new Map(), own = new Map(); steps.forEach((x, i) => { for (const k of x.joins ?? []) at.set(k, i); for (const id of x.enters) if (!enter.has(id)) enter.set(id, i); for (const id of x.items ?? []) if (!own.has(id)) own.set(id, i); }); for (const [id, j] of fittings) if (at.has(j.index)) enter.set(id, at.get(j.index)); return { at, enter, own }; };
499
+ const where = () => {
500
+ const at = new Map(),
501
+ enter = new Map(),
502
+ own = new Map();
503
+ steps.forEach((x, i) => {
504
+ for (const k of x.joins ?? []) at.set(k, i);
505
+ for (const id of x.enters) if (!enter.has(id)) enter.set(id, i);
506
+ for (const id of x.items ?? []) if (!own.has(id)) own.set(id, i);
507
+ });
508
+ for (const [id, j] of fittings) if (at.has(j.index)) enter.set(id, at.get(j.index));
509
+ return { at, enter, own };
510
+ };
244
511
  // then everything else, in the assembly's order, with its fastenings: a part a beam would stand over the screws of goes on
245
512
  // before that beam, once the beams it is fastened to are there; the rest once the frame is square
246
513
  const mounts = [];
247
514
  for (const st of order.steps) {
248
515
  const items = st.items.filter((id) => !L.has(id) && !fittings.has(id));
249
516
  if (!items.length) continue;
250
- const lines = st.fasteners.map(fastenerText), last = mounts.at(-1); // (copies of one thing with no screws of their own, one after another, are one step)
251
- if (last && st.object && last.object === st.object && !lines.length && !last.lines.length) last.items.push(...items);
517
+ const lines = st.fasteners.map(fastenerText),
518
+ last = mounts.at(-1); // (copies of one thing with no screws of their own, one after another, are one step)
519
+ if (last && st.object && last.object === st.object && !lines.length && !last.lines.length)
520
+ last.items.push(...items);
252
521
  else mounts.push({ items, object: st.object, lines, dir: st.dir });
253
522
  }
254
- const covers = order.covers ?? [], mountStep = (m) => ({ kind: 'mount', items: m.items, enters: m.items, dir: m.dir, text: `${m.items.join(', ')}${m.object && !m.items.includes(m.object) ? ` (${m.object})` : ''} go${m.items.length > 1 ? '' : 'es'} on`, lines: m.lines });
523
+ const covers = order.covers ?? [],
524
+ mountStep = (m) => ({
525
+ kind: 'mount',
526
+ items: m.items,
527
+ enters: m.items,
528
+ dir: m.dir,
529
+ text: `${m.items.join(', ')}${m.object && !m.items.includes(m.object) ? ` (${m.object})` : ''} go${m.items.length > 1 ? '' : 'es'} on`,
530
+ lines: m.lines,
531
+ });
255
532
  const late = [];
256
533
  for (const m of mounts) {
257
- const cs = covers.filter((c) => c.screwed.some((id) => m.items.includes(id)) && !m.items.includes(c.wall)), { enter } = where();
258
- const walls = cs.map((c) => c.wall).filter((w) => enter.has(w)), partners = [...new Set(cs.flatMap((c) => c.screwed).filter((id) => !m.items.includes(id)))];
259
- if (!walls.length || partners.some((id) => !enter.has(id))) { late.push(m); continue; }
260
- const w = Math.min(...walls.map((x) => enter.get(x))), wall = walls.find((x) => enter.get(x) === w), p = Math.max(-1, ...partners.map((x) => enter.get(x)));
261
- if (p >= w) { const later = partners.find((x) => enter.get(x) === p); return { problem: { ids: [wall, later], why: `${wall} would stand over the screws of ${m.items.join(', ')} before ${later}, which they fasten to, is on`, stuck: { item: m.items[0], wall, text: `the screws of ${m.items.join(', ')} can't be reached: ${wall} stands over them, and it goes on before ${later}, which they fasten to` } } }; }
534
+ const cs = covers.filter((c) => c.screwed.some((id) => m.items.includes(id)) && !m.items.includes(c.wall)),
535
+ { enter } = where();
536
+ const walls = cs.map((c) => c.wall).filter((w) => enter.has(w)),
537
+ partners = [...new Set(cs.flatMap((c) => c.screwed).filter((id) => !m.items.includes(id)))];
538
+ if (!walls.length || partners.some((id) => !enter.has(id))) {
539
+ late.push(m);
540
+ continue;
541
+ }
542
+ const w = Math.min(...walls.map((x) => enter.get(x))),
543
+ wall = walls.find((x) => enter.get(x) === w),
544
+ p = Math.max(-1, ...partners.map((x) => enter.get(x)));
545
+ if (p >= w) {
546
+ const later = partners.find((x) => enter.get(x) === p);
547
+ return {
548
+ problem: {
549
+ ids: [wall, later],
550
+ why: `${wall} would stand over the screws of ${m.items.join(', ')} before ${later}, which they fasten to, is on`,
551
+ stuck: {
552
+ item: m.items[0],
553
+ wall,
554
+ text: `the screws of ${m.items.join(', ')} can't be reached: ${wall} stands over them, and it goes on before ${later}, which they fasten to`,
555
+ },
556
+ },
557
+ };
558
+ }
262
559
  steps.splice(w, 0, mountStep(m));
263
560
  }
264
561
  // the bays no side squared, once the frame is joined
265
562
  const later = bays.filter((b) => !sides.includes(b));
266
- if (later.length) step({ kind: 'square', items: [...new Set(later.flatMap((b) => b.beams))], text: `Square the frame, then tighten its joins: measure the diagonals of each bay${sides.length ? ' the sides did not' : ''}, push the corners of the long diagonal together until each is within, then tighten each join to its torque and measure again`, lines: later.map((b) => `${b.name}: ${b.square.text}`) });
563
+ if (later.length)
564
+ step({
565
+ kind: 'square',
566
+ items: [...new Set(later.flatMap((b) => b.beams))],
567
+ text: `Square the frame, then tighten its joins: measure the diagonals of each bay${sides.length ? ' the sides did not' : ''}, push the corners of the long diagonal together until each is within, then tighten each join to its torque and measure again`,
568
+ lines: later.map((b) => `${b.name}: ${b.square.text}`),
569
+ });
267
570
  for (const m of late) step(mountStep(m));
268
571
  // every screw reached: what stands over a screw goes on after the step that drives it (a join's, or the later of the
269
572
  // parts it fastens); on the bench, against the side's own beams only
270
573
  const { at: atJ, enter, own } = where();
271
574
  for (const cv of covers) {
272
- const j = cv.fasten != null ? joins.find((x) => x.fasten.includes(cv.fasten)) : null, drive = j ? atJ.get(j.index) : Math.max(...cv.screwed.map((id) => enter.get(id) ?? -1));
575
+ const j = cv.fasten != null ? joins.find((x) => x.fasten.includes(cv.fasten)) : null,
576
+ drive = j ? atJ.get(j.index) : Math.max(...cv.screwed.map((id) => enter.get(id) ?? -1));
273
577
  if (drive == null || drive < 0) continue;
274
- const onBench = j && bench.has(j.items[0]) && bench.get(j.items[0]) === bench.get(j.items[1]) && drive < enter.get(j.items[0]);
275
- const wallAt = onBench ? (bench.get(cv.wall) === bench.get(j.items[0]) ? own.get(cv.wall) : undefined) : enter.get(cv.wall);
578
+ const onBench =
579
+ j && bench.has(j.items[0]) && bench.get(j.items[0]) === bench.get(j.items[1]) && drive < enter.get(j.items[0]);
580
+ const wallAt = onBench
581
+ ? bench.get(cv.wall) === bench.get(j.items[0])
582
+ ? own.get(cv.wall)
583
+ : undefined
584
+ : enter.get(cv.wall);
276
585
  if (wallAt == null || wallAt >= drive) continue;
277
- return { problem: { ids: [cv.wall, ...cv.screwed], why: `${cv.wall} would stand over the screw of ${cv.fit} before it is driven`, stuck: { item: cv.screwed.at(-1), wall: cv.wall, text: `the screw of "${cv.fit}" can't be reached with the frame built beam by beam: ${cv.wall} goes on before it and stands over it` } } };
586
+ return {
587
+ problem: {
588
+ ids: [cv.wall, ...cv.screwed],
589
+ why: `${cv.wall} would stand over the screw of ${cv.fit} before it is driven`,
590
+ stuck: {
591
+ item: cv.screwed.at(-1),
592
+ wall: cv.wall,
593
+ text: `the screw of "${cv.fit}" can't be reached with the frame built beam by beam: ${cv.wall} goes on before it and stands over it`,
594
+ },
595
+ },
596
+ };
278
597
  }
279
598
  // what goes into each slot and when: every head and every nut with a way in at its step (slotPlan)
280
599
  const plan = slotPlan(s, steps, L, where);
281
600
  if (plan.fail) {
282
- const f = plan.fail, st = f.o.type === 'head' ? steps[f.o.step] : null;
283
- if (st && st.kind === 'join' && st.side != null && (st.items ?? []).length > 1) return { problem: { bay: sides[st.side], why: `the head of the ${f.o.j.label} has no way into ${f.o.item}'s ${f.o.named} slot as it goes on: ${f.why}` } };
284
- return { problem: { ids: [], why: f.text, stuck: { item: f.o.item, place: f.o.place, text: f.text, ...(f.o.type === 'head' ? { join: f.o.j.index } : { fasten: f.o.g.rel.index, nut: f.o.g.nut }) } } };
601
+ const f = plan.fail,
602
+ st = f.o.type === 'head' ? steps[f.o.step] : null;
603
+ if (st && st.kind === 'join' && st.side != null && (st.items ?? []).length > 1)
604
+ return {
605
+ problem: {
606
+ bay: sides[st.side],
607
+ why: `the head of the ${f.o.j.label} has no way into ${f.o.item}'s ${f.o.named} slot as it goes on: ${f.why}`,
608
+ },
609
+ };
610
+ return {
611
+ problem: {
612
+ ids: [],
613
+ why: f.text,
614
+ stuck: {
615
+ item: f.o.item,
616
+ place: f.o.place,
617
+ text: f.text,
618
+ ...(f.o.type === 'head' ? { join: f.o.j.index } : { fasten: f.o.g.rel.index, nut: f.o.g.nut }),
619
+ },
620
+ },
621
+ };
285
622
  }
286
623
  for (const [i, d] of plan.dirs) steps[i].dir = d;
287
624
  const { enter: entered } = where();
288
- for (const ld of [...plan.loads].sort((x, y) => y.k - x.k)) steps.splice(ld.k, 0, { kind: 'load', items: [ld.o.item], enters: [], ...(bench.has(ld.o.item) && ld.k < entered.get(ld.o.item) ? { side: bench.get(ld.o.item), bench: true } : {}), text: ld.text });
625
+ for (const ld of [...plan.loads].sort((x, y) => y.k - x.k))
626
+ steps.splice(ld.k, 0, {
627
+ kind: 'load',
628
+ items: [ld.o.item],
629
+ enters: [],
630
+ ...(bench.has(ld.o.item) && ld.k < entered.get(ld.o.item) ? { side: bench.get(ld.o.item), bench: true } : {}),
631
+ text: ld.text,
632
+ });
289
633
  // what is in view at each step: the side on the bench, or the frame so far
290
- const frameNow = new Set(), benchNow = new Map();
634
+ const frameNow = new Set(),
635
+ benchNow = new Map();
291
636
  steps.forEach((x, i) => {
292
637
  x.n = i + 1;
293
638
  const onBench = x.bench && x.side != null;
294
- if (onBench) { const b = benchNow.get(x.side) ?? new Set(); for (const id of x.kind === 'square' ? [] : x.items ?? []) b.add(id); benchNow.set(x.side, b); }
639
+ if (onBench) {
640
+ const b = benchNow.get(x.side) ?? new Set();
641
+ for (const id of x.kind === 'square' ? [] : (x.items ?? [])) b.add(id);
642
+ benchNow.set(x.side, b);
643
+ }
295
644
  for (const id of x.enters) frameNow.add(id);
296
- for (const id of x.kind === 'join' && !onBench ? x.items ?? [] : []) frameNow.add(id);
645
+ for (const id of x.kind === 'join' && !onBench ? (x.items ?? []) : []) frameNow.add(id);
297
646
  for (const [id, jj] of fittings) if (jj && (x.joins ?? []).includes(jj.index)) frameNow.add(id);
298
647
  x.shown = [...(onBench ? benchNow.get(x.side) : frameNow)];
299
- x.now = ['side', 'join', 'mount'].includes(x.kind) ? [...(x.items ?? []), ...[...fittings].filter(([, jj]) => (x.joins ?? []).includes(jj.index)).map(([id]) => id)] : [];
648
+ x.now = ['side', 'join', 'mount'].includes(x.kind)
649
+ ? [
650
+ ...(x.items ?? []),
651
+ ...[...fittings].filter(([, jj]) => (x.joins ?? []).includes(jj.index)).map(([id]) => id),
652
+ ]
653
+ : [];
300
654
  x.dir ??= x.now.length === 1 ? dirOf(x.now[0]) : [0, 0, 1];
301
- delete x.enters; delete x.bench;
655
+ delete x.enters;
656
+ delete x.bench;
302
657
  });
303
658
  // a join made before its bay is squared is left snug, and tightened at that square step, which says so too
304
- steps.forEach((x, i) => { if (x.kind !== 'join' || !x.joins?.length) return; const sq = steps.slice(i + 1).find((y) => y.kind === 'square'); if (sq) x.lines = [...(x.lines ?? []), `Snug for now: tightened to its torque at step ${sq.n}, once square`]; });
659
+ steps.forEach((x, i) => {
660
+ if (x.kind !== 'join' || !x.joins?.length) return;
661
+ const sq = steps.slice(i + 1).find((y) => y.kind === 'square');
662
+ if (sq) x.lines = [...(x.lines ?? []), `Snug for now: tightened to its torque at step ${sq.n}, once square`];
663
+ });
305
664
  // the tightening of each kind of join: the least its screws' seats take, or the torque given (thread: where that
306
665
  // least is half what a thread in plastic strips at)
307
666
  const byKind = new Map();
308
- for (const j of joins) for (const f of s.fits.filter((q) => j.fasten.includes(q.fasten) && q.tighten)) {
309
- const k = byKind.get(j.kind) ?? { kind: j.kind, joins: 0, fasteners: new Set(), keys: new Set(), torque: Infinity, given: false, load: false, thread: false };
310
- k.thread = f.tighten.torque < k.torque ? !!f.tighten.thread : k.thread || (f.tighten.torque === k.torque && !!f.tighten.thread); k.torque = Math.min(k.torque, f.tighten.torque); k.given ||= !!f.tighten.given; k.load ||= !!f.tighten.load; if (f.fastener) k.fasteners.add(f.fastener); if (f.key) k.keys.add(f.key);
311
- byKind.set(j.kind, k);
312
- }
667
+ for (const j of joins)
668
+ for (const f of s.fits.filter((q) => j.fasten.includes(q.fasten) && q.tighten)) {
669
+ const k = byKind.get(j.kind) ?? {
670
+ kind: j.kind,
671
+ joins: 0,
672
+ fasteners: new Set(),
673
+ keys: new Set(),
674
+ torque: Infinity,
675
+ given: false,
676
+ load: false,
677
+ thread: false,
678
+ };
679
+ k.thread =
680
+ f.tighten.torque < k.torque
681
+ ? !!f.tighten.thread
682
+ : k.thread || (f.tighten.torque === k.torque && !!f.tighten.thread);
683
+ k.torque = Math.min(k.torque, f.tighten.torque);
684
+ k.given ||= !!f.tighten.given;
685
+ k.load ||= !!f.tighten.load;
686
+ if (f.fastener) k.fasteners.add(f.fastener);
687
+ if (f.key) k.keys.add(f.key);
688
+ byKind.set(j.kind, k);
689
+ }
313
690
  for (const j of joins) if (byKind.has(j.kind)) byKind.get(j.kind).joins++;
314
- const torques = [...byKind.values()].map((k) => ({ kind: k.kind, joins: k.joins, fasteners: [...k.fasteners], key: [...k.keys].join(' or '), torque: k.torque,
315
- why: k.given ? 'as given' : k.load ? 'what the joint\'s load leaves the thread' : k.thread ? 'at most: half what the thread in plastic is estimated to strip at, less than the seat under the head takes' : 'at most: what the seat under the head takes (a slot\'s lips under a blind join\'s head, an estimate), or the screw tightened fully, the less' }));
691
+ const torques = [...byKind.values()].map((k) => ({
692
+ kind: k.kind,
693
+ joins: k.joins,
694
+ fasteners: [...k.fasteners],
695
+ key: [...k.keys].join(' or '),
696
+ torque: k.torque,
697
+ why: k.given
698
+ ? 'as given'
699
+ : k.load
700
+ ? "what the joint's load leaves the thread"
701
+ : k.thread
702
+ ? 'at most: half what the thread in plastic is estimated to strip at, less than half what the seat under the head takes'
703
+ : "at most: half what the seat under the head takes (a slot's lips under a blind join's head, an estimate), or the screw tightened fully, the less",
704
+ }));
316
705
  return { steps, torques };
317
706
  }
318
707
  }
@@ -327,84 +716,244 @@ function buildFrame(s) {
327
716
  // step after that does; else it is loaded earlier. Heads are placed first, in the order their beams go on, then nuts.
328
717
  // Returns the loads ({ k: the step they go before, o, text }), each step's way on (dirs), or fail { o, text, why }.
329
718
  function slotPlan(s, steps, L, where) {
330
- const joins = s.joins ?? [], { at, enter, own } = where(), EPS = 1e-3, key = (o) => `${o.item}|${o.place}`;
331
- const namedOf = (id, place) => { const ps = s.objects.find((o) => o.id === id)?.beam?.places ?? [], p = ps.find((q) => q.name === place); return p && ps.filter((q) => q.face === p.face).length === 1 ? p.face : place; };
332
- const first = Math.max(0, steps.findIndex((st) => st.kind !== 'cut' && st.kind !== 'drill')); // (a beam is cut and drilled before anything goes into its slots; loose or on, from then on)
333
- const heads = joins.filter((j) => j.kind === 'blind' && L.has(j.items[1]) && at.has(j.index)).map((j) => ({ type: 'head', id: `h${j.index}`, j, item: j.items[1], place: j.model.b.place, named: namedOf(j.items[1], j.model.b.place), lo: j.model.b.distance, hi: j.model.b.distance, step: at.get(j.index), fastener: s.fits.find((f) => j.fasten.includes(f.fasten) && f.fastener)?.fastener ?? 'screw' }));
719
+ const joins = s.joins ?? [],
720
+ { at, enter } = where(),
721
+ EPS = 1e-3,
722
+ key = (o) => `${o.item}|${o.place}`;
723
+ const namedOf = (id, place) => {
724
+ const ps = s.objects.find((o) => o.id === id)?.beam?.places ?? [],
725
+ p = ps.find((q) => q.name === place);
726
+ return p && ps.filter((q) => q.face === p.face).length === 1 ? p.face : place;
727
+ };
728
+ const first = Math.max(
729
+ 0,
730
+ steps.findIndex((st) => st.kind !== 'cut' && st.kind !== 'drill'),
731
+ ); // (a beam is cut and drilled before anything goes into its slots; loose or on, from then on)
732
+ const heads = joins
733
+ .filter((j) => j.kind === 'blind' && L.has(j.items[1]) && at.has(j.index))
734
+ .map((j) => ({
735
+ type: 'head',
736
+ id: `h${j.index}`,
737
+ j,
738
+ item: j.items[1],
739
+ place: j.model.b.place,
740
+ named: namedOf(j.items[1], j.model.b.place),
741
+ lo: j.model.b.distance,
742
+ hi: j.model.b.distance,
743
+ step: at.get(j.index),
744
+ fastener: s.fits.find((f) => j.fasten.includes(f.fasten) && f.fastener)?.fastener ?? 'screw',
745
+ }));
334
746
  const pre = preloadOf(s);
335
- const nuts = nutGroupsOf(s).filter((g) => L.has(g.item) && enter.has(g.part)).map((g, n) => {
336
- const pl = pre.find((p) => p.fasten === g.rel.index && p.item === g.item && p.place === g.place) ?? null, k0 = pl ? Math.min(...pl.closers.map((j) => at.get(j.index) ?? Infinity)) : null;
337
- return { type: 'nut', id: `n${n}`, g, item: g.item, place: g.place, named: g.named, lo: Math.min(...g.at), hi: Math.max(...g.at), step: enter.get(g.part), slide: g.entry === 'end', pl, k0: Number.isFinite(k0) ? k0 : null };
338
- });
339
- const all = [...heads, ...nuts], closes = [];
340
- for (const sl of new Set(all.map(key))) { const [id, place] = sl.split('|'); for (const c of closuresOf(s, id, place)) if (c.end) { const i = c.join ? at.get(c.join.index) : enter.get(c.item); if (i != null) closes.push({ i, key: sl, end: c.end, join: c.join ?? null, item: c.item ?? null }); } }
341
- const closeSays = (c) => (c.join ? `the ${c.join.label} closes it` : `${c.item} is on it`), inSays = (o) => (o.type === 'head' ? `the head of the ${o.j.label} at ${mm(o.lo)} mm is in the way` : `the ${o.g.at.length} nut${o.g.at.length > 1 ? 's' : ''} for ${o.g.part} at ${o.g.at.map(mm).join(' and ')} mm ${o.g.at.length > 1 ? 'are' : 'is'} in the way`);
747
+ const nuts = nutGroupsOf(s)
748
+ .filter((g) => L.has(g.item) && enter.has(g.part))
749
+ .map((g, n) => {
750
+ const pl = pre.find((p) => p.fasten === g.rel.index && p.item === g.item && p.place === g.place) ?? null,
751
+ k0 = pl ? Math.min(...pl.closers.map((j) => at.get(j.index) ?? Infinity)) : null;
752
+ return {
753
+ type: 'nut',
754
+ id: `n${n}`,
755
+ g,
756
+ item: g.item,
757
+ place: g.place,
758
+ named: g.named,
759
+ lo: Math.min(...g.at),
760
+ hi: Math.max(...g.at),
761
+ step: enter.get(g.part),
762
+ slide: g.entry === 'end',
763
+ pl,
764
+ k0: Number.isFinite(k0) ? k0 : null,
765
+ };
766
+ });
767
+ const all = [...heads, ...nuts],
768
+ closes = [];
769
+ for (const sl of new Set(all.map(key))) {
770
+ const [id, place] = sl.split('|');
771
+ for (const c of closuresOf(s, id, place))
772
+ if (c.end) {
773
+ const i = c.join ? at.get(c.join.index) : enter.get(c.item);
774
+ if (i != null) closes.push({ i, key: sl, end: c.end, join: c.join ?? null, item: c.item ?? null });
775
+ }
776
+ }
777
+ const closeSays = (c) => (c.join ? `the ${c.join.label} closes it` : `${c.item} is on it`),
778
+ inSays = (o) =>
779
+ o.type === 'head'
780
+ ? `the head of the ${o.j.label} at ${mm(o.lo)} mm is in the way`
781
+ : `the ${o.g.at.length} nut${o.g.at.length > 1 ? 's' : ''} for ${o.g.part} at ${o.g.at.map(mm).join(' and ')} mm ${o.g.at.length > 1 ? 'are' : 'is'} in the way`;
342
782
  // one pass over the steps with the loads given (plan: id -> the step it goes before) and only the active heads and nuts
343
783
  const sim = (plan, active) => {
344
- const state = new Map(), slot = (k) => { if (!state.has(k)) state.set(k, { in: [], shut: { a: null, b: null } }); return state.get(k); };
345
- const block = (o, e) => { const st = slot(key(o)); if (st.shut[e]) return closeSays(st.shut[e]); const by = st.in.find((x) => (e === 'a' ? x.hi < o.lo - EPS : x.lo > o.hi + EPS)); return by ? inSays(by) : null; };
346
- const way = (o, order = ['a', 'b']) => order.find((e) => !block(o, e)) ?? null, said = (o) => `from end a ${block(o, 'a')}; from end b ${block(o, 'b')}`;
347
- const dirs = new Map(), ways = new Map(), on = (o) => active.has(o.id);
784
+ const state = new Map(),
785
+ slot = (k) => {
786
+ if (!state.has(k)) state.set(k, { in: [], shut: { a: null, b: null } });
787
+ return state.get(k);
788
+ };
789
+ const block = (o, e) => {
790
+ const st = slot(key(o));
791
+ if (st.shut[e]) return closeSays(st.shut[e]);
792
+ const by = st.in.find((x) => (e === 'a' ? x.hi < o.lo - EPS : x.lo > o.hi + EPS));
793
+ return by ? inSays(by) : null;
794
+ };
795
+ const way = (o, order = ['a', 'b']) => order.find((e) => !block(o, e)) ?? null,
796
+ said = (o) => `from end a ${block(o, 'a')}; from end b ${block(o, 'b')}`;
797
+ const dirs = new Map(),
798
+ ways = new Map(),
799
+ on = (o) => active.has(o.id);
348
800
  for (let i = 0; i <= steps.length; i++) {
349
801
  for (const o of all.filter((x) => on(x) && plan.get(x.id) === i)) {
350
802
  const e = way(o, o.pl?.way === 'b' ? ['b', 'a'] : ['a', 'b']);
351
803
  if (!e) return { fail: { o, i, why: said(o) } };
352
- ways.set(o.id, e); slot(key(o)).in.push(o);
804
+ ways.set(o.id, e);
805
+ slot(key(o)).in.push(o);
353
806
  }
354
807
  if (i === steps.length) break;
355
- const st = steps[i], M = new Set((st.items ?? []).filter((id) => L.has(id)));
808
+ const st = steps[i],
809
+ M = new Set((st.items ?? []).filter((id) => L.has(id)));
356
810
  // the heads that slide in as their beams go on, all one way along the slots
357
- const sliding = heads.filter((h) => on(h) && !plan.has(h.id) && h.step === i), moving = sliding.map((h) => ({ h, a: M.has(h.j.items[0]) && !M.has(h.item), b: M.has(h.item) && !M.has(h.j.items[0]) })).filter((x) => x.a || x.b);
811
+ const sliding = heads.filter((h) => on(h) && !plan.has(h.id) && h.step === i),
812
+ moving = sliding
813
+ .map((h) => ({ h, a: M.has(h.j.items[0]) && !M.has(h.item), b: M.has(h.item) && !M.has(h.j.items[0]) }))
814
+ .filter((x) => x.a || x.b);
358
815
  if (moving.length) {
359
- const u = L.get(moving[0].h.item).d, par = (x) => Math.abs(Math.abs(dot(L.get(x.h.item).d, u)) - 1) < 1e-6, d0 = st.dir && Math.abs(Math.abs(dot(st.dir, u)) - 1) < 1e-6 ? Math.sign(dot(st.dir, u)) : 1;
360
- let chosen = null, why = [];
816
+ const u = L.get(moving[0].h.item).d,
817
+ par = (x) => Math.abs(Math.abs(dot(L.get(x.h.item).d, u)) - 1) < 1e-6,
818
+ d0 = st.dir && Math.abs(Math.abs(dot(st.dir, u)) - 1) < 1e-6 ? Math.sign(dot(st.dir, u)) : 1;
819
+ let chosen = null,
820
+ why = [];
361
821
  for (const sg of [d0, -d0]) {
362
- const dir = u.map((x) => +(x * sg).toFixed(6) || 0), ends = moving.filter(par).map((x) => { const p = dot(L.get(x.h.item).d, dir) > 0; return { x, e: x.a ? (p ? 'b' : 'a') : (p ? 'a' : 'b') }; });
822
+ const dir = u.map((x) => +(x * sg).toFixed(6) || 0),
823
+ ends = moving.filter(par).map((x) => {
824
+ const p = dot(L.get(x.h.item).d, dir) > 0;
825
+ return { x, e: x.a ? (p ? 'b' : 'a') : p ? 'a' : 'b' };
826
+ });
363
827
  const across = moving.find((x) => !par(x)); // (a head whose slot runs across the way the beam goes on can't slide in with it)
364
- if (across) { why.push({ x: across, e: sg > 0 ? 'b' : 'a', by: `its slot runs across the way ${steps[i].items.join(', ')} go${steps[i].items.length > 1 ? '' : 'es'} on` }); continue; }
828
+ if (across) {
829
+ why.push({
830
+ x: across,
831
+ e: sg > 0 ? 'b' : 'a',
832
+ by: `its slot runs across the way ${steps[i].items.join(', ')} go${steps[i].items.length > 1 ? '' : 'es'} on`,
833
+ });
834
+ continue;
835
+ }
365
836
  const bad = ends.find(({ x, e }) => block(x.h, e));
366
- if (!bad) { chosen = { dir, ends }; break; }
837
+ if (!bad) {
838
+ chosen = { dir, ends };
839
+ break;
840
+ }
367
841
  why.push({ ...bad, by: block(bad.x.h, bad.e) });
368
842
  }
369
- if (!chosen) return { fail: { o: why[0].x.h, i, why: why[0].x === why[1].x && why[0].by === why[1].by ? why[0].by : `from end ${why[0].e} ${why[0].by}; from end ${why[1].e} ${why[1].by}` } };
370
- dirs.set(i, chosen.dir); for (const { x, e } of chosen.ends) ways.set(x.h.id, e);
843
+ if (!chosen)
844
+ return {
845
+ fail: {
846
+ o: why[0].x.h,
847
+ i,
848
+ why:
849
+ why[0].x === why[1].x && why[0].by === why[1].by
850
+ ? why[0].by
851
+ : `from end ${why[0].e} ${why[0].by}; from end ${why[1].e} ${why[1].by}`,
852
+ },
853
+ };
854
+ dirs.set(i, chosen.dir);
855
+ for (const { x, e } of chosen.ends) ways.set(x.h.id, e);
371
856
  }
372
857
  for (const h of sliding) slot(key(h)).in.push(h);
373
858
  // nuts with their part: a slide-in nut not loaded beforehand needs its way now
374
859
  for (const o of nuts.filter((x) => on(x) && !plan.has(x.id) && x.step === i)) {
375
- if (o.slide) { const e = way(o); if (!e) return { fail: { o, i, why: said(o) } }; ways.set(o.id, e); }
860
+ if (o.slide) {
861
+ const e = way(o);
862
+ if (!e) return { fail: { o, i, why: said(o) } };
863
+ ways.set(o.id, e);
864
+ }
376
865
  slot(key(o)).in.push(o);
377
866
  }
378
867
  for (const c of closes.filter((x) => x.i === i)) slot(c.key).shut[c.end] ||= c;
379
868
  }
380
869
  return { dirs, ways };
381
870
  };
382
- const plan = new Map(), active = new Set(nuts.filter((o) => !o.slide).map((o) => o.id)), stuck = [];
383
- const ok = () => !sim(plan, active).fail, tryAt = (o, ks) => { for (const k of ks) { if (k == null) plan.delete(o.id); else plan.set(o.id, k); if (ok()) return true; } plan.delete(o.id); return false; };
384
- const down = (from, to) => { const out = []; for (let k = from; k >= to; k--) out.push(k); return out; };
385
- for (const h of [...heads].sort((p, q) => p.step - q.step)) { active.add(h.id); if (!tryAt(h, [null, ...down(h.step, first)])) { active.delete(h.id); stuck.push(h); } }
871
+ const plan = new Map(),
872
+ active = new Set(nuts.filter((o) => !o.slide).map((o) => o.id)),
873
+ stuck = [];
874
+ const ok = () => !sim(plan, active).fail,
875
+ tryAt = (o, ks) => {
876
+ for (const k of ks) {
877
+ if (k == null) plan.delete(o.id);
878
+ else plan.set(o.id, k);
879
+ if (ok()) return true;
880
+ }
881
+ plan.delete(o.id);
882
+ return false;
883
+ };
884
+ const down = (from, to) => {
885
+ const out = [];
886
+ for (let k = from; k >= to; k--) out.push(k);
887
+ return out;
888
+ };
889
+ for (const h of [...heads].sort((p, q) => p.step - q.step)) {
890
+ active.add(h.id);
891
+ if (!tryAt(h, [null, ...down(h.step, first)])) {
892
+ active.delete(h.id);
893
+ stuck.push(h);
894
+ }
895
+ }
386
896
  for (const o of nuts.filter((x) => x.slide).sort((p, q) => p.step - q.step)) {
387
897
  active.add(o.id);
388
- const lo = first, ks = o.k0 != null ? [o.k0, ...Array.from({ length: Math.max(0, o.step - o.k0) }, (_, n) => o.k0 + n + 1), ...down(o.k0 - 1, lo)] : [null, ...down(o.step, lo)];
389
- if (!tryAt(o, ks)) { active.delete(o.id); stuck.push(o); }
898
+ const lo = first,
899
+ ks =
900
+ o.k0 != null
901
+ ? [o.k0, ...Array.from({ length: Math.max(0, o.step - o.k0) }, (_, n) => o.k0 + n + 1), ...down(o.k0 - 1, lo)]
902
+ : [null, ...down(o.step, lo)];
903
+ if (!tryAt(o, ks)) {
904
+ active.delete(o.id);
905
+ stuck.push(o);
906
+ }
390
907
  }
391
908
  if (stuck.length) {
392
- const o = stuck[0]; active.add(o.id);
393
- const r = sim(plan, active), why = r.fail?.o === o ? r.fail.why : 'every way in is closed or taken at every step it could go in';
394
- const text = o.type === 'head' ? `the head of the ${o.j.label} has no way into ${o.item}'s ${o.named} slot, at its step or before: ${why}` : `${o.item}'s ${o.named} slot: ${o.g.at.length} ${o.g.kind} nut${o.g.at.length > 1 ? 's' : ''} (${o.g.nut}) for ${o.g.part} have no way in at any step: ${why}. A nut that goes in through the opening, or the part on another slot`;
909
+ const o = stuck[0];
910
+ active.add(o.id);
911
+ const r = sim(plan, active),
912
+ why = r.fail?.o === o ? r.fail.why : 'every way in is closed or taken at every step it could go in';
913
+ const text =
914
+ o.type === 'head'
915
+ ? `the head of the ${o.j.label} has no way into ${o.item}'s ${o.named} slot, at its step or before: ${why}`
916
+ : `${o.item}'s ${o.named} slot: ${o.g.at.length} ${o.g.kind} nut${o.g.at.length > 1 ? 's' : ''} (${o.g.nut}) for ${o.g.part} have no way in at any step: ${why}. A nut that goes in through the opening, or the part on another slot`;
395
917
  return { fail: { o, text, why } };
396
918
  }
397
919
  const r = sim(plan, active);
398
920
  // each load said: its way, and what closes that way after it (a head or nut coming between, the end closed)
399
921
  const timeOf = (o) => (plan.has(o.id) ? plan.get(o.id) - 0.5 : o.step);
400
922
  const loads = [...plan].map(([id, k]) => {
401
- const o = all.find((x) => x.id === id), e = r.ways.get(id), t = k - 0.5, sl = key(o);
402
- const between = all.filter((x) => x !== o && key(x) === sl && timeOf(x) > t && (e === 'a' ? x.hi < o.lo - EPS : x.lo > o.hi + EPS)).map((x) => ({ t: timeOf(x), says: x.type === 'head' ? `the ${x.j.label} is made` : `the nuts for ${x.g.part} go in` }));
403
- const shut = closes.filter((c) => c.key === sl && c.end === e && c.i >= k).map((c) => ({ t: c.i, says: c.join ? `the ${c.join.label} is made` : `${c.item} goes on` }));
404
- const next = [...between, ...shut].sort((p, q) => p.t - q.t)[0], before = next ? `, before ${next.says}` : '';
405
- if (o.type === 'head') return { k, o, text: `Slide ${/^[aeiou8]|^M/i.test(o.fastener) ? 'an' : 'a'} ${o.fastener} screw into ${o.item}'s ${o.named} slot head first, through its end ${e}, to ${mm(o.lo)} mm, for the ${o.j.label}${before}: that join is made with it in place, the screw turned into ${o.j.items[0]}'s end through the access hole` };
406
- if (o.pl && k === o.k0 && e === o.pl.way) { const first = o.pl.closers.find((j) => at.get(j.index) === k); return { k, o, text: `Load${o.pl.text.slice(4)}: the next step makes ${o.pl.closers.length > 1 ? `the ${first.label}` : 'that join'}` }; }
407
- return { k, o, text: `Load ${o.g.at.length} × ${o.g.nut} into ${o.item}'s ${o.named} slot through its end ${e}, for ${o.g.part}${before}` };
923
+ const o = all.find((x) => x.id === id),
924
+ e = r.ways.get(id),
925
+ t = k - 0.5,
926
+ sl = key(o);
927
+ const between = all
928
+ .filter((x) => x !== o && key(x) === sl && timeOf(x) > t && (e === 'a' ? x.hi < o.lo - EPS : x.lo > o.hi + EPS))
929
+ .map((x) => ({
930
+ t: timeOf(x),
931
+ says: x.type === 'head' ? `the ${x.j.label} is made` : `the nuts for ${x.g.part} go in`,
932
+ }));
933
+ const shut = closes
934
+ .filter((c) => c.key === sl && c.end === e && c.i >= k)
935
+ .map((c) => ({ t: c.i, says: c.join ? `the ${c.join.label} is made` : `${c.item} goes on` }));
936
+ const next = [...between, ...shut].sort((p, q) => p.t - q.t)[0],
937
+ before = next ? `, before ${next.says}` : '';
938
+ if (o.type === 'head')
939
+ return {
940
+ k,
941
+ o,
942
+ text: `Slide ${/^[aeiou8]|^M/i.test(o.fastener) ? 'an' : 'a'} ${o.fastener} screw into ${o.item}'s ${o.named} slot head first, through its end ${e}, to ${mm(o.lo)} mm, for the ${o.j.label}${before}: that join is made with it in place, the screw turned into ${o.j.items[0]}'s end through the access hole`,
943
+ };
944
+ if (o.pl && k === o.k0 && e === o.pl.way) {
945
+ const first = o.pl.closers.find((j) => at.get(j.index) === k);
946
+ return {
947
+ k,
948
+ o,
949
+ text: `Load${o.pl.text.slice(4)}: the next step makes ${o.pl.closers.length > 1 ? `the ${first.label}` : 'that join'}`,
950
+ };
951
+ }
952
+ return {
953
+ k,
954
+ o,
955
+ text: `Load ${o.g.at.length} × ${o.g.nut} into ${o.item}'s ${o.named} slot through its end ${e}, for ${o.g.part}${before}`,
956
+ };
408
957
  });
409
958
  return { loads, dirs: r.dirs };
410
959
  }
@@ -412,31 +961,68 @@ function slotPlan(s, steps, L, where) {
412
961
  /** Each step's picture, numbered as the frame's build is: what is in view, the beams or parts going on held off along their way. @param {object} s @param {object} b frameBuild's @returns {{ n: number, parts: object[] }[]} the steps with something to show */
413
962
  export function frameStepPictures(s, b) {
414
963
  let off = 40;
415
- for (const p of s.parts) for (const t of p.triangles) for (const v of t) off = Math.max(off, Math.abs(v[0]), Math.abs(v[1]), Math.abs(v[2]));
964
+ for (const p of s.parts)
965
+ for (const t of p.triangles) for (const v of t) off = Math.max(off, Math.abs(v[0]), Math.abs(v[1]), Math.abs(v[2]));
416
966
  off *= 0.25;
417
- return b.steps.filter((st) => st.shown.length).map((st) => {
418
- const shown = new Set(st.shown), now = new Set(st.now);
419
- return { n: st.n, parts: s.parts.filter((p) => shown.has(p.item)).map((p) => (now.has(p.item) ? { ...p, role: 'part', triangles: p.triangles.map((t) => t.map((v) => v.map((c, k) => c + st.dir[k] * off))) } : { ...p, role: 'reference' })) };
420
- });
967
+ return b.steps
968
+ .filter((st) => st.shown.length)
969
+ .map((st) => {
970
+ const shown = new Set(st.shown),
971
+ now = new Set(st.now);
972
+ return {
973
+ n: st.n,
974
+ parts: s.parts
975
+ .filter((p) => shown.has(p.item))
976
+ .map((p) =>
977
+ now.has(p.item)
978
+ ? {
979
+ ...p,
980
+ role: 'part',
981
+ triangles: p.triangles.map((t) => t.map((v) => v.map((c, k) => c + st.dir[k] * off))),
982
+ }
983
+ : { ...p, role: 'reference' },
984
+ ),
985
+ };
986
+ });
421
987
  }
422
988
 
423
989
  /** The frame's build as text, for cad order. @param {string} ref @param {object} b frameBuild's */
424
990
  export function frameBuildText(ref, b) {
425
991
  if (b.stuck) return `${ref}: ${b.stuck.text}`;
426
992
  const out = [`${ref}: from bars to a square frame`];
427
- for (const st of b.steps) { out.push(` ${String(st.n).padStart(2)}. ${st.text}`); for (const l of st.lines ?? []) out.push(` ${l}`); }
993
+ for (const st of b.steps) {
994
+ out.push(` ${String(st.n).padStart(2)}. ${st.text}`);
995
+ for (const l of st.lines ?? []) out.push(` ${l}`);
996
+ }
428
997
  for (const x of b.notFlat ?? []) out.push(` The bay of ${x.name} is built on the frame, not flat: ${x.why}`);
429
- if (b.torques.length) { out.push(' Tightening, by kind of join:'); for (const t of b.torques) out.push(` ${t.kind} (${t.joins} join${t.joins > 1 ? 's' : ''}, ${t.fasteners.join(', ')}${t.key ? ` with ${/^[aeiou8]/i.test(t.key) ? 'an' : 'a'} ${t.key}` : ''}): ${mm(t.torque)} N m, ${t.why}`); }
998
+ if (b.torques.length) {
999
+ out.push(' Tightening, by kind of join:');
1000
+ for (const t of b.torques)
1001
+ out.push(
1002
+ ` ${t.kind} (${t.joins} join${t.joins > 1 ? 's' : ''}, ${t.fasteners.join(', ')}${t.key ? ` with ${/^[aeiou8]/i.test(t.key) ? 'an' : 'a'} ${t.key}` : ''}): ${mm(t.torque)} N m, ${t.why}`,
1003
+ );
1004
+ }
430
1005
  return out.join('\n');
431
1006
  }
432
1007
 
433
-
434
1008
  // The latest measurement of each prediction in the project's ledger (cad measured writes it), by name
435
1009
  function measuredOf(s) {
436
1010
  let text = '';
437
- try { text = fs.readFileSync(path.join(paths.project(s.project), 'ledger.jsonl'), 'utf8'); } catch { return new Map(); }
1011
+ try {
1012
+ text = readOwnText(path.join(paths.project(s.project), 'ledger.jsonl'));
1013
+ } catch {
1014
+ return new Map();
1015
+ }
438
1016
  const out = new Map();
439
- for (const l of text.split('\n')) { if (!l.trim()) continue; try { const e = JSON.parse(l); if (e.assembly === s.name && typeof e.measured === 'number') out.set(e.name, e); } catch {} }
1017
+ for (const l of text.split('\n')) {
1018
+ if (!l.trim()) continue;
1019
+ try {
1020
+ const e = JSON.parse(l);
1021
+ if (e.assembly === s.name && typeof e.measured === 'number') out.set(e.name, e);
1022
+ } catch {
1023
+ // (a line that isn't JSON (a write cut short): skipped)
1024
+ }
1025
+ }
440
1026
  return out;
441
1027
  }
442
1028
 
@@ -450,15 +1036,44 @@ export function frameSquareChecks(s, f) {
450
1036
  if (!s.joins?.length) return;
451
1037
  const measured = measuredOf(s);
452
1038
  let bays;
453
- try { bays = baysOf(s); } catch (e) { f('fail', e.message, 'frame.cut: refused', { code: 'frame.square' }); return; }
1039
+ try {
1040
+ bays = baysOf(s);
1041
+ } catch (e) {
1042
+ f('fail', e.message, 'frame.cut: refused', { code: 'frame.square' });
1043
+ return;
1044
+ }
454
1045
  for (const b of bays) {
455
- const q = b.square, name = `frame.square.${b.beams.join('-')}`, m = measured.get(name), soft = q.terms.filter((x) => x.kind === 'estimate');
1046
+ const q = b.square,
1047
+ name = `frame.square.${b.beams.join('-')}`,
1048
+ m = measured.get(name),
1049
+ soft = q.terms.filter((x) => x.kind === 'estimate');
456
1050
  const parts = `${q.terms.map((x) => `${x.term} ${mm(x.value)}`).join(', ')} mm`;
457
- const rests = soft.length ? ` It rests on estimates (${soft.map((x) => x.term).join(', ')}): measure the diagonals once it is squared and tightened, and give their difference to cad measured ${s.project}/${s.name} ${name}=<mm>` : '';
458
- let level = 'info', said = '';
459
- if (m) { const d = Math.abs(m.measured), over = d > q.accept + 1e-9; level = over ? 'warn' : 'pass'; said = ` Measured ${mm(m.measured)} mm (${m.date}${m.measured < 0 ? `, ${mm(d)} mm either way` : ''}): ${over ? `${mm(d / q.accept)} times what its cuts and joins allow, so it leans: loosen its joins, push the long diagonal's corners together, tighten and measure again` : 'within what its cuts and joins allow'}.`; }
460
- f(level, `the bay of ${b.name}: ${q.text}. Its share: ${parts}.${said}${m ? '' : rests}`, level === 'warn' ? `${b.beams.join('-')}: out of square` : null,
461
- { code: 'frame.square', predict: { name, figure: `the difference between the diagonals of the bay of ${b.name}, inside corner to inside corner, squared and tightened`, value: q.accept, unit: 'mm' },
462
- values: { ...q.findings[0].values, ...(m ? { measured: m.measured } : {}) }, refs: { beams: b.beams, joins: b.joins, tolerance: b.tolFrom } });
1051
+ const rests = soft.length
1052
+ ? ` It rests on estimates (${soft.map((x) => x.term).join(', ')}): measure the diagonals once it is squared and tightened, and give their difference to cad measured ${s.project}/${s.name} ${name}=<mm>`
1053
+ : '';
1054
+ let level = 'info',
1055
+ said = '';
1056
+ if (m) {
1057
+ const d = Math.abs(m.measured),
1058
+ over = d > q.accept + 1e-9;
1059
+ level = over ? 'warn' : 'pass';
1060
+ said = ` Measured ${mm(m.measured)} mm (${m.date}${m.measured < 0 ? `, ${mm(d)} mm either way` : ''}): ${over ? `${mm(d / q.accept)} times what its cuts and joins allow, so it leans: loosen its joins, push the long diagonal's corners together, tighten and measure again` : 'within what its cuts and joins allow'}.`;
1061
+ }
1062
+ f(
1063
+ level,
1064
+ `the bay of ${b.name}: ${q.text}. Its share: ${parts}.${said}${m ? '' : rests}`,
1065
+ level === 'warn' ? `${b.beams.join('-')}: out of square` : null,
1066
+ {
1067
+ code: 'frame.square',
1068
+ predict: {
1069
+ name,
1070
+ figure: `the difference between the diagonals of the bay of ${b.name}, inside corner to inside corner, squared and tightened`,
1071
+ value: q.accept,
1072
+ unit: 'mm',
1073
+ },
1074
+ values: { ...q.findings[0].values, ...(m ? { measured: m.measured } : {}) },
1075
+ refs: { beams: b.beams, joins: b.joins, tolerance: b.tolFrom },
1076
+ },
1077
+ );
463
1078
  }
464
1079
  }