@rulecad/cad 0.7.97 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/AGENTS.md +26 -10
  2. package/CHANGELOG.md +442 -2
  3. package/EXAMPLES.md +48 -42
  4. package/README.md +226 -73
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2253 -514
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1854 -437
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +734 -113
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +900 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2710 -502
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +792 -176
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +149 -18
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +3 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1022 -212
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +41 -0
  57. package/lib/optimise.mjs +979 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +224 -36
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +38 -4
  68. package/lib/sandbox-hooks.mjs +154 -12
  69. package/lib/sandbox-preload.mjs +2 -2
  70. package/lib/sandbox-run.mjs +127 -12
  71. package/lib/sandbox.mjs +632 -35
  72. package/lib/schema.mjs +43 -11
  73. package/lib/seats.mjs +227 -49
  74. package/lib/services.mjs +261 -52
  75. package/lib/sheet.mjs +851 -178
  76. package/lib/slotnuts.mjs +213 -34
  77. package/lib/targets/gist.mjs +4 -1
  78. package/lib/targets.mjs +42 -6
  79. package/lib/task.mjs +376 -79
  80. package/lib/versions.mjs +113 -28
  81. package/lib/wires.mjs +228 -45
  82. package/lib/workspace.mjs +216 -17
  83. package/package.json +19 -19
  84. package/schemas/assembly.schema.json +2 -2
  85. package/schemas/object.schema.json +1 -1
  86. package/schemas/project.schema.json +1 -1
package/lib/beams.mjs CHANGED
@@ -17,7 +17,16 @@ import * as frames from '@rulecad/frames';
17
17
  import fs from 'node:fs';
18
18
  import crypto from 'node:crypto';
19
19
  import path from 'node:path';
20
- import { beamModel, beam, beamAnchor, cutList, beamMarks, beamSheet, printedBeam, printedInPlace } from '@rulecad/frames';
20
+ import {
21
+ beamModel,
22
+ beam,
23
+ beamAnchor,
24
+ cutList,
25
+ beamMarks,
26
+ beamSheet,
27
+ printedBeam,
28
+ printedInPlace,
29
+ } from '@rulecad/frames';
21
30
  import { frame } from '@rulecad/model-link';
22
31
  import { RULE_DIRS, paths } from './workspace.mjs';
23
32
  import { named } from './parts.mjs';
@@ -39,32 +48,80 @@ export const framesContext = () => contextIn(RULE_DIRS[0]);
39
48
  * @param {object} it the item @param {(x: any) => number} num the assembly's expressions @param {object} [context] framesContext()'s
40
49
  */
41
50
  export function beamOf(it, num, context = framesContext()) {
42
- const what = `item ${it.id}`, b = it.beam;
43
- if (!b || typeof b !== 'object' || Array.isArray(b)) throw new Error(`${what}: beam is { "profile", "length", "material" } (got ${shown(b)})`);
44
- for (const k of Object.keys(b)) if (!KEYS.includes(k)) throw new Error(`${what}: a beam has no "${k}": it takes ${KEYS.join(', ')}`);
45
- if (typeof b.profile !== 'string' || !b.profile) throw new Error(`${what}: beam.profile names a profile, such as 2020-misumi-hfs5 (got ${shown(b.profile)})`);
46
- if (b.printed != null && typeof b.printed !== 'boolean' && (typeof b.printed !== 'object' || Array.isArray(b.printed))) throw new Error(`${what}: beam.printed is true, false, or how it prints: { "pose": "lying", "walls": 3, "infill": 0.4, "end": "insert" } (got ${shown(b.printed)})`);
47
- if (b.laid != null && (typeof b.laid !== 'boolean' || (b.laid && !b.printed))) throw new Error(`${what}: beam.laid draws a printed beam as it prints: true or false, with printed (got ${shown(b.laid)}${b.printed ? '' : ' on a bought beam'})`);
48
- if (b.ops != null && !Array.isArray(b.ops)) throw new Error(`${what}: beam.ops is a list of operations, [{ "op": "tap", "at": "a" }] (got ${shown(b.ops)})`);
51
+ const what = `item ${it.id}`,
52
+ b = it.beam;
53
+ if (!b || typeof b !== 'object' || Array.isArray(b))
54
+ throw new Error(`${what}: beam is { "profile", "length", "material" } (got ${shown(b)})`);
55
+ for (const k of Object.keys(b))
56
+ if (!KEYS.includes(k)) throw new Error(`${what}: a beam has no "${k}": it takes ${KEYS.join(', ')}`);
57
+ if (typeof b.profile !== 'string' || !b.profile)
58
+ throw new Error(`${what}: beam.profile names a profile, such as 2020-misumi-hfs5 (got ${shown(b.profile)})`);
59
+ if (
60
+ b.printed != null &&
61
+ typeof b.printed !== 'boolean' &&
62
+ (typeof b.printed !== 'object' || Array.isArray(b.printed))
63
+ )
64
+ throw new Error(
65
+ `${what}: beam.printed is true, false, or how it prints: { "pose": "lying", "walls": 3, "infill": 0.4, "end": "insert" } (got ${shown(b.printed)})`,
66
+ );
67
+ if (b.laid != null && (typeof b.laid !== 'boolean' || (b.laid && !b.printed)))
68
+ throw new Error(
69
+ `${what}: beam.laid draws a printed beam as it prints: true or false, with printed (got ${shown(b.laid)}${b.printed ? '' : ' on a bought beam'})`,
70
+ );
71
+ if (b.ops != null && !Array.isArray(b.ops))
72
+ throw new Error(`${what}: beam.ops is a list of operations, [{ "op": "tap", "at": "a" }] (got ${shown(b.ops)})`);
49
73
  // an operation's numbers may be expressions, as a length is
50
- const ops = (b.ops ?? []).map((o) => (o && typeof o === 'object' && !Array.isArray(o) ? Object.fromEntries(Object.entries(o).map(([k, v]) => [k, OP_NUMBERS.includes(k) && v != null ? num(v) : k === 'size' && Array.isArray(v) ? v.map(num) : v])) : o));
51
- if (b.material != null && typeof b.material !== 'string') throw new Error(`${what}: beam.material is a material set's name, such as al6063-t5 (got ${shown(b.material)})`);
74
+ const ops = (b.ops ?? []).map((o) =>
75
+ o && typeof o === 'object' && !Array.isArray(o)
76
+ ? Object.fromEntries(
77
+ Object.entries(o).map(([k, v]) => [
78
+ k,
79
+ OP_NUMBERS.includes(k) && v != null ? num(v) : k === 'size' && Array.isArray(v) ? v.map(num) : v,
80
+ ]),
81
+ )
82
+ : o,
83
+ );
84
+ if (b.material != null && typeof b.material !== 'string')
85
+ throw new Error(`${what}: beam.material is a material set's name, such as al6063-t5 (got ${shown(b.material)})`);
52
86
  const ends = it.from != null || it.to != null;
53
- if (ends && (it.from == null || it.to == null)) throw new Error(`${what}: a beam placed by its ends gives both: from (end a) and to (end b)`);
54
- if (ends && (it.at != null || it.rotate != null)) throw new Error(`${what}: a beam is placed by its ends (from, to, roll) or by at and rotate, not both`);
55
- if (!ends && it.roll != null) throw new Error(`${what}: roll turns a beam placed by its ends: give from and to, or turn it with rotate`);
56
- if (ends && it.repeat) throw new Error(`${what}: a beam placed by its ends is one beam: give each its own item, or place it with at and repeat`);
57
- for (const k of ['from', 'to']) if (ends && !(Array.isArray(it[k]) && it[k].length === 3)) throw new Error(`${what}: ${k} is a point, [x, y, z] (got ${shown(it[k])})`);
87
+ if (ends && (it.from == null || it.to == null))
88
+ throw new Error(`${what}: a beam placed by its ends gives both: from (end a) and to (end b)`);
89
+ if (ends && (it.at != null || it.rotate != null))
90
+ throw new Error(`${what}: a beam is placed by its ends (from, to, roll) or by at and rotate, not both`);
91
+ if (!ends && it.roll != null)
92
+ throw new Error(`${what}: roll turns a beam placed by its ends: give from and to, or turn it with rotate`);
93
+ if (ends && it.repeat)
94
+ throw new Error(
95
+ `${what}: a beam placed by its ends is one beam: give each its own item, or place it with at and repeat`,
96
+ );
97
+ for (const k of ['from', 'to'])
98
+ if (ends && !(Array.isArray(it[k]) && it[k].length === 3))
99
+ throw new Error(`${what}: ${k} is a point, [x, y, z] (got ${shown(it[k])})`);
58
100
  const span = ends ? Math.hypot(...[0, 1, 2].map((i) => num(it.to[i]) - num(it.from[i]))) : null;
59
- if (b.length == null && span == null) throw new Error(`${what}: give the beam a length, or place it by its ends (from and to) so the length is theirs`);
101
+ if (b.length == null && span == null)
102
+ throw new Error(`${what}: give the beam a length, or place it by its ends (from and to) so the length is theirs`);
60
103
  const length = b.length != null ? num(b.length) : span;
61
- if (!(Number.isFinite(length) && length > 0)) throw new Error(`${what}: a beam's length is above 0 mm (got ${shown(b.length ?? length)}${b.length == null ? ': its ends are at one point' : ''})`);
62
- if (span != null && Math.abs(span - length) > 1e-3) throw new Error(`${what}: its length is ${mm(length)} mm, and its ends are ${mm(span)} mm apart: leave the length out, or move an end`);
104
+ if (!(Number.isFinite(length) && length > 0))
105
+ throw new Error(
106
+ `${what}: a beam's length is above 0 mm (got ${shown(b.length ?? length)}${b.length == null ? ': its ends are at one point' : ''})`,
107
+ );
108
+ if (span != null && Math.abs(span - length) > 1e-3)
109
+ throw new Error(
110
+ `${what}: its length is ${mm(length)} mm, and its ends are ${mm(span)} mm apart: leave the length out, or move an end`,
111
+ );
63
112
  const given = givenFor(context, b.profile);
64
113
  let model;
65
114
  try {
66
- model = beamModel(frames.profileModel(b.profile, {}, given), { length, ...(b.material ? { material: b.material } : {}), ...(ops.length ? { ops } : {}), ...(b.printed ? { printed: b.printed } : {}), given });
67
- } catch (e) { throw new Error(`${what}: ${strip(e)}`); }
115
+ model = beamModel(frames.profileModel(b.profile, {}, given), {
116
+ length,
117
+ ...(b.material ? { material: b.material } : {}),
118
+ ...(ops.length ? { ops } : {}),
119
+ ...(b.printed ? { printed: b.printed } : {}),
120
+ given,
121
+ });
122
+ } catch (e) {
123
+ throw new Error(`${what}: ${strip(e)}`);
124
+ }
68
125
  return { model, length };
69
126
  }
70
127
 
@@ -75,12 +132,25 @@ export function beamOf(it, num, context = framesContext()) {
75
132
  */
76
133
  export function beamPlace(it, num) {
77
134
  if (it.from == null) return null;
78
- const a = it.from.map(num), b = it.to.map(num), z = b.map((v, k) => v - a[k]), l = Math.hypot(...z), u = z.map((v) => v / l);
79
- const up = Math.abs(u[2]) > Math.cos(0.1 * Math.PI / 180) ? [0, 1, 0] : [0, 0, 1], d = up[0] * u[0] + up[1] * u[1] + up[2] * u[2];
80
- const yl = up.map((v, k) => v - d * u[k]), n = Math.hypot(...yl), y = yl.map((v) => v / n);
135
+ const a = it.from.map(num),
136
+ b = it.to.map(num),
137
+ z = b.map((v, k) => v - a[k]),
138
+ l = Math.hypot(...z),
139
+ u = z.map((v) => v / l);
140
+ const up = Math.abs(u[2]) > Math.cos((0.1 * Math.PI) / 180) ? [0, 1, 0] : [0, 0, 1],
141
+ d = up[0] * u[0] + up[1] * u[1] + up[2] * u[2];
142
+ const yl = up.map((v, k) => v - d * u[k]),
143
+ n = Math.hypot(...yl),
144
+ y = yl.map((v) => v / n);
81
145
  const x = [y[1] * u[2] - y[2] * u[1], y[2] * u[0] - y[0] * u[2], y[0] * u[1] - y[1] * u[0]]; // y × z
82
- const r = (it.roll != null ? num(it.roll) : 0) * Math.PI / 180, c = Math.cos(r), s = Math.sin(r);
83
- return frame(a, u, x.map((v, k) => c * v + s * y[k]));
146
+ const r = ((it.roll != null ? num(it.roll) : 0) * Math.PI) / 180,
147
+ c = Math.cos(r),
148
+ s = Math.sin(r);
149
+ return frame(
150
+ a,
151
+ u,
152
+ x.map((v, k) => c * v + s * y[k]),
153
+ );
84
154
  }
85
155
 
86
156
  /**
@@ -92,29 +162,104 @@ export function beamBuilt(it, num, id, context = framesContext()) {
92
162
  const { model: m, length } = beamOf(it, num, context);
93
163
  if (m.printed) return printedBuilt(it, m, id);
94
164
  const meta = { body: { label: `${m.profile.name} x ${mm(length)} mm` } };
95
- const parts = named({ body: beam(m) }, meta), link = named({ body: beam(m, { display: 'link', tracks: true }) }, meta)[0];
165
+ const parts = named({ body: beam(m) }, meta),
166
+ link = named({ body: beam(m, { display: 'link', tracks: true }) }, meta)[0];
96
167
  parts[0].collide = link.geometry; // (the overlap check measures the envelope, light, less any V tracks: a V-wheel's rim runs in them, and a rim out of them hits the beam)
97
- const anchors = Object.fromEntries(Object.entries(m.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis, ref: a.ref }]));
98
- const values = { length, width: m.profile.width, height: m.profile.height, area: m.area, ...(m.mass != null ? { mass: m.mass } : {}) };
99
- const entries = Object.entries(m.profile.figures).filter(([, f]) => typeof f?.value === 'number').map(([k, f]) => ({ name: `${m.profile.name}.${k}`, value: f.value, unit: f.unit, rule: f.rule, kind: f.kind, source: f.source, checked: f.checked, set: m.profile.name }));
168
+ const anchors = Object.fromEntries(
169
+ Object.entries(m.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis, ref: a.ref }]),
170
+ );
171
+ const values = {
172
+ length,
173
+ width: m.profile.width,
174
+ height: m.profile.height,
175
+ area: m.area,
176
+ ...(m.mass != null ? { mass: m.mass } : {}),
177
+ };
178
+ const entries = Object.entries(m.profile.figures)
179
+ .filter(([, f]) => typeof f?.value === 'number')
180
+ .map(([k, f]) => ({
181
+ name: `${m.profile.name}.${k}`,
182
+ value: f.value,
183
+ unit: f.unit,
184
+ rule: f.rule,
185
+ kind: f.kind,
186
+ source: f.source,
187
+ checked: f.checked,
188
+ set: m.profile.name,
189
+ }));
100
190
  const grams = m.weight.sheet ?? m.mass; // (weighed by the sheet where it gives a mass per metre: a light section's drawn outline can be 10 to 20% heavy)
101
- return referenceBuilt({ id, key: 'beam', objName: `beam:${m.profile.name}`, name: m.profile.name, parts, anchors, entries, values,
102
- extra: { beam: m, bought: { set: m.profile.name, variant: null, part: 'beam', mass: grams != null ? grams / 1000 : null, length } } });
191
+ return referenceBuilt({
192
+ id,
193
+ key: 'beam',
194
+ objName: `beam:${m.profile.name}`,
195
+ name: m.profile.name,
196
+ parts,
197
+ anchors,
198
+ entries,
199
+ values,
200
+ extra: {
201
+ beam: m,
202
+ bought: { set: m.profile.name, variant: null, part: 'beam', mass: grams != null ? grams / 1000 : null, length },
203
+ },
204
+ });
103
205
  }
104
206
 
105
207
  // A printed beam, built: a printed part, solid, in its place (or laid as it prints, for a plate), its part's fill the share
106
208
  // of its section the walls and infill lay (cad list weighs it by that), its anchors and figures as a bought beam's
107
209
  function printedBuilt(it, m, id) {
108
- const sec = m.printed.section, laid = !!it.beam.laid, label = `${m.profile.name} x ${mm(m.length)} mm, printed ${m.printed.pose === 'lying' ? 'lying down' : 'standing up'}`;
210
+ const sec = m.printed.section,
211
+ laid = !!it.beam.laid,
212
+ label = `${m.profile.name} x ${mm(m.length)} mm, printed ${m.printed.pose === 'lying' ? 'lying down' : 'standing up'}`;
109
213
  const parts = named({ body: laid ? printedBeam(m) : printedInPlace(m) }, { body: { label } }); // (in its place, its ends' inserts or nuts cut in, as a screw into them is checked)
110
214
  parts[0].fill = +(sec.plastic / sec.solid.area).toFixed(4);
111
- if (!laid) parts[0].collide = named({ body: printedInPlace(m, { display: 'link' }) }, { body: { label } })[0].geometry;
112
- const anchors = laid ? {} : Object.fromEntries(Object.entries(m.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis, ref: a.ref }]));
113
- const values = { length: m.length, width: m.profile.width, height: m.profile.height, grams: m.mass, design: m.printed.design };
114
- const entries = Object.entries(m.figures).filter(([, f]) => typeof f?.value === 'number').map(([k, f]) => ({ name: `${m.profile.name}.printed.${k}`, value: f.value, unit: f.unit, rule: `The printed beam's ${k}, from its walls and infill`, kind: f.kind, source: f.source, checked: '2026-11-17', set: m.profile.name }));
115
- const hash = crypto.createHash('sha256').update(JSON.stringify([it.beam, m.name, m.mass, laid])).digest('hex').slice(0, 16);
116
- const b = { object: { name: m.name, title: label, role: 'part', version: '0.0.0', anchors }, values, entries, deps: [], units: {}, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash };
117
- return { key: `beam:${id}:${hash}`, objName: `beam:${m.profile.name}:printed`, b, version: '0.0.0', role: 'part', beam: m };
215
+ if (!laid)
216
+ parts[0].collide = named({ body: printedInPlace(m, { display: 'link' }) }, { body: { label } })[0].geometry;
217
+ const anchors = laid
218
+ ? {}
219
+ : Object.fromEntries(Object.entries(m.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis, ref: a.ref }]));
220
+ const values = {
221
+ length: m.length,
222
+ width: m.profile.width,
223
+ height: m.profile.height,
224
+ grams: m.mass,
225
+ design: m.printed.design,
226
+ };
227
+ const entries = Object.entries(m.figures)
228
+ .filter(([, f]) => typeof f?.value === 'number')
229
+ .map(([k, f]) => ({
230
+ name: `${m.profile.name}.printed.${k}`,
231
+ value: f.value,
232
+ unit: f.unit,
233
+ rule: `The printed beam's ${k}, from its walls and infill`,
234
+ kind: f.kind,
235
+ source: f.source,
236
+ checked: '2026-11-17',
237
+ set: m.profile.name,
238
+ }));
239
+ const hash = crypto
240
+ .createHash('sha256')
241
+ .update(JSON.stringify([it.beam, m.name, m.mass, laid]))
242
+ .digest('hex')
243
+ .slice(0, 16);
244
+ const b = {
245
+ object: { name: m.name, title: label, role: 'part', version: '0.0.0', anchors },
246
+ values,
247
+ entries,
248
+ deps: [],
249
+ units: {},
250
+ parts,
251
+ polygons: parts.flatMap((p) => p.polygons),
252
+ triangles: parts.flatMap((p) => p.triangles),
253
+ hash,
254
+ };
255
+ return {
256
+ key: `beam:${id}:${hash}`,
257
+ objName: `beam:${m.profile.name}:printed`,
258
+ b,
259
+ version: '0.0.0',
260
+ role: 'part',
261
+ beam: m,
262
+ };
118
263
  }
119
264
 
120
265
  /**
@@ -124,7 +269,25 @@ function printedBuilt(it, m, id) {
124
269
  */
125
270
  export function laidSpec(it, num, length) {
126
271
  const { profile, printed, material, ops } = it.beam;
127
- return { profile, length, printed, ...(material ? { material } : {}), ...(ops?.length ? { ops: ops.map((o) => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, OP_NUMBERS.includes(k) && v != null ? num(v) : k === 'size' && Array.isArray(v) ? v.map(num) : v]))) } : {}), laid: true };
272
+ return {
273
+ profile,
274
+ length,
275
+ printed,
276
+ ...(material ? { material } : {}),
277
+ ...(ops?.length
278
+ ? {
279
+ ops: ops.map((o) =>
280
+ Object.fromEntries(
281
+ Object.entries(o).map(([k, v]) => [
282
+ k,
283
+ OP_NUMBERS.includes(k) && v != null ? num(v) : k === 'size' && Array.isArray(v) ? v.map(num) : v,
284
+ ]),
285
+ ),
286
+ ),
287
+ }
288
+ : {}),
289
+ laid: true,
290
+ };
128
291
  }
129
292
 
130
293
  /**
@@ -134,28 +297,47 @@ export function laidSpec(it, num, length) {
134
297
  */
135
298
  export function beamAddress(m, address, what) {
136
299
  let a;
137
- try { a = beamAnchor(m, address); } catch (e) { throw new Error(`${what}: ${strip(e)}`); }
300
+ try {
301
+ a = beamAnchor(m, address);
302
+ } catch (e) {
303
+ throw new Error(`${what}: ${strip(e)}`);
304
+ }
138
305
  return frame(a.origin, a.axis, a.ref);
139
306
  }
140
307
 
141
308
  /** The assembly's bought beams, nested ones too, as { id, beam } for @rulecad/frames' cut list. @param {object} s a built assembly */
142
- export const beamsIn = (s) => s.objects.filter((o) => o.beam && !o.beam.printed && !o.unplaced).map((o) => ({ id: o.id, beam: o.beam })); // (a printed beam is printed, not cut)
309
+ export const beamsIn = (s) =>
310
+ s.objects.filter((o) => o.beam && !o.beam.printed && !o.unplaced).map((o) => ({ id: o.id, beam: o.beam })); // (a printed beam is printed, not cut)
143
311
 
144
312
  /** Each beam's mark: beams that are the same share one (A, B, ...), as the cut list and the sheets name them. @returns {Map<string, string>} item to mark */
145
313
  export function marksOf(objects) {
146
- const list = objects.filter((o) => o.beam && !o.beam.printed && !o.unplaced), out = new Map();
147
- if (list.length) for (const m of beamMarks(list.map((o) => ({ id: o.id, beam: o.beam })))) for (const id of m.items) out.set(id, m.mark);
314
+ const list = objects.filter((o) => o.beam && !o.beam.printed && !o.unplaced),
315
+ out = new Map();
316
+ if (list.length)
317
+ for (const m of beamMarks(list.map((o) => ({ id: o.id, beam: o.beam }))))
318
+ for (const id of m.items) out.set(id, m.mark);
148
319
  return out;
149
320
  }
150
321
 
151
322
  /** The cut list of an assembly's beams (frames' cutList), or null where it has none. @param {object} s a built assembly */
152
323
  export function cutListOf(s) {
153
- const b = beamsIn(s), t = s.a?.frame?.cut?.tolerance;
154
- return b.length ? cutList(b, t != null && Number.isFinite(s.num(t)) && s.num(t) >= 0 ? { tolerance: s.num(t) } : {}) : null; // (the workshop's own tolerance, frame.cut; refused by name in frame.square)
324
+ const b = beamsIn(s),
325
+ t = s.a?.frame?.cut?.tolerance;
326
+ return b.length
327
+ ? cutList(b, t != null && Number.isFinite(s.num(t)) && s.num(t) >= 0 ? { tolerance: s.num(t) } : {})
328
+ : null; // (the workshop's own tolerance, frame.cut; refused by name in frame.square)
155
329
  }
156
330
 
157
331
  /** The cut list as the list and the build page keep it: no beam models, the numbers and words only. */
158
- export const cutListData = (c) => c && { marks: c.marks.map(({ beam, ...m }) => m), stock: c.stock, totals: c.totals, rules: Object.fromEntries(Object.entries(c.rules).map(([k, r]) => [k, { value: r.value, unit: r.unit, kind: r.kind }])) };
332
+ export const cutListData = (c) =>
333
+ c && {
334
+ marks: c.marks.map(({ beam, ...m }) => m),
335
+ stock: c.stock,
336
+ totals: c.totals,
337
+ rules: Object.fromEntries(
338
+ Object.entries(c.rules).map(([k, r]) => [k, { value: r.value, unit: r.unit, kind: r.kind }]),
339
+ ),
340
+ };
159
341
 
160
342
  /** The sheet files cad beams writes for an assembly, by mark: exports/<project>/<assembly>.beam-<mark>.svg */
161
343
  export const sheetFile = (s, mark) => paths.exports(s.project, `${s.name}.beam-${mark}.svg`);
@@ -165,16 +347,38 @@ export const sheetFile = (s, mark) => paths.exports(s.project, `${s.name}.beam-$
165
347
  * assembly removed. @param {object} s a built assembly @returns {{ mark: string, file: string, items: string[], scale: number }[]}
166
348
  */
167
349
  export function writeBeamSheets(s) {
168
- const c = cutListOf(s), dir = paths.exports(s.project), base = `${s.name}.beam-`;
169
- if (fs.existsSync(dir)) for (const f of fs.readdirSync(dir)) if (f.startsWith(base) && f.endsWith('.svg')) fs.rmSync(path.join(dir, f));
350
+ const c = cutListOf(s),
351
+ dir = paths.exports(s.project),
352
+ base = `${s.name}.beam-`;
353
+ if (fs.existsSync(dir))
354
+ for (const f of fs.readdirSync(dir)) if (f.startsWith(base) && f.endsWith('.svg')) fs.rmSync(path.join(dir, f));
170
355
  if (!c) return [];
171
356
  fs.mkdirSync(dir, { recursive: true });
172
- return c.marks.map((m) => { const sh = beamSheet(m.beam, { mark: m.mark, items: m.items, grams: m.grams }), file = sheetFile(s, m.mark); fs.writeFileSync(file, sh.svg); return { mark: m.mark, file, items: m.items, scale: sh.scale }; });
357
+ return c.marks.map((m) => {
358
+ const sh = beamSheet(m.beam, { mark: m.mark, items: m.items, grams: m.grams }),
359
+ file = sheetFile(s, m.mark);
360
+ fs.writeFileSync(file, sh.svg);
361
+ return { mark: m.mark, file, items: m.items, scale: sh.scale };
362
+ });
173
363
  }
174
364
 
175
365
  /** Each beam's own findings (its mass beside the sheet's, its length beside the stock's), named by item; and the cut list's (frame.cut). */
176
366
  export function beamFindings(s, f) {
177
- for (const o of s.objects) if (o.beam && !o.unplaced) for (const x of o.beam.findings) f(x.level, `${o.id}: ${x.text}`, null, { code: x.code, ...(x.values ? { values: x.values } : {}), refs: { item: o.id, profile: o.beam.profile.name, length: o.beam.length, ...(x.rule ? { rule: x.rule } : {}) } });
367
+ for (const o of s.objects)
368
+ if (o.beam && !o.unplaced)
369
+ for (const x of o.beam.findings)
370
+ f(x.level, `${o.id}: ${x.text}`, null, {
371
+ code: x.code,
372
+ ...(x.values ? { values: x.values } : {}),
373
+ refs: {
374
+ item: o.id,
375
+ profile: o.beam.profile.name,
376
+ length: o.beam.length,
377
+ ...(x.rule ? { rule: x.rule } : {}),
378
+ },
379
+ });
178
380
  const c = cutListOf(s);
179
- if (c) for (const x of c.findings) f(x.level, x.text, null, { code: x.code, ...(x.values ? { values: x.values } : {}), refs: x.refs });
381
+ if (c)
382
+ for (const x of c.findings)
383
+ f(x.level, x.text, null, { code: x.code, ...(x.values ? { values: x.values } : {}), refs: x.refs });
180
384
  }
package/lib/belts.mjs CHANGED
@@ -9,13 +9,29 @@ import { massesOf, beyond } from './loads.mjs';
9
9
  import { axisOf } from './motors.mjs';
10
10
 
11
11
  const G = 9.80665;
12
- const invAt = (W, p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
12
+ const invAt = (W, p) => {
13
+ const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]];
14
+ return [
15
+ W[0] * q[0] + W[4] * q[1] + W[8] * q[2],
16
+ W[1] * q[0] + W[5] * q[1] + W[9] * q[2],
17
+ W[2] * q[0] + W[6] * q[1] + W[10] * q[2],
18
+ ];
19
+ };
13
20
 
14
21
  // An item's box in the belt's own frame (the face's: x along the beam from end a, y across, z over the face), from its
15
22
  // drawn triangles, which are in the world at the motion's pose
16
23
  function boxIn(W, parts) {
17
- const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
18
- for (const p of parts) for (const t of p.triangles) for (const v of t) { const q = invAt(W, v); for (let k = 0; k < 3; k++) { lo[k] = Math.min(lo[k], q[k]); hi[k] = Math.max(hi[k], q[k]); } }
24
+ const lo = [Infinity, Infinity, Infinity],
25
+ hi = [-Infinity, -Infinity, -Infinity];
26
+ for (const p of parts)
27
+ for (const t of p.triangles)
28
+ for (const v of t) {
29
+ const q = invAt(W, v);
30
+ for (let k = 0; k < 3; k++) {
31
+ lo[k] = Math.min(lo[k], q[k]);
32
+ hi[k] = Math.max(hi[k], q[k]);
33
+ }
34
+ }
19
35
  return Number.isFinite(lo[0]) ? { lo, hi } : null;
20
36
  }
21
37
 
@@ -24,39 +40,74 @@ function boxIn(W, parts) {
24
40
  * @param {object} s a built assembly @param {{ placeItems: Function, jointValues: Function, mul: Function }} helpers
25
41
  */
26
42
  export function beltLoads(s, helpers) {
27
- const motion = s.motion, belts = (s.guides ?? []).filter((x) => x.kind === 'belt');
43
+ const motion = s.motion,
44
+ belts = (s.guides ?? []).filter((x) => x.kind === 'belt');
28
45
  if (!motion || !belts.length) return;
29
- const ids = motion.items.map((x) => x[0]), masses = massesOf(s, helpers), worlds = helpers.placeItems(motion, helpers.jointValues(motion, motion.pose ?? undefined));
30
- const g = motion.gravity || [0, 0, -1], gn = Math.hypot(...g);
46
+ const ids = motion.items.map((x) => x[0]),
47
+ masses = massesOf(s, helpers),
48
+ worlds = helpers.placeItems(motion, helpers.jointValues(motion, motion.pose ?? undefined));
49
+ const g = motion.gravity || [0, 0, -1],
50
+ gn = Math.hypot(...g);
31
51
  for (const r of belts) {
32
52
  const j = motion.joints.find((x) => x.id === r.joints[0]);
33
53
  if (!j) continue;
34
54
  let kg = 0;
35
55
  for (const q of masses) if (beyond(motion, j, q.item)) kg += q.kg;
36
56
  const own = kg; // (the parts' own: the carriage, the clamp, what is drawn on them; the loads' masses the motor checks have)
37
- for (const l of motion.loads ?? []) if (l.mass != null && !l.belt) { const k = typeof l.item === 'number' ? l.item : ids.indexOf(l.item); if (beyond(motion, j, k)) kg += l.mass; }
57
+ for (const l of motion.loads ?? [])
58
+ if (l.mass != null && !l.belt) {
59
+ const k = typeof l.item === 'number' ? l.item : ids.indexOf(l.item);
60
+ if (beyond(motion, j, k)) kg += l.mass;
61
+ }
38
62
  const tool = s.task?.item != null ? ids.indexOf(s.task.item) : -1;
39
63
  if (s.task?.payload && tool >= 0 && beyond(motion, j, tool)) kg += s.task.payload;
40
- const accel = r.accel ?? s.task?.accel ?? BELT_DEFAULTS.accel.value, force = (kg * accel) / 1000;
64
+ const accel = r.accel ?? s.task?.accel ?? BELT_DEFAULTS.accel.value,
65
+ force = (kg * accel) / 1000;
41
66
  // the weight's part along the travel: kg × g × the cosine between the slide and gravity (0 on a level axis)
42
- const { Z } = axisOf(motion, worlds, j, helpers.mul), cos = (Z[0] * g[0] + Z[1] * g[1] + Z[2] * g[2]) / (Math.hypot(...Z) * gn), along = Math.abs(cos) > 1e-9 ? cos : 0, weight = kg * G * Math.abs(along);
43
- Object.assign(r, { carried: kg, accelUsed: accel, accelFrom: r.accel != null ? 'the guide' : s.task?.accel != null ? 'the task' : 'BELT_DEFAULTS.accel', force, weight });
67
+ const { Z } = axisOf(motion, worlds, j, helpers.mul),
68
+ cos = (Z[0] * g[0] + Z[1] * g[1] + Z[2] * g[2]) / (Math.hypot(...Z) * gn),
69
+ along = Math.abs(cos) > 1e-9 ? cos : 0,
70
+ weight = kg * G * Math.abs(along);
71
+ Object.assign(r, {
72
+ carried: kg,
73
+ accelUsed: accel,
74
+ accelFrom: r.accel != null ? 'the guide' : s.task?.accel != null ? 'the task' : 'BELT_DEFAULTS.accel',
75
+ force,
76
+ weight,
77
+ });
44
78
  // the push, either way along the travel (motors.mjs adds it in the worse direction); off level, the parts' own weight
45
79
  // along it too, signed as gravity's (the declared loads' weight the motor checks read from their masses)
46
- motion.loads = [...(motion.loads ?? []).filter((l) => l.belt !== r.id && l.beltWeight !== r.id), { joint: j.id, value: force, note: `${r.id}: ${(kg * 1000).toFixed(0)} g pushed at ${accel} mm/s²`, belt: r.id },
47
- ...(along && own ? [{ joint: j.id, value: own * G * along, note: `${r.id}: the carriage's own ${(own * 1000).toFixed(0)} g along the travel`, beltWeight: r.id }] : [])];
80
+ motion.loads = [
81
+ ...(motion.loads ?? []).filter((l) => l.belt !== r.id && l.beltWeight !== r.id),
82
+ { joint: j.id, value: force, note: `${r.id}: ${(kg * 1000).toFixed(0)} g pushed at ${accel} mm/s²`, belt: r.id },
83
+ ...(along && own
84
+ ? [
85
+ {
86
+ joint: j.id,
87
+ value: own * G * along,
88
+ note: `${r.id}: the carriage's own ${(own * 1000).toFixed(0)} g along the travel`,
89
+ beltWeight: r.id,
90
+ },
91
+ ]
92
+ : []),
93
+ ];
48
94
  if (j.slide?.stretch) Object.assign(j.slide.stretch, { load: force + weight, length: r.layout.span });
49
95
  // what else the carriage carries, by its box: held against the belt's runs through the travel (belt.rub), as the
50
96
  // beam, the rail, the carriage and the clamp are
51
- const kb = ids.indexOf(r.items.belt), kc = ids.indexOf(r.carriage), mine = new Set([r.carriage, r.items.clamp, r.items.belt]), partsOf = (id) => s.parts.filter((p) => p.item === id && p.role !== 'support' && p.triangles?.length);
97
+ const kb = ids.indexOf(r.items.belt),
98
+ kc = ids.indexOf(r.carriage),
99
+ mine = new Set([r.carriage, r.items.clamp, r.items.belt]),
100
+ partsOf = (id) => s.parts.filter((p) => p.item === id && p.role !== 'support' && p.triangles?.length);
52
101
  const cbox = kb >= 0 && kc >= 0 ? boxIn(worlds[kb], partsOf(r.carriage)) : null;
53
102
  if (!cbox) continue;
54
- const xc = (cbox.lo[0] + cbox.hi[0]) / 2, carried = [];
103
+ const xc = (cbox.lo[0] + cbox.hi[0]) / 2,
104
+ carried = [];
55
105
  ids.forEach((id, k) => {
56
106
  if (mine.has(id) || !beyond(motion, j, k)) return;
57
107
  const b = boxIn(worlds[kb], partsOf(id));
58
108
  if (b) carried.push({ part: id, lo: [b.lo[0] - xc, b.lo[1], b.lo[2]], hi: [b.hi[0] - xc, b.hi[1], b.hi[2]] });
59
109
  });
60
- if (carried.length) Object.assign(r, { rub: beltRub(r.layout, { carried }), carriedParts: carried.map((x) => x.part) });
110
+ if (carried.length)
111
+ Object.assign(r, { rub: beltRub(r.layout, { carried }), carriedParts: carried.map((x) => x.part) });
61
112
  }
62
113
  }
@@ -0,0 +1,12 @@
1
+ // The tool's own work on a sandboxed board design's circuit, in a thread of its own (design.mjs boardWork): making the
2
+ // board's solid (pcb solids) and checking it (pcb checks). The circuit is the design's to say, and both take far
3
+ // longer the more it holds: drilling 1000 holes nearly two minutes, checking 1000 tracks laid over each other more
4
+ // than a minute (each against every other). A design that hands back thousands would otherwise keep the tool itself
5
+ // busy for hours after its own process had ended inside its time limit. Here the thread can be stopped at that limit,
6
+ // and holds no more memory than the design may.
7
+ import { parentPort, workerData } from 'node:worker_threads';
8
+
9
+ const pcb = await import('@rulecad/pcb');
10
+ const { job, args } = workerData;
11
+ if (job !== 'solids' && job !== 'checks') throw new Error(`no such board job: ${job}`);
12
+ parentPort.postMessage(await pcb[job](...args));