@rulecad/cad 0.8.0 → 0.10.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 (102) hide show
  1. package/AGENTS.md +45 -16
  2. package/CHANGELOG.md +724 -0
  3. package/EXAMPLES.md +61 -54
  4. package/README.md +376 -98
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2664 -541
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1883 -435
  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/cache-file.mjs +105 -0
  15. package/lib/carried.mjs +201 -0
  16. package/lib/clone.mjs +194 -42
  17. package/lib/code-text.mjs +28 -0
  18. package/lib/design-imports.mjs +127 -0
  19. package/lib/design.mjs +871 -147
  20. package/lib/designshapes.mjs +142 -0
  21. package/lib/drive.mjs +187 -63
  22. package/lib/edit.mjs +922 -192
  23. package/lib/errors.mjs +16 -3
  24. package/lib/estimates.mjs +51 -0
  25. package/lib/explain.mjs +62 -13
  26. package/lib/fasten.mjs +2708 -507
  27. package/lib/fe-key.mjs +29 -0
  28. package/lib/fittings.mjs +721 -122
  29. package/lib/fixings.mjs +38 -13
  30. package/lib/framebuild.mjs +790 -175
  31. package/lib/framecheck.mjs +1901 -368
  32. package/lib/framegen.mjs +108 -22
  33. package/lib/frameheat.mjs +225 -42
  34. package/lib/frameprint.mjs +513 -108
  35. package/lib/frames.mjs +86 -18
  36. package/lib/framesize.mjs +719 -120
  37. package/lib/frametip.mjs +235 -0
  38. package/lib/gait.mjs +135 -23
  39. package/lib/grip.mjs +62 -13
  40. package/lib/guides.mjs +1403 -230
  41. package/lib/host.mjs +129 -23
  42. package/lib/inplace.mjs +171 -36
  43. package/lib/jigs.mjs +360 -78
  44. package/lib/joins.mjs +697 -118
  45. package/lib/jsonedit.mjs +88 -26
  46. package/lib/kept.mjs +84 -0
  47. package/lib/kit.mjs +439 -69
  48. package/lib/layout.mjs +2 -1
  49. package/lib/links.mjs +149 -42
  50. package/lib/list.mjs +334 -64
  51. package/lib/live-guard.mjs +68 -0
  52. package/lib/live-shape.mjs +96 -24
  53. package/lib/live.mjs +189 -59
  54. package/lib/loads.mjs +597 -136
  55. package/lib/machine.mjs +372 -74
  56. package/lib/magnets.mjs +162 -44
  57. package/lib/measured.mjs +1080 -117
  58. package/lib/mesh.mjs +526 -119
  59. package/lib/meshcmd.mjs +215 -60
  60. package/lib/motors.mjs +1002 -214
  61. package/lib/motorsvg.mjs +114 -32
  62. package/lib/names.mjs +18 -1
  63. package/lib/optimise.mjs +991 -287
  64. package/lib/order.mjs +515 -114
  65. package/lib/panels.mjs +482 -94
  66. package/lib/parts.mjs +81 -23
  67. package/lib/pins.mjs +163 -44
  68. package/lib/plates.mjs +223 -35
  69. package/lib/player.mjs +37 -9
  70. package/lib/power.mjs +64 -13
  71. package/lib/preview.mjs +83 -16
  72. package/lib/profilemeasure.mjs +572 -129
  73. package/lib/rules.mjs +17 -6
  74. package/lib/sandbox-hooks.mjs +179 -27
  75. package/lib/sandbox-lock.mjs +225 -0
  76. package/lib/sandbox-preload.mjs +2 -2
  77. package/lib/sandbox-run.mjs +122 -25
  78. package/lib/sandbox.mjs +667 -75
  79. package/lib/schema.mjs +42 -11
  80. package/lib/seats.mjs +227 -49
  81. package/lib/services.mjs +261 -52
  82. package/lib/sheet.mjs +963 -179
  83. package/lib/slotnuts.mjs +213 -34
  84. package/lib/targets/gist.mjs +4 -1
  85. package/lib/targets.mjs +22 -4
  86. package/lib/task.mjs +376 -79
  87. package/lib/versions.mjs +285 -39
  88. package/lib/wires.mjs +228 -45
  89. package/lib/workspace.mjs +200 -14
  90. package/package.json +19 -19
  91. package/schemas/assembly.schema.json +2 -2
  92. package/schemas/project.schema.json +6 -0
  93. package/templates/coupons/MEASURE.md +109 -0
  94. package/templates/coupons/assemblies/fixings-test.json +20 -0
  95. package/templates/coupons/assemblies/slot-test.json +11 -0
  96. package/templates/coupons/objects/fixings-coupon.js +88 -0
  97. package/templates/coupons/objects/fixings-coupon.json +26 -0
  98. package/templates/coupons/objects/holds-coupon.js +130 -0
  99. package/templates/coupons/objects/holds-coupon.json +42 -0
  100. package/templates/coupons/objects/slot-coupon.js +89 -0
  101. package/templates/coupons/objects/slot-coupon.json +29 -0
  102. package/templates/coupons/project.json +10 -0
package/lib/jigs.mjs CHANGED
@@ -9,7 +9,20 @@
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import jscad from '@jscad/modeling';
12
- import { JOINS, beamSheet, workOrder, drillGuideModel, drillGuide, tapGuideModel, tapGuide, lengthStopModel, lengthStop, squareCornerModel, squareCorner, JIG_KINDS } from '@rulecad/frames';
12
+ import {
13
+ JOINS,
14
+ beamSheet,
15
+ workOrder,
16
+ drillGuideModel,
17
+ drillGuide,
18
+ tapGuideModel,
19
+ tapGuide,
20
+ lengthStopModel,
21
+ lengthStop,
22
+ squareCornerModel,
23
+ squareCorner,
24
+ JIG_KINDS,
25
+ } from '@rulecad/frames';
13
26
  import { placeItems } from '@rulecad/model-link';
14
27
  import { text } from '@rulecad/shapes';
15
28
  import { check as printCheck } from '@rulecad/printcheck';
@@ -19,8 +32,10 @@ import { threemf } from './threemf.mjs';
19
32
  import { cutListOf } from './beams.mjs';
20
33
  import { plasticOf } from './fittings.mjs';
21
34
 
22
- const { measureBoundingBox } = jscad.measurements, { translate } = jscad.transforms, { geom3 } = jscad.geometries;
23
- const mm = (x) => String(+Number(x).toFixed(2)), r3 = (x) => +x.toFixed(3);
35
+ const { measureBoundingBox } = jscad.measurements,
36
+ { geom3 } = jscad.geometries;
37
+ const mm = (x) => String(+Number(x).toFixed(2)),
38
+ r3 = (x) => +x.toFixed(3);
24
39
  const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
25
40
  const strip = (e) => String(e?.message ?? e).replace(/^\w+Model: /, '');
26
41
  const HOLES = JIG_KINDS['drill-guide'].ops;
@@ -29,10 +44,26 @@ const SQUARE_JOINS = Object.keys(JOINS).filter((k) => ['blind', 'end-tap'].inclu
29
44
  // The project's printer as frames reads it ({ name, rules }), and as printcheck reads it (plain numbers)
30
45
  function printerFor(project) {
31
46
  let set = null;
32
- try { set = peekRuleSet(printerOf(project)); } catch { set = null; }
47
+ try {
48
+ set = peekRuleSet(printerOf(project));
49
+ } catch {
50
+ set = null;
51
+ }
33
52
  const num = (k, d) => (typeof set?.rules?.[k]?.value === 'number' ? set.rules[k].value : d);
34
53
  const layer = num('layer', 0.2);
35
- return { set, check: { bed: num('bed', 256), overhang: num('overhang', 45), layer, support_gap: num('support_gap', layer), bridge: num('bridge', 5), line: num('line', 0.42), print_gap: num('print_gap', 0.3), foot: num('foot', 0.15) } };
54
+ return {
55
+ set,
56
+ check: {
57
+ bed: num('bed', 256),
58
+ overhang: num('overhang', 45),
59
+ layer,
60
+ support_gap: num('support_gap', layer),
61
+ bridge: num('bridge', 5),
62
+ line: num('line', 0.42),
63
+ print_gap: num('print_gap', 0.3),
64
+ foot: num('foot', 0.15),
65
+ },
66
+ };
36
67
  }
37
68
 
38
69
  // Where a beam item's face lies in the world: its outward normal and a point on it, from the item's placed frame
@@ -44,30 +75,66 @@ function faceWorld(W, place, L) {
44
75
 
45
76
  // 4x4s: an item's placed frame (row by row) as JSCAD's (column by column), a product of two of JSCAD's, a point through one
46
77
  const colMajor = (W) => [W[0], W[4], W[8], 0, W[1], W[5], W[9], 0, W[2], W[6], W[10], 0, W[3], W[7], W[11], 1];
47
- const mul = (P, Q) => Array.from({ length: 16 }, (_, i) => { const c = Math.floor(i / 4), r = i % 4; return P[r] * Q[4 * c] + P[4 + r] * Q[4 * c + 1] + P[8 + r] * Q[4 * c + 2] + P[12 + r] * Q[4 * c + 3]; });
78
+ const mul = (P, Q) =>
79
+ Array.from({ length: 16 }, (_, i) => {
80
+ const c = Math.floor(i / 4),
81
+ r = i % 4;
82
+ return P[r] * Q[4 * c] + P[4 + r] * Q[4 * c + 1] + P[8 + r] * Q[4 * c + 2] + P[12 + r] * Q[4 * c + 3];
83
+ });
48
84
  const apply = (M, p) => [0, 1, 2].map((k) => M[k] * p[0] + M[4 + k] * p[1] + M[8 + k] * p[2] + M[12 + k]);
49
85
  // a world point in a beam item's frame (its section in x and y about the envelope's middle, z from end a)
50
- const local = (W, p) => [0, 1, 2].map((k) => W[k] * (p[0] - W[3]) + W[4 + k] * (p[1] - W[7]) + W[8 + k] * (p[2] - W[11]));
51
- const inside = (beam, q, e = 0.01) => Math.abs(q[0]) < beam.profile.width / 2 - e && Math.abs(q[1]) < beam.profile.height / 2 - e && q[2] > e && q[2] < beam.length - e;
52
- const inPolygon = (pts, x, y) => { let c = false; for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const [xi, yi] = pts[i], [xj, yj] = pts[j]; if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) c = !c; } return c; };
86
+ const local = (W, p) =>
87
+ [0, 1, 2].map((k) => W[k] * (p[0] - W[3]) + W[4 + k] * (p[1] - W[7]) + W[8 + k] * (p[2] - W[11]));
88
+ const inside = (beam, q, e = 0.01) =>
89
+ Math.abs(q[0]) < beam.profile.width / 2 - e &&
90
+ Math.abs(q[1]) < beam.profile.height / 2 - e &&
91
+ q[2] > e &&
92
+ q[2] < beam.length - e;
93
+ const inPolygon = (pts, x, y) => {
94
+ let c = false;
95
+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {
96
+ const [xi, yi] = pts[i],
97
+ [xj, yj] = pts[j];
98
+ if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) c = !c;
99
+ }
100
+ return c;
101
+ };
53
102
 
54
103
  // How a squaring corner, fitted in the world by F, sits on its beams: how much of each tongue lies along its own beam
55
104
  // (from the tongue's ends, in that beam's frame), and which beams its plate meets (its outline sampled every 2 mm at
56
105
  // half its thickness). ok where both tongues lie whole on their beams and the plate meets none.
57
106
  function cornerFit(m, F, ai, bi, beams, worlds) {
58
- const t = m.plate.thickness, { a: ta, b: tb } = m.tongues, why = [];
59
- const along = (id, p, q) => { const W = worlds[id], B = beams.get(id), u = local(W, apply(F, p)), v = local(W, apply(F, q)), mid = u.map((x, k) => (x + v[k]) / 2);
107
+ const t = m.plate.thickness,
108
+ { a: ta, b: tb } = m.tongues,
109
+ why = [];
110
+ const along = (id, p, q) => {
111
+ const W = worlds[id],
112
+ B = beams.get(id),
113
+ u = local(W, apply(F, p)),
114
+ v = local(W, apply(F, q)),
115
+ mid = u.map((x, k) => (x + v[k]) / 2);
60
116
  const across = Math.abs(mid[0]) < B.profile.width / 2 && Math.abs(mid[1]) < B.profile.height / 2;
61
- return across ? Math.max(0, Math.min(Math.max(u[2], v[2]), B.length) - Math.max(Math.min(u[2], v[2]), 0)) : 0; };
62
- const on = { a: r3(along(ai, [ta.at, ta.from, t + ta.depth / 2], [ta.at, ta.to, t + ta.depth / 2])), b: r3(along(bi, [tb.from, tb.at, t + tb.depth / 2], [tb.to, tb.at, t + tb.depth / 2])) };
117
+ return across ? Math.max(0, Math.min(Math.max(u[2], v[2]), B.length) - Math.max(Math.min(u[2], v[2]), 0)) : 0;
118
+ };
119
+ const on = {
120
+ a: r3(along(ai, [ta.at, ta.from, t + ta.depth / 2], [ta.at, ta.to, t + ta.depth / 2])),
121
+ b: r3(along(bi, [tb.from, tb.at, t + tb.depth / 2], [tb.to, tb.at, t + tb.depth / 2])),
122
+ };
63
123
  const need = { a: r3(ta.to - ta.from), b: r3(tb.to - tb.from) };
64
- for (const k of ['a', 'b']) if (on[k] < need[k] - 0.01) why.push(`its ${k} tongue has ${mm(on[k])} of its ${mm(need[k])} mm on ${k === 'a' ? ai : bi}, the rest past its end`);
65
- const xs = m.outline.map((p) => p[0]), ys = m.outline.map((p) => p[1]), hits = new Set();
66
- for (let x = Math.min(...xs) + 0.5; x < Math.max(...xs); x += 2) for (let y = Math.min(...ys) + 0.5; y < Math.max(...ys); y += 2) {
67
- if (!inPolygon(m.outline, x, y)) continue;
68
- const w = apply(F, [x, y, t / 2]);
69
- for (const [id, B] of beams) if (worlds[id] && !hits.has(id) && inside(B, local(worlds[id], w))) hits.add(id);
70
- }
124
+ for (const k of ['a', 'b'])
125
+ if (on[k] < need[k] - 0.01)
126
+ why.push(
127
+ `its ${k} tongue has ${mm(on[k])} of its ${mm(need[k])} mm on ${k === 'a' ? ai : bi}, the rest past its end`,
128
+ );
129
+ const xs = m.outline.map((p) => p[0]),
130
+ ys = m.outline.map((p) => p[1]),
131
+ hits = new Set();
132
+ for (let x = Math.min(...xs) + 0.5; x < Math.max(...xs); x += 2)
133
+ for (let y = Math.min(...ys) + 0.5; y < Math.max(...ys); y += 2) {
134
+ if (!inPolygon(m.outline, x, y)) continue;
135
+ const w = apply(F, [x, y, t / 2]);
136
+ for (const [id, B] of beams) if (worlds[id] && !hits.has(id) && inside(B, local(worlds[id], w))) hits.add(id);
137
+ }
71
138
  if (hits.size) why.push(`its plate meets ${[...hits].join(', ')}`);
72
139
  return { ok: !why.length, on, why, short: r3(need.a - on.a + need.b - on.b + 100 * hits.size) };
73
140
  }
@@ -81,63 +148,176 @@ function cornerFit(m, F, ai, bi, beams, worlds) {
81
148
  * @returns {{ jigs: { kind: string, name: string, model: object, for: object[], label: string }[], findings: object[] }}
82
149
  */
83
150
  export function jigsOf(s) {
84
- const c = cutListOf(s), jigs = new Map(), findings = [], printer = printerFor(s.project).set ?? undefined, fx = { ...(printer ? { printer } : {}), material: plasticOf(s.project) }; // (printed in the project's plastic, as its fittings are)
151
+ const c = cutListOf(s),
152
+ jigs = new Map(),
153
+ findings = [],
154
+ printer = printerFor(s.project).set ?? undefined,
155
+ fx = { ...(printer ? { printer } : {}), material: plasticOf(s.project) }; // (printed in the project's plastic, as its fittings are)
85
156
  const warn = (code, txt, refs) => findings.push({ level: 'warn', code, text: txt, refs });
86
- const add = (key, kind, model, who) => { if (!jigs.has(key)) jigs.set(key, { kind, name: model.name, model, for: [] }); jigs.get(key).for.push(who); };
157
+ const add = (key, kind, model, who) => {
158
+ if (!jigs.has(key)) jigs.set(key, { kind, name: model.name, model, for: [] });
159
+ jigs.get(key).for.push(who);
160
+ };
87
161
  if (!c) return { jigs: [], findings };
88
162
  for (const mk of c.marks) {
89
- const b = mk.beam, sheet = beamSheet(b, { mark: mk.mark, items: mk.items });
163
+ const b = mk.beam,
164
+ sheet = beamSheet(b, { mark: mk.mark, items: mk.items });
90
165
  // (each operation by its number on the sheet, the order it is done in; i is its index in the model's ops)
91
- const order = workOrder(b), step = (i) => order.indexOf(i) + 1;
166
+ const order = workOrder(b),
167
+ step = (i) => order.indexOf(i) + 1;
92
168
  b.ops.forEach((x, i) => {
93
- const n = step(i), who = { mark: mk.mark, items: mk.items, op: n, at: x.at, line: x.line };
169
+ const n = step(i),
170
+ who = { mark: mk.mark, items: mk.items, op: n, at: x.at, line: x.line };
94
171
  if (HOLES.includes(x.op)) {
95
172
  try {
96
- const m = drillGuideModel(b, i, fx), z = r3(m.fit[6] * m.bush.at[1] + m.fit[14]); // (the bush's axis, fitted: its distance from end a)
173
+ const m = drillGuideModel(b, i, fx),
174
+ z = r3(m.fit[6] * m.bush.at[1] + m.fit[14]); // (the bush's axis, fitted: its distance from end a)
97
175
  const dim = sheet.dimensions.find((d) => d.op === n);
98
- add(`drill|${m.name}|${m.profile}|${m.plate.span.join(',')}`, 'drill-guide', m, { ...who, label: `${mk.mark}${n}`, from: m.from, distance: m.bush.at[1], bush: z, sheet: dim ? dim.distance : null, sheetText: dim ? dim.text : null });
99
- } catch (e) { warn('jig.drill', `mark ${mk.mark} (${mk.items.join(', ')}), operation ${n}: no drill guide: ${strip(e)}`, { mark: mk.mark, op: n }); }
176
+ add(`drill|${m.name}|${m.profile}|${m.plate.span.join(',')}`, 'drill-guide', m, {
177
+ ...who,
178
+ label: `${mk.mark}${n}`,
179
+ from: m.from,
180
+ distance: m.bush.at[1],
181
+ bush: z,
182
+ sheet: dim ? dim.distance : null,
183
+ sheetText: dim ? dim.text : null,
184
+ });
185
+ } catch (e) {
186
+ warn('jig.drill', `mark ${mk.mark} (${mk.items.join(', ')}), operation ${n}: no drill guide: ${strip(e)}`, {
187
+ mark: mk.mark,
188
+ op: n,
189
+ });
190
+ }
100
191
  }
101
192
  if (x.op === 'tap') {
102
193
  try {
103
194
  const m = tapGuideModel(b, i, fx);
104
- add(`tap|${m.name}|${m.profile}|${JSON.stringify(m.bores)}`, 'tap-guide', m, { ...who, label: `${mk.mark}${n}`, end: x.end, bores: x.bores });
105
- } catch (e) { warn('jig.tap', `mark ${mk.mark} (${mk.items.join(', ')}), operation ${n}: no tap guide: ${strip(e)}`, { mark: mk.mark, op: n }); }
195
+ add(`tap|${m.name}|${m.profile}|${JSON.stringify(m.bores)}`, 'tap-guide', m, {
196
+ ...who,
197
+ label: `${mk.mark}${n}`,
198
+ end: x.end,
199
+ bores: x.bores,
200
+ });
201
+ } catch (e) {
202
+ warn('jig.tap', `mark ${mk.mark} (${mk.items.join(', ')}), operation ${n}: no tap guide: ${strip(e)}`, {
203
+ mark: mk.mark,
204
+ op: n,
205
+ });
206
+ }
106
207
  }
107
208
  });
108
209
  const m = lengthStopModel(b.profile, b.length, fx);
109
- add(`length|${b.profile.name}|${b.length}`, 'length-stop', m, { mark: mk.mark, items: mk.items, label: `${mk.mark} ${mm(b.length)}`, length: b.length });
210
+ add(`length|${b.profile.name}|${b.length}`, 'length-stop', m, {
211
+ mark: mk.mark,
212
+ items: mk.items,
213
+ label: `${mk.mark} ${mm(b.length)}`,
214
+ length: b.length,
215
+ });
110
216
  }
111
217
  // a squaring corner for each square join: on a face of each beam in one plane, of the hand whose arm b lies on b, its
112
218
  // tongues whole on their beams and its plate clear of every beam; the outer pair of faces first, then right-handed
113
219
  const marks = new Map(c.marks.flatMap((mk) => mk.items.map((id) => [id, mk.mark])));
114
- const placed = s.joins?.length ? placeItems(s.motion, s.jointValues) : [], worlds = Object.fromEntries(s.motion.items.map((x, i) => [x[0], placed[i]])), beams = new Map(s.objects.filter((o) => o.beam && !o.unplaced).map((o) => [o.id, o.beam]));
115
- const middle = (() => { const pts = [...beams.keys()].filter((id) => worlds[id]).map((id) => { const W = worlds[id], L = beams.get(id).length; return [W[2] * L / 2 + W[3], W[6] * L / 2 + W[7], W[10] * L / 2 + W[11]]; }); return pts.length ? [0, 1, 2].map((k) => pts.reduce((t, p) => t + p[k], 0) / pts.length) : [0, 0, 0]; })();
116
- const models = new Map(), corner = (...args) => { const key = JSON.stringify(args); if (!models.has(key)) models.set(key, squareCornerModel(...args)); return models.get(key); };
220
+ const placed = s.joins?.length ? placeItems(s.motion, s.jointValues) : [],
221
+ worlds = Object.fromEntries(s.motion.items.map((x, i) => [x[0], placed[i]])),
222
+ beams = new Map(s.objects.filter((o) => o.beam && !o.unplaced).map((o) => [o.id, o.beam]));
223
+ const middle = (() => {
224
+ const pts = [...beams.keys()]
225
+ .filter((id) => worlds[id])
226
+ .map((id) => {
227
+ const W = worlds[id],
228
+ L = beams.get(id).length;
229
+ return [(W[2] * L) / 2 + W[3], (W[6] * L) / 2 + W[7], (W[10] * L) / 2 + W[11]];
230
+ });
231
+ return pts.length ? [0, 1, 2].map((k) => pts.reduce((t, p) => t + p[k], 0) / pts.length) : [0, 0, 0];
232
+ })();
233
+ const models = new Map(),
234
+ corner = (...args) => {
235
+ const key = JSON.stringify(args);
236
+ if (!models.has(key)) models.set(key, squareCornerModel(...args));
237
+ return models.get(key);
238
+ };
117
239
  for (const j of s.joins ?? []) {
118
240
  if (!SQUARE_JOINS.includes(j.kind) || j.model.b.end != null) continue;
119
- const [ai, bi] = j.items, A = beams.get(ai), B = beams.get(bi), Wa = worlds[ai], Wb = worlds[bi];
241
+ const [ai, bi] = j.items,
242
+ A = beams.get(ai),
243
+ B = beams.get(bi),
244
+ Wa = worlds[ai],
245
+ Wb = worlds[bi];
120
246
  if (!A || !B || !Wa || !Wb) continue;
121
- const end = j.end[0], away = [0, 1, 2].map((k) => (end === 'a' ? 1 : -1) * Wa[4 * k + 2]); // along a, away from b
247
+ const end = j.end[0],
248
+ away = [0, 1, 2].map((k) => (end === 'a' ? 1 : -1) * Wa[4 * k + 2]); // along a, away from b
122
249
  const tried = [];
123
- for (const pa of A.places.filter((q) => q.slot)) for (const pb of B.places.filter((q) => q.slot)) {
124
- const fa = faceWorld(Wa, pa, A.length), fb = faceWorld(Wb, pb, B.length);
125
- if (dot(fa.n, fb.n) < 1 - 1e-6 || Math.abs(dot(fa.n, fa.at.map((v, k) => v - fb.at[k]))) > 0.05) continue;
126
- const out = dot(fa.n, fb.at.map((v, k) => v - middle[k])), edge = dot(fb.along, away) > 0 ? 'hi' : 'lo';
127
- for (const hand of ['right', 'left']) {
128
- const m = corner({ profile: A.profile, face: pa.name, end, length: A.length }, { profile: B.profile, face: pb.name, edge }, { hand, ...fx });
129
- tried.push({ pa, pb, hand, out, m, fit: mul(colMajor(Wa), m.fit), ...cornerFit(m, mul(colMajor(Wa), m.fit), ai, bi, beams, worlds) });
250
+ for (const pa of A.places.filter((q) => q.slot))
251
+ for (const pb of B.places.filter((q) => q.slot)) {
252
+ const fa = faceWorld(Wa, pa, A.length),
253
+ fb = faceWorld(Wb, pb, B.length);
254
+ if (
255
+ dot(fa.n, fb.n) < 1 - 1e-6 ||
256
+ Math.abs(
257
+ dot(
258
+ fa.n,
259
+ fa.at.map((v, k) => v - fb.at[k]),
260
+ ),
261
+ ) > 0.05
262
+ )
263
+ continue;
264
+ const out = dot(
265
+ fa.n,
266
+ fb.at.map((v, k) => v - middle[k]),
267
+ ),
268
+ edge = dot(fb.along, away) > 0 ? 'hi' : 'lo';
269
+ for (const hand of ['right', 'left']) {
270
+ const m = corner(
271
+ { profile: A.profile, face: pa.name, end, length: A.length },
272
+ { profile: B.profile, face: pb.name, edge },
273
+ { hand, ...fx },
274
+ );
275
+ tried.push({
276
+ pa,
277
+ pb,
278
+ hand,
279
+ out,
280
+ m,
281
+ fit: mul(colMajor(Wa), m.fit),
282
+ ...cornerFit(m, mul(colMajor(Wa), m.fit), ai, bi, beams, worlds),
283
+ });
284
+ }
130
285
  }
286
+ if (!tried.length) {
287
+ warn(
288
+ 'jig.square',
289
+ `${j.label}: no squaring corner: ${ai} and ${bi} have no slotted faces in one plane for it to key into`,
290
+ { join: j.index },
291
+ );
292
+ continue;
131
293
  }
132
- if (!tried.length) { warn('jig.square', `${j.label}: no squaring corner: ${ai} and ${bi} have no slotted faces in one plane for it to key into`, { join: j.index }); continue; }
133
- const fits = tried.filter((x) => x.ok).sort((x, y) => y.out - x.out || (x.hand === 'right' ? -1 : 1) - (y.hand === 'right' ? -1 : 1));
294
+ const fits = tried
295
+ .filter((x) => x.ok)
296
+ .sort((x, y) => y.out - x.out || (x.hand === 'right' ? -1 : 1) - (y.hand === 'right' ? -1 : 1));
134
297
  if (!fits.length) {
135
298
  const near = [...tried].sort((x, y) => x.short - y.short)[0];
136
- warn('jig.square', `${j.label}: no squaring corner fits: on ${ai}'s ${near.pa.name} and ${bi}'s ${near.pb.name}, the nearest (${near.hand}-handed) ${near.why.join('; ')}. Square this join with an engineer's square`, { join: j.index });
299
+ warn(
300
+ 'jig.square',
301
+ `${j.label}: no squaring corner fits: on ${ai}'s ${near.pa.name} and ${bi}'s ${near.pb.name}, the nearest (${near.hand}-handed) ${near.why.join('; ')}. Square this join with an engineer's square`,
302
+ { join: j.index },
303
+ );
137
304
  continue;
138
305
  }
139
- const best = fits[0], m = best.m;
140
- add(`corner|${m.name}|${JSON.stringify([m.outline, m.tongues])}`, 'square-corner', m, { join: j.index, label: `${marks.get(ai)}${marks.get(bi)}`, marks: [marks.get(ai), marks.get(bi)], items: [ai, bi], faces: [best.pa.name, best.pb.name], end, edge: m.edge, hand: best.hand, on: best.on, fit: best.fit.map(r3), text: j.label });
306
+ const best = fits[0],
307
+ m = best.m;
308
+ add(`corner|${m.name}|${JSON.stringify([m.outline, m.tongues])}`, 'square-corner', m, {
309
+ join: j.index,
310
+ label: `${marks.get(ai)}${marks.get(bi)}`,
311
+ marks: [marks.get(ai), marks.get(bi)],
312
+ items: [ai, bi],
313
+ faces: [best.pa.name, best.pb.name],
314
+ end,
315
+ edge: m.edge,
316
+ hand: best.hand,
317
+ on: best.on,
318
+ fit: best.fit.map(r3),
319
+ text: j.label,
320
+ });
141
321
  }
142
322
  const out = [...jigs.values()].map((x) => ({ ...x, label: labelOf(x) }));
143
323
  return { jigs: out, findings };
@@ -145,41 +325,74 @@ export function jigsOf(s) {
145
325
 
146
326
  // A jig's mark: what it is for, as short as the face it is cut in takes (the first and a + where all do not fit)
147
327
  function labelOf(x) {
148
- const marks = [...new Set(x.for.flatMap((w) => w.marks ?? [w.mark]))].sort().join(''), t = x.kind === 'length-stop' ? `${marks} ${mm(x.model.length)}` : marks;
328
+ const marks = [...new Set(x.for.flatMap((w) => w.marks ?? [w.mark]))].sort().join(''),
329
+ t = x.kind === 'length-stop' ? `${marks} ${mm(x.model.length)}` : marks;
149
330
  return t.length <= 9 ? t : `${t.slice(0, 8)}+`;
150
331
  }
151
332
 
152
333
  // A mark as a 2D outline that fits the room given ([along, across]), or null where none fits
153
334
  function markShape(label, room) {
154
335
  if (!label || !room || room[1] < 2.5 || room[0] < 4) return null;
155
- let h = Math.min(4, room[1] * 0.7), g = text({ text: label, height: h, stroke: 0.6 });
156
- const [lo, hi] = measureBoundingBox(g), w = hi[0] - lo[0];
157
- if (w > room[0]) { h *= room[0] / w; if (h < 2) return null; g = text({ text: label, height: h, stroke: 0.6 }); }
336
+ let h = Math.min(4, room[1] * 0.7),
337
+ g = text({ text: label, height: h, stroke: 0.6 });
338
+ const [lo, hi] = measureBoundingBox(g),
339
+ w = hi[0] - lo[0];
340
+ if (w > room[0]) {
341
+ h *= room[0] / w;
342
+ if (h < 2) return null;
343
+ g = text({ text: label, height: h, stroke: 0.6 });
344
+ }
158
345
  return g;
159
346
  }
160
347
 
161
348
  /** Each jig's printed parts, in print pose and marked: [{ name, solid, count }]. @param {object} x one of jigsOf's */
162
349
  export function jigParts(x) {
163
- const m = x.model, mark = (room) => markShape(x.label, room);
350
+ const m = x.model,
351
+ mark = (room) => markShape(x.label, room);
164
352
  if (x.kind === 'drill-guide') return [{ name: m.name, solid: drillGuide(m, { mark: mark(m.label.room) }), count: 1 }];
165
353
  if (x.kind === 'tap-guide') return [{ name: m.name, solid: tapGuide(m, { mark: mark(m.label?.room) }), count: 1 }];
166
- if (x.kind === 'square-corner') return [{ name: m.name, solid: squareCorner(m, { mark: mark(m.label.room) }), count: 1 }];
167
- return [{ name: `${m.name}-block`, solid: lengthStop(m, { mark: mark(m.label.room) }), count: 1 }, { name: `${m.name}-gauge`, solid: lengthStop(m, { part: 'gauge', mark: mark(m.gaugeLabel.room) }), count: m.gauge.pieces }];
354
+ if (x.kind === 'square-corner')
355
+ return [{ name: m.name, solid: squareCorner(m, { mark: mark(m.label.room) }), count: 1 }];
356
+ return [
357
+ { name: `${m.name}-block`, solid: lengthStop(m, { mark: mark(m.label.room) }), count: 1 },
358
+ {
359
+ name: `${m.name}-gauge`,
360
+ solid: lengthStop(m, { part: 'gauge', mark: mark(m.gaugeLabel.room) }),
361
+ count: m.gauge.pieces,
362
+ },
363
+ ];
168
364
  }
169
365
 
170
- const triangles = (g) => geom3.toPolygons(g).flatMap((p) => p.vertices.slice(1, -1).map((v, i) => [[...p.vertices[0]], [...v], [...p.vertices[i + 2]]]));
366
+ const triangles = (g) =>
367
+ geom3
368
+ .toPolygons(g)
369
+ .flatMap((p) => p.vertices.slice(1, -1).map((v, i) => [[...p.vertices[0]], [...v], [...p.vertices[i + 2]]]));
171
370
 
172
371
  // Shelves on a bed, largest first, each part gap apart: as many beds as it takes
173
372
  function pack(items, bed, gap) {
174
- const sorted = [...items].sort((a, b) => b.size[1] - a.size[1] || b.size[0] - a.size[0]), beds = [], room = bed - 2 * gap;
373
+ const sorted = [...items].sort((a, b) => b.size[1] - a.size[1] || b.size[0] - a.size[0]),
374
+ beds = [],
375
+ room = bed - 2 * gap;
175
376
  for (const p of sorted) {
176
- if (p.size[0] > room || p.size[1] > room) throw new Error(`${p.name} is ${mm(p.size[0])} x ${mm(p.size[1])} mm, more than the ${mm(bed)} mm bed takes`);
377
+ if (p.size[0] > room || p.size[1] > room)
378
+ throw new Error(`${p.name} is ${mm(p.size[0])} x ${mm(p.size[1])} mm, more than the ${mm(bed)} mm bed takes`);
177
379
  let done = false;
178
380
  for (const b of beds) {
179
381
  const shelf = b.shelves.at(-1);
180
- if (shelf.x + p.size[0] <= room + 1e-9) { b.parts.push({ ...p, at: [shelf.x, shelf.y] }); shelf.x += p.size[0] + gap; shelf.h = Math.max(shelf.h, p.size[1]); done = true; break; }
382
+ if (shelf.x + p.size[0] <= room + 1e-9) {
383
+ b.parts.push({ ...p, at: [shelf.x, shelf.y] });
384
+ shelf.x += p.size[0] + gap;
385
+ shelf.h = Math.max(shelf.h, p.size[1]);
386
+ done = true;
387
+ break;
388
+ }
181
389
  const y = shelf.y + shelf.h + gap;
182
- if (y + p.size[1] <= room + 1e-9) { b.shelves.push({ x: p.size[0] + gap, y, h: p.size[1] }); b.parts.push({ ...p, at: [0, y] }); done = true; break; }
390
+ if (y + p.size[1] <= room + 1e-9) {
391
+ b.shelves.push({ x: p.size[0] + gap, y, h: p.size[1] });
392
+ b.parts.push({ ...p, at: [0, y] });
393
+ done = true;
394
+ break;
395
+ }
183
396
  }
184
397
  if (!done) beds.push({ shelves: [{ x: p.size[0] + gap, y: 0, h: p.size[1] }], parts: [{ ...p, at: [0, 0] }] });
185
398
  }
@@ -197,42 +410,111 @@ export const jigFile = (s, n, of) => paths.exports(s.project, `${s.name}.jigs${o
197
410
  * jigs: each with its kind, name, mark, what it is for, grams, margin and what printcheck says of each part
198
411
  */
199
412
  export async function writeJigs(s, { write = true } = {}) {
200
- const { jigs, findings } = jigsOf(s), { check } = printerFor(s.project), dir = paths.exports(s.project), base = `${s.name}.jigs`;
201
- if (write && fs.existsSync(dir)) for (const f of fs.readdirSync(dir)) if (f.startsWith(base) && f.endsWith('.3mf')) fs.rmSync(path.join(dir, f));
202
- const parts = [], rows = [], material = () => { const p = plasticOf(s.project); return typeof p === 'string' ? p : p.name; };
413
+ const { jigs, findings } = jigsOf(s),
414
+ { check } = printerFor(s.project),
415
+ dir = paths.exports(s.project),
416
+ base = `${s.name}.jigs`;
417
+ if (write && fs.existsSync(dir))
418
+ for (const f of fs.readdirSync(dir)) if (f.startsWith(base) && f.endsWith('.3mf')) fs.rmSync(path.join(dir, f));
419
+ const parts = [],
420
+ rows = [],
421
+ material = () => {
422
+ const p = plasticOf(s.project);
423
+ return typeof p === 'string' ? p : p.name;
424
+ };
203
425
  for (const x of jigs) {
204
- const made = jigParts(x), checks = [];
426
+ const made = jigParts(x),
427
+ checks = [];
205
428
  for (const p of made) {
206
- const tris = triangles(p.solid), issues = printCheck(tris, check).filter((f) => f.level === 'fail' || f.level === 'warn');
429
+ const tris = triangles(p.solid),
430
+ issues = printCheck(tris, check).filter((f) => f.level === 'fail' || f.level === 'warn');
207
431
  checks.push({ part: p.name, count: p.count, issues: issues.map((f) => `${f.code}: ${f.text}`) });
208
432
  const [lo, hi] = measureBoundingBox(p.solid);
209
- for (let k = 0; k < p.count; k++) parts.push({ name: p.count > 1 ? `${p.name}-${k + 1}` : p.name, jig: x.name, tris: tris.map((t) => t.map((v) => [v[0] - lo[0], v[1] - lo[1], v[2] - lo[2]])), size: [hi[0] - lo[0], hi[1] - lo[1]] });
210
- for (const f of issues) findings.push({ level: f.level, code: 'jig.print', text: `${p.name}: ${f.text}`, refs: { jig: x.name, check: f.code } });
433
+ for (let k = 0; k < p.count; k++)
434
+ parts.push({
435
+ name: p.count > 1 ? `${p.name}-${k + 1}` : p.name,
436
+ jig: x.name,
437
+ tris: tris.map((t) => t.map((v) => [v[0] - lo[0], v[1] - lo[1], v[2] - lo[2]])),
438
+ size: [hi[0] - lo[0], hi[1] - lo[1]],
439
+ });
440
+ for (const f of issues)
441
+ findings.push({
442
+ level: f.level,
443
+ code: 'jig.print',
444
+ text: `${p.name}: ${f.text}`,
445
+ refs: { jig: x.name, check: f.code },
446
+ });
211
447
  }
212
448
  const m = x.model;
213
- rows.push({ kind: x.kind, name: x.name, mark: x.label, for: x.for, material: m.material, grams: m.grams, margin: m.margin, size: m.size, checks, findings: m.findings.map(({ level, code, text: t, values }) => ({ level, code, text: t, ...(values ? { values } : {}) })) });
449
+ rows.push({
450
+ kind: x.kind,
451
+ name: x.name,
452
+ mark: x.label,
453
+ for: x.for,
454
+ material: m.material,
455
+ grams: m.grams,
456
+ margin: m.margin,
457
+ size: m.size,
458
+ checks,
459
+ findings: m.findings.map(({ level, code, text: t, values }) => ({
460
+ level,
461
+ code,
462
+ text: t,
463
+ ...(values ? { values } : {}),
464
+ })),
465
+ });
214
466
  }
215
- const gap = Math.max(2, Math.ceil((check.print_gap + 2 * check.foot) / check.line - 1e-6) * check.line), beds = parts.length ? pack(parts, check.bed, gap) : [];
467
+ const gap = Math.max(2, Math.ceil((check.print_gap + 2 * check.foot) / check.line - 1e-6) * check.line),
468
+ beds = parts.length ? pack(parts, check.bed, gap) : [];
216
469
  const plates = [];
217
470
  for (const [n, b] of beds.entries()) {
218
- const file = jigFile(s, n + 1, beds.length), half = check.bed / 2 - gap;
219
- const objects = b.parts.map((p) => ({ name: p.name, parts: [{ name: p.name, triangles: p.tris.map((t) => t.map((v) => [v[0] + p.at[0] - half, v[1] + p.at[1] - half, v[2]])), slot: 1 }] }));
220
- if (write) { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, await threemf(objects, { title: `${s.a.title || s.name}: jigs` })); }
471
+ const file = jigFile(s, n + 1, beds.length),
472
+ half = check.bed / 2 - gap;
473
+ const objects = b.parts.map((p) => ({
474
+ name: p.name,
475
+ parts: [
476
+ {
477
+ name: p.name,
478
+ triangles: p.tris.map((t) => t.map((v) => [v[0] + p.at[0] - half, v[1] + p.at[1] - half, v[2]])),
479
+ slot: 1,
480
+ },
481
+ ],
482
+ }));
483
+ if (write) {
484
+ fs.mkdirSync(dir, { recursive: true });
485
+ fs.writeFileSync(file, await threemf(objects, { title: `${s.a.title || s.name}: jigs` }));
486
+ }
221
487
  plates.push({ file, material: material(), parts: b.parts.map((p) => p.name), objects });
222
488
  }
223
- return { jigs: rows, plates: plates.map(({ objects, ...p }) => p), findings, parts: plates.flatMap((p) => p.objects) };
489
+ return {
490
+ jigs: rows,
491
+ plates: plates.map(({ objects, ...p }) => p),
492
+ findings,
493
+ parts: plates.flatMap((p) => p.objects),
494
+ };
224
495
  }
225
496
 
226
497
  /** The jigs as lines for a person: each with its mark, what it is for, its grams and margin, and how it prints. */
227
498
  export function jigsText(ref, r) {
228
499
  const out = [`${ref}: ${r.jigs.length} jig${r.jigs.length === 1 ? '' : 's'}, marked with what each is for`];
229
500
  for (const x of r.jigs) {
230
- const what = x.kind === 'drill-guide' ? x.for.map((w) => `${w.label} (${w.items.join(', ')}: ${w.line}; bush ${mm(w.bush)} mm from end a, the sheet ${w.sheetText})`).join('; ')
231
- : x.kind === 'tap-guide' ? x.for.map((w) => `${w.label} (${w.items.join(', ')}: ${w.line})`).join('; ')
232
- : x.kind === 'length-stop' ? x.for.map((w) => `mark ${w.mark} (${w.items.join(', ')})`).join('; ')
233
- : x.for.map((w) => w.text).join('; ');
501
+ const what =
502
+ x.kind === 'drill-guide'
503
+ ? x.for
504
+ .map(
505
+ (w) =>
506
+ `${w.label} (${w.items.join(', ')}: ${w.line}; bush ${mm(w.bush)} mm from end a, the sheet ${w.sheetText})`,
507
+ )
508
+ .join('; ')
509
+ : x.kind === 'tap-guide'
510
+ ? x.for.map((w) => `${w.label} (${w.items.join(', ')}: ${w.line})`).join('; ')
511
+ : x.kind === 'length-stop'
512
+ ? x.for.map((w) => `mark ${w.mark} (${w.items.join(', ')})`).join('; ')
513
+ : x.for.map((w) => w.text).join('; ');
234
514
  const bad = x.checks.flatMap((c) => c.issues);
235
- out.push(` ${x.name} [${x.mark}]: ${mm(x.grams)} g, ${mm(x.margin)}× at its load, ${bad.length ? `${bad.length} print issue${bad.length > 1 ? 's' : ''}` : 'prints clean'}: for ${what}`);
515
+ out.push(
516
+ ` ${x.name} [${x.mark}]: ${mm(x.grams)} g, ${mm(x.margin)}× at its load, ${bad.length ? `${bad.length} print issue${bad.length > 1 ? 's' : ''}` : 'prints clean'}: for ${what}`,
517
+ );
236
518
  }
237
519
  for (const p of r.plates) out.push(` plate ${p.file}: ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}`);
238
520
  for (const f of r.findings) out.push(` [${f.level}] ${f.text}`);